Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(cdp): follow active pages in tab frontends

ldm094c5baa970e8
diff --git a/moli-protocol-server/src/cdp_frontend.rs b/moli-protocol-server/src/cdp_frontend.rs
index a5b5769ff..760280583 100644
--- a/moli-protocol-server/src/cdp_frontend.rs
+++ b/moli-protocol-server/src/cdp_frontend.rs
@@ -27,12 +27,23 @@ pub(crate) enum CdpFrontendControlRequest {
sink: CdpSocketSink,
completion_tx: oneshot::Sender<Result<u64>>,
},
+ AttachForegroundTab {
+ page_target_id: String,
+ sink: CdpSocketSink,
+ completion_tx: oneshot::Sender<Result<u64>>,
+ },
DetachBrowser {
frontend_id: u64,
},
DetachPage {
frontend_id: u64,
},
+ DetachForegroundTab {
+ frontend_id: u64,
+ },
+ ForegroundTabChanged {
+ page_target_id: String,
+ },
TargetDestroyed {
target_id: String,
},
@@ -113,6 +124,30 @@ impl CdpFrontendEndpoint {
}
}
+ pub(crate) async fn attach_foreground_tab(
+ &self,
+ page_target_id: String,
+ sink: CdpSocketSink,
+ ) -> Result<u64> {
+ if self.is_shutting_down() {
+ bail!("CDP target owner is shutting down");
+ }
+ let (completion_tx, completion_rx) = oneshot::channel();
+ self.control_tx
+ .send(CdpFrontendControlRequest::AttachForegroundTab {
+ page_target_id,
+ sink,
+ completion_tx,
+ })
+ .context("CDP target owner is no longer available")?;
+ tokio::select! {
+ biased;
+ _ = self.wait_for_shutdown() => bail!("CDP owner stopped before foreground tab attach"),
+ completion = completion_rx => completion
+ .context("CDP owner stopped before foreground tab attach")?,
+ }
+ }
+
pub(crate) async fn command(&self, frontend_id: u64, raw: String) -> bool {
tokio::select! {
biased;
@@ -133,6 +168,18 @@ impl CdpFrontendEndpoint {
.send(CdpFrontendControlRequest::DetachPage { frontend_id });
}
+ pub(crate) fn detach_foreground_tab(&self, frontend_id: u64) {
+ let _ = self
+ .control_tx
+ .send(CdpFrontendControlRequest::DetachForegroundTab { frontend_id });
+ }
+
+ pub(crate) fn foreground_tab_changed(&self, page_target_id: String) {
+ let _ = self
+ .control_tx
+ .send(CdpFrontendControlRequest::ForegroundTabChanged { page_target_id });
+ }
+
pub(crate) fn target_destroyed(&self, target_id: String) {
let _ = self
.control_tx
diff --git a/moli-protocol-server/src/cdp_frontend_router.rs b/moli-protocol-server/src/cdp_frontend_router.rs
index 0ee71a156..4d75a6ad9 100644
--- a/moli-protocol-server/src/cdp_frontend_router.rs
+++ b/moli-protocol-server/src/cdp_frontend_router.rs
@@ -7,6 +7,8 @@ use serde_json::Value;
use crate::{cdp_scheduler::ProtocolOutputSequence, cdp_writer::CdpSocketSink};
+pub(crate) use self::routing::ForegroundTabFrontendRoute;
+
use self::routing::CdpFrontendRoutingState;
mod routing;
@@ -65,6 +67,23 @@ impl CdpFrontendRouter {
.register_page_frontend(frontend_id, target_id, session_id, sink)
}
+ pub(crate) fn register_foreground_tab_frontend(
+ &self,
+ frontend_id: u64,
+ browser_context_id: Option<String>,
+ page_target_id: String,
+ session_id: String,
+ sink: CdpSocketSink,
+ ) -> Result<()> {
+ self.routing.lock().register_foreground_tab_frontend(
+ frontend_id,
+ browser_context_id,
+ page_target_id,
+ session_id,
+ sink,
+ )
+ }
+
pub(crate) fn unregister_browser_frontend(&self, frontend_id: u64) -> Option<String> {
self.routing.lock().unregister_browser_frontend(frontend_id)
}
@@ -73,6 +92,36 @@ impl CdpFrontendRouter {
self.routing.lock().unregister_page_frontend(frontend_id)
}
+ pub(crate) fn unregister_foreground_tab_frontend(&self, frontend_id: u64) -> Option<String> {
+ self.routing
+ .lock()
+ .unregister_foreground_tab_frontend(frontend_id)
+ }
+
+ pub(crate) fn foreground_tab_frontends_for_browser_context(
+ &self,
+ browser_context_id: Option<&str>,
+ ) -> Vec<ForegroundTabFrontendRoute> {
+ self.routing
+ .lock()
+ .foreground_tab_frontends_for_browser_context(browser_context_id)
+ }
+
+ pub(crate) fn replace_foreground_tab_frontend_base(
+ &self,
+ frontend_id: u64,
+ browser_context_id: Option<String>,
+ page_target_id: String,
+ session_id: String,
+ ) -> Result<String> {
+ self.routing.lock().replace_foreground_tab_frontend_base(
+ frontend_id,
+ browser_context_id,
+ page_target_id,
+ session_id,
+ )
+ }
+
pub(crate) fn unregister_page_frontends_for_target(&self, target_id: &str) {
self.routing
.lock()
diff --git a/moli-protocol-server/src/cdp_frontend_router/routing.rs b/moli-protocol-server/src/cdp_frontend_router/routing.rs
index 3df96f28b..e6cfa8023 100644
--- a/moli-protocol-server/src/cdp_frontend_router/routing.rs
+++ b/moli-protocol-server/src/cdp_frontend_router/routing.rs
@@ -10,6 +10,8 @@ mod frontend_registry;
mod output;
mod pending_commands;
+pub(crate) use frontend_registry::ForegroundTabFrontendRoute;
+
pub(super) struct CdpRoutedFrontend {
frontend_id: u64,
sink: CdpSocketSink,
@@ -55,6 +57,23 @@ impl CdpFrontendRoutingState {
.register_page_frontend(frontend_id, target_id, session_id, sink)
}
+ pub(super) fn register_foreground_tab_frontend(
+ &mut self,
+ frontend_id: u64,
+ browser_context_id: Option<String>,
+ page_target_id: String,
+ session_id: String,
+ sink: CdpSocketSink,
+ ) -> Result<()> {
+ self.frontends.register_foreground_tab_frontend(
+ frontend_id,
+ browser_context_id,
+ page_target_id,
+ session_id,
+ sink,
+ )
+ }
+
pub(super) fn unregister_browser_frontend(&mut self, frontend_id: u64) -> Option<String> {
let session_id = self.frontends.unregister_browser_frontend(frontend_id);
if session_id.is_some() {
@@ -71,6 +90,42 @@ impl CdpFrontendRoutingState {
session_id
}
+ pub(super) fn unregister_foreground_tab_frontend(
+ &mut self,
+ frontend_id: u64,
+ ) -> Option<String> {
+ let session_id = self
+ .frontends
+ .unregister_foreground_tab_frontend(frontend_id);
+ if session_id.is_some() {
+ self.pending_commands.remove_frontend(frontend_id);
+ }
+ session_id
+ }
+
+ pub(super) fn foreground_tab_frontends_for_browser_context(
+ &self,
+ browser_context_id: Option<&str>,
+ ) -> Vec<ForegroundTabFrontendRoute> {
+ self.frontends
+ .foreground_tab_frontends_for_browser_context(browser_context_id)
+ }
+
+ pub(super) fn replace_foreground_tab_frontend_base(
+ &mut self,
+ frontend_id: u64,
+ browser_context_id: Option<String>,
+ page_target_id: String,
+ session_id: String,
+ ) -> Result<String> {
+ self.frontends.replace_foreground_tab_frontend_base(
+ frontend_id,
+ browser_context_id,
+ page_target_id,
+ session_id,
+ )
+ }
+
pub(super) fn register_private_session(&mut self, session_id: String) -> Result<()> {
self.frontends.register_internal_control_session(session_id)
}
diff --git a/moli-protocol-server/src/cdp_frontend_router/routing/command.rs b/moli-protocol-server/src/cdp_frontend_router/routing/command.rs
index 054225b5b..46b0e5525 100644
--- a/moli-protocol-server/src/cdp_frontend_router/routing/command.rs
+++ b/moli-protocol-server/src/cdp_frontend_router/routing/command.rs
@@ -60,6 +60,21 @@ impl CdpFrontendRoutingState {
.and_then(Value::as_str)
.map(str::to_owned),
}
+ } else if client_session_id.is_none()
+ && self.frontends.is_foreground_tab_frontend(frontend_id)
+ && matches!(
+ method.as_str(),
+ "Target.setAutoAttach" | "Target.setDiscoverTargets" | "Target.setRemoteLocations"
+ )
+ {
+ PendingCommandEffect::ReplayForegroundTabTargetCommand {
+ method: method.clone(),
+ params: request
+ .params()
+ .cloned()
+ .map(Value::Object)
+ .unwrap_or_else(|| Value::Object(Default::default())),
+ }
} else {
PendingCommandEffect::None
};
diff --git a/moli-protocol-server/src/cdp_frontend_router/routing/frontend_registry.rs b/moli-protocol-server/src/cdp_frontend_router/routing/frontend_registry.rs
index 85a1d8bf7..06a8a892e 100644
--- a/moli-protocol-server/src/cdp_frontend_router/routing/frontend_registry.rs
+++ b/moli-protocol-server/src/cdp_frontend_router/routing/frontend_registry.rs
@@ -1,6 +1,7 @@
use std::collections::{HashMap, HashSet};
use anyhow::{Result, bail};
+use serde_json::Value;
use crate::cdp_writer::CdpSocketSink;
@@ -8,15 +9,26 @@ use crate::cdp_writer::CdpSocketSink;
pub(super) enum CdpSessionFrontendKind {
Browser,
Page,
+ ForegroundTab,
}
pub(super) struct CdpSessionFrontendRoute {
kind: CdpSessionFrontendKind,
target_id: Option<String>,
+ browser_context_id: Option<String>,
base_session_id: String,
+ replayable_target_commands: Vec<(String, Value)>,
sink: CdpSocketSink,
}
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub(crate) struct ForegroundTabFrontendRoute {
+ pub(crate) frontend_id: u64,
+ pub(crate) page_target_id: String,
+ pub(crate) base_session_id: String,
+ pub(crate) replayable_target_commands: Vec<(String, Value)>,
+}
+
#[derive(Clone)]
pub(super) struct FrontendSessionRoute {
pub(super) frontend_id: u64,
@@ -75,6 +87,7 @@ impl FrontendRegistry {
frontend_id,
CdpSessionFrontendKind::Browser,
None,
+ None,
session_id,
sink,
true,
@@ -92,6 +105,26 @@ impl FrontendRegistry {
frontend_id,
CdpSessionFrontendKind::Page,
Some(target_id),
+ None,
+ session_id,
+ sink,
+ false,
+ )
+ }
+
+ pub(super) fn register_foreground_tab_frontend(
+ &mut self,
+ frontend_id: u64,
+ browser_context_id: Option<String>,
+ page_target_id: String,
+ session_id: String,
+ sink: CdpSocketSink,
+ ) -> Result<()> {
+ self.register_session_frontend(
+ frontend_id,
+ CdpSessionFrontendKind::ForegroundTab,
+ Some(page_target_id),
+ browser_context_id,
session_id,
sink,
false,
@@ -103,6 +136,7 @@ impl FrontendRegistry {
frontend_id: u64,
kind: CdpSessionFrontendKind,
target_id: Option<String>,
+ browser_context_id: Option<String>,
session_id: String,
sink: CdpSocketSink,
may_claim_control_session: bool,
@@ -132,7 +166,9 @@ impl FrontendRegistry {
CdpSessionFrontendRoute {
kind,
target_id,
+ browser_context_id,
base_session_id: session_id,
+ replayable_target_commands: Vec::new(),
sink,
},
);
@@ -163,6 +199,14 @@ impl FrontendRegistry {
.map(|route| route.base_session_id)
}
+ pub(super) fn unregister_foreground_tab_frontend(
+ &mut self,
+ frontend_id: u64,
+ ) -> Option<String> {
+ self.unregister_session_frontend(frontend_id, CdpSessionFrontendKind::ForegroundTab)
+ .map(|route| route.base_session_id)
+ }
+
fn unregister_session_frontend(
&mut self,
frontend_id: u64,
@@ -187,17 +231,113 @@ impl FrontendRegistry {
.frontends
.iter()
.filter_map(|(frontend_id, route)| {
- (route.kind == CdpSessionFrontendKind::Page
- && route.target_id.as_deref() == Some(target_id))
+ (matches!(
+ route.kind,
+ CdpSessionFrontendKind::Page | CdpSessionFrontendKind::ForegroundTab
+ ) && route.target_id.as_deref() == Some(target_id))
.then_some(*frontend_id)
})
.collect::<Vec<_>>();
for frontend_id in &frontend_ids {
- self.unregister_page_frontend(*frontend_id);
+ match self.frontends.get(frontend_id).map(|route| route.kind) {
+ Some(CdpSessionFrontendKind::Page) => {
+ self.unregister_page_frontend(*frontend_id);
+ }
+ Some(CdpSessionFrontendKind::ForegroundTab) => {
+ self.unregister_foreground_tab_frontend(*frontend_id);
+ }
+ Some(CdpSessionFrontendKind::Browser) | None => {}
+ }
}
frontend_ids
}
+ pub(super) fn foreground_tab_frontends_for_browser_context(
+ &self,
+ browser_context_id: Option<&str>,
+ ) -> Vec<ForegroundTabFrontendRoute> {
+ self.frontends
+ .iter()
+ .filter_map(|(frontend_id, route)| {
+ if route.kind != CdpSessionFrontendKind::ForegroundTab
+ || route.browser_context_id.as_deref() != browser_context_id
+ {
+ return None;
+ }
+ Some(ForegroundTabFrontendRoute {
+ frontend_id: *frontend_id,
+ page_target_id: route.target_id.clone()?,
+ base_session_id: route.base_session_id.clone(),
+ replayable_target_commands: route.replayable_target_commands.clone(),
+ })
+ })
+ .collect()
+ }
+
+ pub(super) fn replace_foreground_tab_frontend_base(
+ &mut self,
+ frontend_id: u64,
+ browser_context_id: Option<String>,
+ page_target_id: String,
+ session_id: String,
+ ) -> Result<String> {
+ if self.sessions.contains_key(&session_id) {
+ bail!("CDP foreground tab replacement session is already registered");
+ }
+ let previous_session_id = {
+ let Some(route) = self.frontends.get_mut(&frontend_id) else {
+ bail!("CDP foreground tab frontend is not registered");
+ };
+ if route.kind != CdpSessionFrontendKind::ForegroundTab {
+ bail!("CDP frontend is not a foreground tab");
+ }
+ let previous_session_id =
+ std::mem::replace(&mut route.base_session_id, session_id.clone());
+ route.target_id = Some(page_target_id);
+ route.browser_context_id = browser_context_id;
+ previous_session_id
+ };
+ self.remove_session_descendants(&previous_session_id);
+ self.sessions.remove(&previous_session_id);
+ self.sessions.insert(
+ session_id,
+ SessionBinding::Frontend(FrontendSessionRoute {
+ frontend_id,
+ kind: FrontendSessionKind::Base,
+ }),
+ );
+ Ok(previous_session_id)
+ }
+
+ pub(super) fn is_foreground_tab_frontend(&self, frontend_id: u64) -> bool {
+ self.frontends
+ .get(&frontend_id)
+ .is_some_and(|route| route.kind == CdpSessionFrontendKind::ForegroundTab)
+ }
+
+ pub(super) fn remember_foreground_tab_target_command(
+ &mut self,
+ frontend_id: u64,
+ method: String,
+ params: Value,
+ ) {
+ let Some(route) = self.frontends.get_mut(&frontend_id) else {
+ return;
+ };
+ if route.kind != CdpSessionFrontendKind::ForegroundTab {
+ return;
+ }
+ if let Some((_, previous_params)) = route
+ .replayable_target_commands
+ .iter_mut()
+ .find(|(previous_method, _)| previous_method == &method)
+ {
+ *previous_params = params;
+ return;
+ }
+ route.replayable_target_commands.push((method, params));
+ }
+
pub(super) fn base_session_id(&self, frontend_id: u64) -> Option<&str> {
self.frontends
.get(&frontend_id)
diff --git a/moli-protocol-server/src/cdp_frontend_router/routing/output.rs b/moli-protocol-server/src/cdp_frontend_router/routing/output.rs
index 7ec5176db..f3ee51f85 100644
--- a/moli-protocol-server/src/cdp_frontend_router/routing/output.rs
+++ b/moli-protocol-server/src/cdp_frontend_router/routing/output.rs
@@ -32,19 +32,31 @@ impl CdpFrontendRoutingState {
client_session_id,
} = pending.frontend;
let sink = self.frontends.frontend_sink(frontend_id)?;
- if message.get("error").is_none()
- && let PendingCommandEffect::AttachToTarget { target_id } = pending.effect
- && let Some(child_session_id) = message
- .pointer("/result/sessionId")
- .and_then(Value::as_str)
- .map(str::to_owned)
- {
- self.register_child_session(
- frontend_id,
- dispatch_session_id.as_deref(),
- &child_session_id,
- target_id.as_deref(),
- );
+ if message.get("error").is_none() {
+ match pending.effect {
+ PendingCommandEffect::AttachToTarget { target_id } => {
+ if let Some(child_session_id) = message
+ .pointer("/result/sessionId")
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ {
+ self.register_child_session(
+ frontend_id,
+ dispatch_session_id.as_deref(),
+ &child_session_id,
+ target_id.as_deref(),
+ );
+ }
+ }
+ PendingCommandEffect::ReplayForegroundTabTargetCommand { method, params } => {
+ self.frontends.remember_foreground_tab_target_command(
+ frontend_id,
+ method,
+ params,
+ );
+ }
+ PendingCommandEffect::None => {}
+ }
}
set_top_level_session_id(&mut message, client_session_id.as_deref());
Some((CdpRoutedFrontend { frontend_id, sink }, message))
diff --git a/moli-protocol-server/src/cdp_frontend_router/routing/pending_commands.rs b/moli-protocol-server/src/cdp_frontend_router/routing/pending_commands.rs
index 6a76da199..e2b8e4f36 100644
--- a/moli-protocol-server/src/cdp_frontend_router/routing/pending_commands.rs
+++ b/moli-protocol-server/src/cdp_frontend_router/routing/pending_commands.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use anyhow::{Context, Result};
+use serde_json::Value;
#[derive(Clone)]
pub(super) struct CdpCommandFrontend {
@@ -12,6 +13,7 @@ pub(super) struct CdpCommandFrontend {
pub(super) enum PendingCommandEffect {
None,
AttachToTarget { target_id: Option<String> },
+ ReplayForegroundTabTargetCommand { method: String, params: Value },
}
pub(super) struct PendingCommandRoute {
diff --git a/moli-protocol-server/src/cdp_scheduler/frontend_control.rs b/moli-protocol-server/src/cdp_scheduler/frontend_control.rs
index a2a142c09..24e38a9b5 100644
--- a/moli-protocol-server/src/cdp_scheduler/frontend_control.rs
+++ b/moli-protocol-server/src/cdp_scheduler/frontend_control.rs
@@ -140,6 +140,56 @@ impl CdpFrontendControlState {
}
true
}
+ CdpFrontendControlRequest::AttachForegroundTab {
+ page_target_id,
+ sink,
+ completion_tx,
+ } => {
+ let result = match self
+ .target_control
+ .attach_foreground_tab(scheduler, frontend_router, &page_target_id)
+ .await
+ {
+ Ok((session_id, browser_context_id)) => {
+ let frontend_id = self.allocate_frontend_id();
+ match frontend_router.register_foreground_tab_frontend(
+ frontend_id,
+ browser_context_id,
+ page_target_id,
+ session_id.clone(),
+ sink,
+ ) {
+ Ok(()) => Ok(frontend_id),
+ Err(error) => {
+ self.target_control
+ .detach_frontend_session(
+ scheduler,
+ frontend_router,
+ &session_id,
+ )
+ .await;
+ Err(error)
+ }
+ }
+ }
+ Err(error) => Err(error),
+ };
+ match completion_tx.send(result) {
+ Ok(()) => {}
+ Err(Ok(frontend_id)) => {
+ if let Some(session_id) =
+ frontend_router.unregister_foreground_tab_frontend(frontend_id)
+ {
+ self.target_control
+ .detach_frontend_session(scheduler, frontend_router, &session_id)
+ .await;
+ }
+ send_cookie_checkpoint(scheduler, owner_lifecycle);
+ }
+ Err(Err(_)) => {}
+ }
+ true
+ }
CdpFrontendControlRequest::DetachBrowser { frontend_id } => {
if let Some(session_id) = frontend_router.unregister_browser_frontend(frontend_id) {
self.target_control
@@ -158,6 +208,23 @@ impl CdpFrontendControlState {
}
true
}
+ CdpFrontendControlRequest::DetachForegroundTab { frontend_id } => {
+ if let Some(session_id) =
+ frontend_router.unregister_foreground_tab_frontend(frontend_id)
+ {
+ self.target_control
+ .detach_frontend_session(scheduler, frontend_router, &session_id)
+ .await;
+ send_cookie_checkpoint(scheduler, owner_lifecycle);
+ }
+ true
+ }
+ CdpFrontendControlRequest::ForegroundTabChanged { page_target_id } => {
+ self.target_control
+ .follow_foreground_tab_change(scheduler, frontend_router, page_target_id)
+ .await;
+ true
+ }
CdpFrontendControlRequest::TargetDestroyed { target_id } => {
frontend_router.unregister_page_frontends_for_target(&target_id);
true
diff --git a/moli-protocol-server/src/cdp_scheduler/frontend_control/target_control.rs b/moli-protocol-server/src/cdp_scheduler/frontend_control/target_control.rs
index 5e65a0076..4313bd3fe 100644
--- a/moli-protocol-server/src/cdp_scheduler/frontend_control/target_control.rs
+++ b/moli-protocol-server/src/cdp_scheduler/frontend_control/target_control.rs
@@ -11,6 +11,12 @@ pub(super) struct CdpFrontendTargetControl {
default_target_materialized: bool,
}
+struct ForegroundTabRoute {
+ browser_context_id: Option<String>,
+ page_target_id: String,
+ tab_target_id: String,
+}
+
impl Default for CdpFrontendTargetControl {
fn default() -> Self {
Self {
@@ -27,6 +33,29 @@ impl CdpFrontendTargetControl {
scheduler: &mut CdpScheduler,
frontend_router: &CdpFrontendRouter,
target_id: &str,
+ ) -> Result<String> {
+ self.attach_target(scheduler, frontend_router, target_id)
+ .await
+ }
+
+ pub(super) async fn attach_foreground_tab(
+ &mut self,
+ scheduler: &mut CdpScheduler,
+ frontend_router: &CdpFrontendRouter,
+ page_target_id: &str,
+ ) -> Result<(String, Option<String>)> {
+ let route = foreground_tab_route(scheduler, page_target_id)?;
+ let session_id = self
+ .attach_target(scheduler, frontend_router, &route.tab_target_id)
+ .await?;
+ Ok((session_id, route.browser_context_id))
+ }
+
+ async fn attach_target(
+ &mut self,
+ scheduler: &mut CdpScheduler,
+ frontend_router: &CdpFrontendRouter,
+ target_id: &str,
) -> Result<String> {
let control_session_id = self
.ensure_page_control_session(scheduler, frontend_router)
@@ -50,6 +79,85 @@ impl CdpFrontendTargetControl {
Ok(session_id)
}
+ pub(super) async fn follow_foreground_tab_change(
+ &mut self,
+ scheduler: &mut CdpScheduler,
+ frontend_router: &CdpFrontendRouter,
+ page_target_id: String,
+ ) {
+ let route = match foreground_tab_route(scheduler, &page_target_id) {
+ Ok(route) => route,
+ Err(error) => {
+ tracing::warn!(
+ target_id = page_target_id,
+ ?error,
+ "failed to resolve promoted foreground tab"
+ );
+ return;
+ }
+ };
+ let frontends = frontend_router
+ .foreground_tab_frontends_for_browser_context(route.browser_context_id.as_deref());
+ for frontend in frontends {
+ if frontend.page_target_id == route.page_target_id {
+ continue;
+ }
+ let new_session_id = match self
+ .attach_target(scheduler, frontend_router, &route.tab_target_id)
+ .await
+ {
+ Ok(session_id) => session_id,
+ Err(error) => {
+ tracing::warn!(
+ frontend_id = frontend.frontend_id,
+ target_id = route.page_target_id,
+ ?error,
+ "failed to attach promoted foreground tab"
+ );
+ continue;
+ }
+ };
+ self.detach_frontend_session(scheduler, frontend_router, &frontend.base_session_id)
+ .await;
+ if let Err(error) = frontend_router.replace_foreground_tab_frontend_base(
+ frontend.frontend_id,
+ route.browser_context_id.clone(),
+ route.page_target_id.clone(),
+ new_session_id.clone(),
+ ) {
+ tracing::warn!(
+ frontend_id = frontend.frontend_id,
+ target_id = route.page_target_id,
+ ?error,
+ "failed to bind promoted foreground tab"
+ );
+ self.detach_frontend_session(scheduler, frontend_router, &new_session_id)
+ .await;
+ continue;
+ }
+ for (method, params) in frontend.replayable_target_commands {
+ if let Err(error) = self
+ .execute_command(
+ scheduler,
+ frontend_router,
+ Some(&new_session_id),
+ &method,
+ params,
+ )
+ .await
+ {
+ tracing::warn!(
+ frontend_id = frontend.frontend_id,
+ target_id = route.page_target_id,
+ method,
+ ?error,
+ "failed to restore foreground tab target state"
+ );
+ }
+ }
+ }
+ }
+
pub(super) async fn attach_browser(
&mut self,
scheduler: &mut CdpScheduler,
@@ -279,6 +387,21 @@ impl CdpFrontendTargetControl {
}
}
+fn foreground_tab_route(
+ scheduler: &CdpScheduler,
+ page_target_id: &str,
+) -> Result<ForegroundTabRoute> {
+ let (tab_target_id, browser_context_id) = scheduler
+ .conn
+ .frontend_tab_target_identity(page_target_id)
+ .with_context(|| format!("CDP page target {page_target_id} has no tab target"))?;
+ Ok(ForegroundTabRoute {
+ browser_context_id,
+ page_target_id: page_target_id.to_owned(),
+ tab_target_id,
+ })
+}
+
fn control_command_result(response: Option<Value>, method: &str) -> Result<Value> {
let response = response.with_context(|| format!("{method} returned no response"))?;
if let Some(error) = response.get("error") {
diff --git a/moli-protocol-server/src/protocol_server/cdp.rs b/moli-protocol-server/src/protocol_server/cdp.rs
index 307bebd6f..c84c8eeab 100644
--- a/moli-protocol-server/src/protocol_server/cdp.rs
+++ b/moli-protocol-server/src/protocol_server/cdp.rs
@@ -28,14 +28,15 @@ pub(super) async fn json_version(State(state): State<AppState>) -> impl IntoResp
}))
}
-pub(super) async fn json_list(State(state): State<AppState>) -> impl IntoResponse {
+pub(super) async fn json_list(State(state): State<AppState>, uri: Uri) -> impl IntoResponse {
+ let for_tab = requests_tab_target(&uri);
let target_infos = state.cdp_agent_host_directory.page_target_infos();
let targets = if target_infos.is_empty() {
- vec![target_json(&state, DEFAULT_TARGET_URL)]
+ vec![target_json(&state, DEFAULT_TARGET_URL, for_tab)]
} else {
target_infos
.into_iter()
- .filter_map(|target_info| dynamic_target_json(&state, target_info))
+ .filter_map(|target_info| dynamic_target_json(&state, target_info, for_tab))
.collect()
};
axum::Json(json!(targets))
@@ -49,6 +50,7 @@ pub(super) async fn json_protocol() -> impl IntoResponse {
}
pub(super) async fn json_new_target(State(state): State<AppState>, uri: Uri) -> Response {
+ let for_tab = requests_tab_target(&uri);
let endpoint = match state.cdp_owner_registry.shared_owner() {
Ok(endpoint) => endpoint,
Err(error) => {
@@ -80,7 +82,7 @@ pub(super) async fn json_new_target(State(state): State<AppState>, uri: Uri) ->
)
.into_response();
};
- let Some(target) = dynamic_target_json(&state, route.target_info) else {
+ let Some(target) = dynamic_target_json(&state, route.target_info, for_tab) else {
rollback_unpublished_target(&endpoint, &target_id).await;
return (
StatusCode::INTERNAL_SERVER_ERROR,
@@ -153,35 +155,58 @@ fn no_such_target_response(target_id: &str) -> Response {
.into_response()
}
-fn target_json(state: &AppState, target_url: &str) -> serde_json::Value {
+fn target_json(state: &AppState, target_url: &str, for_tab: bool) -> serde_json::Value {
+ let (target_type, devtools_frontend_url, websocket_debugger_url) = if for_tab {
+ ("tab", &state.tab_devtools_frontend_url, &state.tab_ws_url)
+ } else {
+ ("page", &state.devtools_frontend_url, &state.page_ws_url)
+ };
json!({
"description": "",
- "devtoolsFrontendUrl": &state.devtools_frontend_url,
+ "devtoolsFrontendUrl": devtools_frontend_url,
"id": DEFAULT_TARGET_ID,
"title": target_url,
- "type": "page",
+ "type": target_type,
"url": target_url,
- "webSocketDebuggerUrl": &state.page_ws_url,
+ "webSocketDebuggerUrl": websocket_debugger_url,
})
}
fn dynamic_target_json(
state: &AppState,
target_info: DevToolsTargetInfo,
+ for_tab: bool,
) -> Option<serde_json::Value> {
let target_id = target_info.target_id.as_ref()?.as_str();
- let page_ws_url_prefix = state.page_ws_url.strip_suffix(DEFAULT_TARGET_ID)?;
- let devtools_frontend_url_prefix = state
- .devtools_frontend_url
- .strip_suffix(DEFAULT_TARGET_ID)?;
+ let (target_type, websocket_debugger_url, devtools_frontend_url) = if for_tab {
+ let websocket_prefix = state.tab_ws_url.strip_suffix(DEFAULT_TARGET_ID)?;
+ let frontend_prefix = state
+ .tab_devtools_frontend_url
+ .strip_suffix(DEFAULT_TARGET_ID)?;
+ (
+ "tab",
+ format!("{websocket_prefix}{target_id}"),
+ format!("{frontend_prefix}{target_id}"),
+ )
+ } else {
+ let websocket_prefix = state.page_ws_url.strip_suffix(DEFAULT_TARGET_ID)?;
+ let frontend_prefix = state
+ .devtools_frontend_url
+ .strip_suffix(DEFAULT_TARGET_ID)?;
+ (
+ "page",
+ format!("{websocket_prefix}{target_id}"),
+ format!("{frontend_prefix}{target_id}"),
+ )
+ };
Some(json!({
"description": "",
- "devtoolsFrontendUrl": format!("{devtools_frontend_url_prefix}{target_id}"),
+ "devtoolsFrontendUrl": devtools_frontend_url,
"id": target_id,
"title": target_info.title,
- "type": "page",
+ "type": target_type,
"url": target_info.url,
- "webSocketDebuggerUrl": format!("{page_ws_url_prefix}{target_id}"),
+ "webSocketDebuggerUrl": websocket_debugger_url,
}))
}
@@ -202,6 +227,11 @@ fn requested_target_url(uri: &Uri) -> String {
.unwrap_or_else(|| DEFAULT_TARGET_URL.to_owned())
}
+fn requests_tab_target(uri: &Uri) -> bool {
+ uri.query()
+ .is_some_and(|query| query.split('&').any(|component| component == "for_tab"))
+}
+
pub(super) async fn ws_browser_upgrade_handler(
Path(browser_id): Path<String>,
ws: WebSocketUpgrade,
@@ -239,6 +269,38 @@ pub(super) async fn ws_page_upgrade_handler(
page_ws_upgrade_response(ws, target_id, route.endpoint)
}
+pub(super) async fn ws_foreground_tab_upgrade_handler(
+ Path(target_id): Path<String>,
+ ws: WebSocketUpgrade,
+ State(state): State<AppState>,
+) -> Response {
+ if target_id == DEFAULT_TARGET_ID {
+ let owner_registry = state.cdp_owner_registry;
+ return ws.on_upgrade(move |socket| {
+ run_shared_frontend_socket(
+ socket,
+ owner_registry,
+ CdpFrontendSocketKind::ForegroundTab {
+ page_target_id: DEFAULT_TARGET_ID.to_owned(),
+ },
+ )
+ });
+ }
+ let Some(route) = state.cdp_agent_host_directory.lookup_page(&target_id) else {
+ return StatusCode::NOT_FOUND.into_response();
+ };
+ ws.on_upgrade(move |socket| async move {
+ run_cdp_frontend_socket(
+ socket,
+ route.endpoint,
+ CdpFrontendSocketKind::ForegroundTab {
+ page_target_id: target_id,
+ },
+ )
+ .await;
+ })
+}
+
async fn run_shared_frontend_socket(
socket: WebSocket,
owner_registry: SharedCdpOwnerRegistry,
diff --git a/moli-protocol-server/src/protocol_server/cdp_agent_host.rs b/moli-protocol-server/src/protocol_server/cdp_agent_host.rs
index fa2e78fa3..506911dba 100644
--- a/moli-protocol-server/src/protocol_server/cdp_agent_host.rs
+++ b/moli-protocol-server/src/protocol_server/cdp_agent_host.rs
@@ -49,14 +49,14 @@ impl CdpPageAgentHost {
}
impl CdpAgentHostDirectoryState {
- fn activate_page_host(&mut self, owner_id: u64, target_id: &str) {
- let Some(browser_context_id) = self
+ fn activate_page_host(&mut self, owner_id: u64, target_id: &str) -> bool {
+ let browser_context_id = self
.page_hosts
.get(target_id)
.filter(|host| host.owner_id == owner_id)
- .map(|host| host.browser_context_id().map(str::to_owned))
- else {
- return;
+ .map(|host| host.browser_context_id().map(str::to_owned));
+ let Some(browser_context_id) = browser_context_id else {
+ return false;
};
for host in self.page_hosts.values_mut().filter(|host| {
@@ -66,7 +66,9 @@ impl CdpAgentHostDirectoryState {
}
if let Some(host) = self.page_hosts.get_mut(target_id) {
host.is_active = true;
+ return true;
}
+ false
}
}
@@ -162,7 +164,9 @@ impl SharedCdpAgentHostDirectory {
}
}
CdpTargetHostLifecycleDelta::Activated { target_id } => {
- self.inner.lock().activate_page_host(owner_id, &target_id);
+ if self.inner.lock().activate_page_host(owner_id, &target_id) {
+ endpoint.foreground_tab_changed(target_id);
+ }
}
CdpTargetHostLifecycleDelta::Destroyed { target_id } => {
let endpoint = {
diff --git a/moli-protocol-server/src/protocol_server/cdp_socket.rs b/moli-protocol-server/src/protocol_server/cdp_socket.rs
index d152f2f09..ccda9dd84 100644
--- a/moli-protocol-server/src/protocol_server/cdp_socket.rs
+++ b/moli-protocol-server/src/protocol_server/cdp_socket.rs
@@ -7,6 +7,7 @@ use crate::{cdp_frontend::CdpFrontendEndpoint, cdp_writer::spawn_socket_sink};
pub(super) enum CdpFrontendSocketKind {
Browser,
Page { target_id: String },
+ ForegroundTab { page_target_id: String },
}
pub(super) async fn run_cdp_frontend_socket(
@@ -22,6 +23,11 @@ pub(super) async fn run_cdp_frontend_socket(
CdpFrontendSocketKind::Page { target_id } => {
endpoint.attach_page(target_id.clone(), sink).await
}
+ CdpFrontendSocketKind::ForegroundTab { page_target_id } => {
+ endpoint
+ .attach_foreground_tab(page_target_id.clone(), sink)
+ .await
+ }
};
let frontend_id = match frontend_id {
Ok(frontend_id) => frontend_id,
@@ -36,6 +42,7 @@ pub(super) async fn run_cdp_frontend_socket(
kind: match kind {
CdpFrontendSocketKind::Browser => CdpFrontendKind::Browser,
CdpFrontendSocketKind::Page { .. } => CdpFrontendKind::Page,
+ CdpFrontendSocketKind::ForegroundTab { .. } => CdpFrontendKind::ForegroundTab,
},
};
@@ -95,6 +102,7 @@ async fn wait_for_peer_close(socket_rx: &mut futures_util::stream::SplitStream<W
enum CdpFrontendKind {
Browser,
Page,
+ ForegroundTab,
}
struct CdpFrontendDetachGuard {
@@ -111,6 +119,9 @@ impl CdpFrontendDetachGuard {
match self.kind {
CdpFrontendKind::Browser => self.endpoint.detach_browser(frontend_id),
CdpFrontendKind::Page => self.endpoint.detach_page(frontend_id),
+ CdpFrontendKind::ForegroundTab => {
+ self.endpoint.detach_foreground_tab(frontend_id);
+ }
}
}
}
diff --git a/moli-protocol-server/src/protocol_server/mod.rs b/moli-protocol-server/src/protocol_server/mod.rs
index a40a73b3e..cd31c96aa 100644
--- a/moli-protocol-server/src/protocol_server/mod.rs
+++ b/moli-protocol-server/src/protocol_server/mod.rs
@@ -201,6 +201,14 @@ fn build_router(app_state: AppState) -> Router {
"/devtools/page/{target_id}/",
get(cdp::ws_page_upgrade_handler),
)
+ .route(
+ "/devtools/tab/{target_id}",
+ get(cdp::ws_foreground_tab_upgrade_handler),
+ )
+ .route(
+ "/devtools/tab/{target_id}/",
+ get(cdp::ws_foreground_tab_upgrade_handler),
+ )
.route(
"/session",
get(webdriver_bidi::ws_bidi_session_upgrade_handler)
@@ -734,12 +742,14 @@ fn is_websocket_upgrade_request(request: &Request<Body>) -> bool {
struct AppState {
browser_ws_url: String,
page_ws_url: String,
+ tab_ws_url: String,
bidi_ws_url: String,
bidi_session_registry: SharedBidiSessionRegistry,
classic_session_registry: SharedClassicSessionRegistry,
cdp_agent_host_directory: SharedCdpAgentHostDirectory,
cdp_owner_registry: SharedCdpOwnerRegistry,
devtools_frontend_url: String,
+ tab_devtools_frontend_url: String,
cookie_profile: SharedCookieProfile,
storage_partition: Arc<StoragePartitionState>,
fetch_config: FetchConfig,
@@ -800,13 +810,17 @@ impl AppState {
Self {
browser_ws_url: format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"),
page_ws_url: format!("ws://{addr}/devtools/page/{DEFAULT_TARGET_ID}"),
+ tab_ws_url: format!("ws://{addr}/devtools/tab/{DEFAULT_TARGET_ID}"),
bidi_ws_url: format!("ws://{addr}/session"),
bidi_session_registry: SharedBidiSessionRegistry::default(),
classic_session_registry: SharedClassicSessionRegistry::default(),
cdp_agent_host_directory,
cdp_owner_registry,
devtools_frontend_url: format!(
- "/devtools/inspector.html?ws={addr}/devtools/page/{DEFAULT_TARGET_ID}"
+ "/devtools/inspector.html?targetType=tab&ws={addr}/devtools/tab/{DEFAULT_TARGET_ID}"
+ ),
+ tab_devtools_frontend_url: format!(
+ "/devtools/inspector.html?ws={addr}/devtools/tab/{DEFAULT_TARGET_ID}"
),
cookie_profile,
storage_partition,
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
index 5c87a6fe9..b9b6fab07 100644
--- a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
@@ -26,6 +26,96 @@ async fn connect_dynamic_page(addr: std::net::SocketAddr, target_id: &str) -> Te
.0
}
+async fn connect_discovered_foreground_tab(
+ addr: std::net::SocketAddr,
+ target_id: &str,
+) -> TestCdpSocket {
+ let (status, body) = fetch_server_response(addr, "GET", "/json/list?for_tab").await;
+ assert_eq!(status, 200);
+ let targets: Vec<serde_json::Value> =
+ serde_json::from_slice(&body).expect("parse tab target discovery response");
+ let target = targets
+ .iter()
+ .find(|target| target["id"] == json!(target_id))
+ .expect("discovered foreground tab target");
+ assert_eq!(target["type"], json!("tab"));
+ let websocket_url = target["webSocketDebuggerUrl"]
+ .as_str()
+ .expect("foreground tab websocket URL");
+ assert!(websocket_url.contains("/devtools/tab/"));
+ connect_async(websocket_url)
+ .await
+ .expect("foreground tab websocket should connect")
+ .0
+}
+
+async fn enable_foreground_tab_page(
+ socket: &mut TestCdpSocket,
+ command_id: u64,
+ target_id: &str,
+) -> String {
+ send_cdp_command_without_wait(
+ socket,
+ command_id,
+ "Target.setAutoAttach",
+ None,
+ json!({
+ "autoAttach": true,
+ "waitForDebuggerOnStart": true,
+ "flatten": true
+ }),
+ )
+ .await;
+ let mut saw_response = false;
+ let mut attached_session_id = None;
+ let messages = recv_until_match(socket, |message| {
+ saw_response |= message["id"] == json!(command_id);
+ if message["method"] == json!("Target.attachedToTarget")
+ && message["params"]["targetInfo"]["targetId"] == json!(target_id)
+ {
+ attached_session_id = message["params"]["sessionId"].as_str().map(str::to_owned);
+ }
+ saw_response && attached_session_id.is_some()
+ })
+ .await;
+ assert_eq!(response_by_id(&messages, command_id)["result"], json!({}));
+ attached_session_id.expect("foreground tab page session")
+}
+
+async fn expect_foreground_tab_page_replaced(
+ socket: &mut TestCdpSocket,
+ old_session_id: &str,
+ target_id: &str,
+) -> String {
+ let mut detached = false;
+ let mut attached_session = None;
+ recv_until_match(socket, |message| {
+ detached |= message["method"] == json!("Target.detachedFromTarget")
+ && message["params"]["sessionId"] == json!(old_session_id);
+ if message["method"] == json!("Target.attachedToTarget")
+ && message["params"]["targetInfo"]["targetId"] == json!(target_id)
+ {
+ attached_session = message["params"]["sessionId"].as_str().map(|session_id| {
+ (
+ session_id.to_owned(),
+ message["params"]["waitingForDebugger"]
+ .as_bool()
+ .expect("replacement attachment waitingForDebugger"),
+ )
+ });
+ }
+ detached && attached_session.is_some()
+ })
+ .await;
+ let (session_id, waiting_for_debugger) =
+ attached_session.expect("replacement foreground tab page session");
+ assert!(
+ !waiting_for_debugger,
+ "an existing replacement page must not wait for the debugger"
+ );
+ session_id
+}
+
async fn wait_for_websocket_close(socket: &mut TestCdpSocket, label: &str) {
let wait_for_close = async {
loop {
@@ -48,6 +138,26 @@ fn response_by_id(messages: &[serde_json::Value], id: u64) -> &serde_json::Value
.unwrap_or_else(|| panic!("missing response id {id}: {messages:#?}"))
}
+fn is_screencast_visibility(message: &serde_json::Value, visible: bool) -> bool {
+ message["method"] == json!("Page.screencastVisibilityChanged")
+ && message["params"]["visible"] == json!(visible)
+}
+
+fn is_target_created_for_url(message: &serde_json::Value, url: &str) -> bool {
+ message["method"] == json!("Target.targetCreated")
+ && message["params"]["targetInfo"]["url"] == json!(url)
+}
+
+async fn expect_screencast_visibility(socket: &mut TestCdpSocket, visible: bool) {
+ let messages =
+ recv_until_match(socket, |message| is_screencast_visibility(message, visible)).await;
+ assert!(
+ messages
+ .iter()
+ .any(|message| is_screencast_visibility(message, visible))
+ );
+}
+
async fn enable_runtime_and_expect_default_context(
socket: &mut TestCdpSocket,
command_id: u64,
@@ -209,18 +319,26 @@ async fn fetch_server_response(
(status, response[header_end + 4..].to_vec())
}
-async fn dispatch_primary_click(socket: &mut TestCdpSocket, command_id: u64, x: u32, y: u32) {
+async fn dispatch_primary_click(
+ socket: &mut TestCdpSocket,
+ command_id: u64,
+ session_id: Option<&str>,
+ x: u32,
+ y: u32,
+) -> Vec<serde_json::Value> {
+ let mut messages = Vec::new();
for (offset, event_type) in [(0, "mousePressed"), (1, "mouseReleased")] {
let response = send_cdp_command(
socket,
command_id + offset,
"Input.dispatchMouseEvent",
- None,
+ session_id,
json!({
"type": event_type,
"x": x,
"y": y,
"button": "left",
+ "buttons": if event_type == "mousePressed" { 1 } else { 0 },
"clickCount": 1
}),
)
@@ -230,7 +348,9 @@ async fn dispatch_primary_click(socket: &mut TestCdpSocket, command_id: u64, x:
.get("result")
.is_some()
);
+ messages.extend(response);
}
+ messages
}
async fn evaluate_page_surface(socket: &mut TestCdpSocket, command_id: u64) -> serde_json::Value {
@@ -427,7 +547,7 @@ async fn websocket_cdp_dynamic_page_routes_to_existing_target_owner() {
assert_eq!(
listed_target["devtoolsFrontendUrl"],
json!(format!(
- "/devtools/inspector.html?ws={addr}/devtools/page/{target_id}"
+ "/devtools/inspector.html?targetType=tab&ws={addr}/devtools/tab/{target_id}"
))
);
let mut page = connect_dynamic_page(addr, &target_id).await;
@@ -554,7 +674,11 @@ async fn foreground_blank_click_activates_popup_browser_surface() {
let (mut opener, _) = connect_async(format!("ws://{addr}/devtools/page/{DEFAULT_TARGET_ID}"))
.await
.expect("connect default page websocket");
+ let mut foreground_tab = connect_discovered_foreground_tab(addr, DEFAULT_TARGET_ID).await;
+ let opener_foreground_session =
+ enable_foreground_tab_page(&mut foreground_tab, 1, DEFAULT_TARGET_ID).await;
let popup_url = "data:text/html,%3Ctitle%3EForeground%20Popup%3C/title%3E";
+ let popup_final_url = "data:text/html,<title>Foreground Popup</title>";
let opener_url = format!(
"data:text/html,<title>Popup Opener</title>\
<a id='popup' href='{popup_url}' \
@@ -570,7 +694,107 @@ async fn foreground_blank_click_activates_popup_browser_surface() {
)
.await;
assert!(response_by_id(&navigation, 1).get("result").is_some());
- dispatch_primary_click(&mut opener, 2, 20, 20).await;
+ assert!(
+ response_by_id(
+ &send_cdp_command(&mut opener, 2, "Page.enable", None, json!({})).await,
+ 2,
+ )
+ .get("result")
+ .is_some()
+ );
+ assert!(
+ response_by_id(
+ &send_cdp_command(
+ &mut opener,
+ 3,
+ "Target.setDiscoverTargets",
+ None,
+ json!({ "discover": true }),
+ )
+ .await,
+ 3,
+ )
+ .get("result")
+ .is_some()
+ );
+ let screencast_started =
+ send_cdp_command(&mut opener, 4, "Page.startScreencast", None, json!({})).await;
+ assert_eq!(response_by_id(&screencast_started, 4)["result"], json!({}));
+ assert!(
+ screencast_started
+ .iter()
+ .any(|message| is_screencast_visibility(message, true))
+ );
+
+ let foreground_link = send_cdp_command(
+ &mut foreground_tab,
+ 3,
+ "Runtime.evaluate",
+ Some(&opener_foreground_session),
+ json!({
+ "expression": "(() => { const link = document.getElementById('popup'); const rect = link?.getBoundingClientRect(); return { href: location.href, link: link?.href, x: rect?.x, y: rect?.y, width: rect?.width, height: rect?.height, hit: document.elementFromPoint(20, 20)?.id }; })()",
+ "returnByValue": true
+ }),
+ )
+ .await;
+ assert_eq!(
+ response_by_id(&foreground_link, 3)["result"]["result"]["value"]["link"],
+ json!(popup_final_url)
+ );
+
+ dispatch_primary_click(
+ &mut foreground_tab,
+ 5,
+ Some(&opener_foreground_session),
+ 20,
+ 20,
+ )
+ .await;
+ let mut activation_messages = recv_until_match(&mut opener, |message| {
+ is_target_created_for_url(message, popup_final_url)
+ || is_screencast_visibility(message, false)
+ })
+ .await;
+ let mut saw_popup_created = activation_messages
+ .iter()
+ .any(|message| is_target_created_for_url(message, popup_final_url));
+ let mut saw_opener_hidden = activation_messages
+ .iter()
+ .any(|message| is_screencast_visibility(message, false));
+ if !saw_popup_created || !saw_opener_hidden {
+ activation_messages.extend(
+ recv_until_match(&mut opener, |message| {
+ saw_popup_created |= is_target_created_for_url(message, popup_final_url);
+ saw_opener_hidden |= is_screencast_visibility(message, false);
+ saw_popup_created && saw_opener_hidden
+ })
+ .await,
+ );
+ }
+ let popup_created_index = activation_messages
+ .iter()
+ .position(|message| is_target_created_for_url(message, popup_final_url))
+ .expect("foreground click should create the popup target");
+ let opener_hidden_index = activation_messages
+ .iter()
+ .position(|message| is_screencast_visibility(message, false))
+ .expect("foreground click should hide the opener screencast");
+ assert!(
+ popup_created_index < opener_hidden_index,
+ "Chromium reports popup creation before the opener becomes inactive: {activation_messages:#?}"
+ );
+ let popup_target_id = activation_messages
+ .iter()
+ .find(|message| is_target_created_for_url(message, popup_final_url))
+ .and_then(|message| message["params"]["targetInfo"]["targetId"].as_str())
+ .expect("foreground popup target id")
+ .to_owned();
+ let popup_foreground_session = expect_foreground_tab_page_replaced(
+ &mut foreground_tab,
+ &opener_foreground_session,
+ &popup_target_id,
+ )
+ .await;
let targets = wait_for_target_list(
addr,
@@ -583,22 +807,56 @@ async fn foreground_blank_click_activates_popup_browser_surface() {
},
)
.await;
- let popup_target_id = targets[0]["id"]
- .as_str()
- .expect("popup target id")
- .to_owned();
+ assert_eq!(targets[0]["id"], json!(&popup_target_id));
+ let foreground_popup = send_cdp_command(
+ &mut foreground_tab,
+ 9,
+ "Runtime.evaluate",
+ Some(&popup_foreground_session),
+ json!({
+ "expression": "location.href",
+ "returnByValue": true
+ }),
+ )
+ .await;
+ assert_eq!(
+ response_by_id(&foreground_popup, 9)["result"]["result"]["value"],
+ json!(popup_final_url)
+ );
assert_eq!(targets[0]["title"], json!("Foreground Popup"));
assert_eq!(targets[1]["id"], json!(DEFAULT_TARGET_ID));
assert_eq!(targets[1]["title"], json!("Popup Opener"));
assert_eq!(targets[1]["url"], json!(&opener_url));
- let opener_surface = evaluate_page_surface(&mut opener, 4).await;
+ let opener_surface = evaluate_page_surface(&mut opener, 7).await;
assert_eq!(opener_surface["href"], json!(&opener_url));
assert_page_surface_active(&opener_surface, false);
+ let parked_opener_screencast =
+ send_cdp_command(&mut opener, 8, "Page.startScreencast", None, json!({})).await;
+ assert_eq!(
+ response_by_id(&parked_opener_screencast, 8)["result"],
+ json!({})
+ );
+ assert!(
+ parked_opener_screencast
+ .iter()
+ .any(|message| is_screencast_visibility(message, false))
+ );
let mut popup = connect_dynamic_page(addr, &popup_target_id).await;
- let popup_surface = evaluate_page_surface(&mut popup, 5).await;
+ let popup_surface = evaluate_page_surface(&mut popup, 9).await;
assert_page_surface_active(&popup_surface, true);
+ let popup_screencast_started =
+ send_cdp_command(&mut popup, 10, "Page.startScreencast", None, json!({})).await;
+ assert_eq!(
+ response_by_id(&popup_screencast_started, 10)["result"],
+ json!({})
+ );
+ assert!(
+ popup_screencast_started
+ .iter()
+ .any(|message| is_screencast_visibility(message, true))
+ );
let (activate_status, _) =
fetch_server_response(addr, "GET", "/json/activate/moli-default").await;
@@ -614,9 +872,34 @@ async fn foreground_blank_click_activates_popup_browser_surface() {
)
.await;
- let restored_opener = evaluate_page_surface(&mut opener, 6).await;
+ expect_screencast_visibility(&mut opener, true).await;
+ expect_screencast_visibility(&mut popup, false).await;
+
+ let restored_foreground_session = expect_foreground_tab_page_replaced(
+ &mut foreground_tab,
+ &popup_foreground_session,
+ DEFAULT_TARGET_ID,
+ )
+ .await;
+ let foreground_opener = send_cdp_command(
+ &mut foreground_tab,
+ 10,
+ "Runtime.evaluate",
+ Some(&restored_foreground_session),
+ json!({
+ "expression": "location.href",
+ "returnByValue": true
+ }),
+ )
+ .await;
+ assert_eq!(
+ response_by_id(&foreground_opener, 10)["result"]["result"]["value"],
+ json!(&opener_url)
+ );
+
+ let restored_opener = evaluate_page_surface(&mut opener, 11).await;
assert_page_surface_active(&restored_opener, true);
- let demoted_popup = evaluate_page_surface(&mut popup, 7).await;
+ let demoted_popup = evaluate_page_surface(&mut popup, 12).await;
assert_page_surface_active(&demoted_popup, false);
abort_test_cdp_server(server).await;
diff --git a/moli-protocol-server/src/protocol_server/tests/misc.rs b/moli-protocol-server/src/protocol_server/tests/misc.rs
index 382517e29..2683443a8 100644
--- a/moli-protocol-server/src/protocol_server/tests/misc.rs
+++ b/moli-protocol-server/src/protocol_server/tests/misc.rs
@@ -240,7 +240,9 @@ async fn discovery_endpoints_accept_trailing_slashes() {
assert_eq!(list[0]["description"], json!(""));
assert_eq!(
list[0]["devtoolsFrontendUrl"],
- json!("/devtools/inspector.html?ws=127.0.0.1:9222/devtools/page/moli-default")
+ json!(
+ "/devtools/inspector.html?targetType=tab&ws=127.0.0.1:9222/devtools/tab/moli-default"
+ )
);
assert_eq!(list[0]["id"], json!(DEFAULT_TARGET_ID));
assert_eq!(list[0]["title"], json!(DEFAULT_TARGET_URL));
@@ -499,19 +501,34 @@ async fn browser_websocket_exposes_same_default_target_as_json_list() {
#[tokio::test]
async fn chromium_devtools_json_list_accepts_non_get_methods_and_for_tab() {
let list = request_json("/json").await;
+ let tab_list = request_json("/json/list?for_tab").await;
// Ported from Chromium DevToolsHttpHandlerTest.TestJsonList: list
- // discovery is not method-gated, and the legacy for_tab query is
- // accepted by the same endpoint.
+ // discovery is not method-gated. Chromium's remote-device discovery asks
+ // for tab targets explicitly so its frontend can auto-attach the current
+ // page below a stable tab root.
assert_eq!(request_json_with_method(Method::PUT, "/json").await, list);
assert_eq!(
request_json_with_method(Method::PUT, "/json/list").await,
list
);
- assert_eq!(request_json("/json/list?for_tab").await, list);
assert_eq!(
request_json_with_method(Method::PUT, "/json/list?for_tab").await,
- list
+ tab_list
+ );
+ assert_eq!(list[0]["type"], json!("page"));
+ assert_eq!(
+ list[0]["webSocketDebuggerUrl"],
+ json!("ws://127.0.0.1:9222/devtools/page/moli-default")
+ );
+ assert_eq!(tab_list[0]["type"], json!("tab"));
+ assert_eq!(
+ tab_list[0]["devtoolsFrontendUrl"],
+ json!("/devtools/inspector.html?ws=127.0.0.1:9222/devtools/tab/moli-default")
+ );
+ assert_eq!(
+ tab_list[0]["webSocketDebuggerUrl"],
+ json!("ws://127.0.0.1:9222/devtools/tab/moli-default")
);
}
@@ -539,6 +556,12 @@ async fn chromium_devtools_json_new_uses_put_and_decodes_first_query_component()
request_json_with_method(Method::PUT, &format!("/json/new?{encoded}&for_tab")).await;
assert_eq!(target["url"], json!("about:blank?q=1&x=2"));
assert_eq!(target["title"], json!(""));
+ assert_eq!(target["type"], json!("tab"));
+ assert!(
+ target["webSocketDebuggerUrl"]
+ .as_str()
+ .is_some_and(|url| url.contains("/devtools/tab/"))
+ );
let target = request_json_with_method(Method::PUT, "/json/new?url=about%3Ablank%23named").await;
assert_eq!(target["url"], json!("about:blank#named"));
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rs
index 5736bf25c..71fd47054 100644
--- a/moli-protocol/src/conn.rs
+++ b/moli-protocol/src/conn.rs
@@ -124,6 +124,25 @@ pub enum CdpTargetHostLifecycleDelta {
Destroyed { target_id: String },
}
+/// Successful target selection and the Page events caused by its surface move.
+///
+/// The events stay attached to the completion so every activation entry point
+/// must preserve their position relative to its own response or owner action.
+#[derive(Debug)]
+pub(crate) struct CompletedTargetActivation {
+ protocol_events: Vec<BackgroundProtocolEvent>,
+}
+
+impl CompletedTargetActivation {
+ fn new(protocol_events: Vec<BackgroundProtocolEvent>) -> Self {
+ Self { protocol_events }
+ }
+
+ pub(crate) fn into_protocol_events(self) -> Vec<BackgroundProtocolEvent> {
+ self.protocol_events
+ }
+}
+
#[derive(Clone)]
pub struct CdpTargetHostLifecycleObserver {
callback: Arc<dyn Fn(CdpTargetHostLifecycleDelta) + Send + Sync>,
@@ -1505,6 +1524,14 @@ impl CdpConnection {
})
}
+ pub(crate) fn session_owner_target_has_waiting_for_debugger_session(
+ &self,
+ session_id: Option<&str>,
+ ) -> bool {
+ self.target_id_for_session_owner(session_id)
+ .is_some_and(|target_id| self.target_has_waiting_for_debugger_session(&target_id))
+ }
+
pub fn background_navigation_target_id_for_event(
&self,
event: &BackgroundProtocolEvent,
@@ -2643,7 +2670,16 @@ impl CdpConnection {
pub(crate) async fn promote_background_target_to_active_for_connection_async(
&mut self,
target_id: &str,
- ) -> Result<bool, String> {
+ ) -> Result<Option<CompletedTargetActivation>, String> {
+ let previous_active_target_id = self
+ .browser_context
+ .as_ref()
+ .and_then(BrowserContext::active_target_id_owned);
+ let hidden_screencast_sessions = previous_active_target_id
+ .as_deref()
+ .filter(|active_target_id| *active_target_id != target_id)
+ .map(|active_target_id| self.page_screencast_session_ids_for_target(active_target_id))
+ .unwrap_or_default();
self.handoff_navigation_engine_for_target_activation(target_id);
let Some(browser_context) = self.browser_context.as_mut() else {
return Err("BrowserContextNotLoaded".to_owned());
@@ -2651,11 +2687,51 @@ impl CdpConnection {
let promoted = browser_context
.promote_background_target_to_active_slot_async(target_id)
.await?;
- if promoted {
- self.refresh_active_browser_context_loader_async().await;
- self.notify_target_host_activated(target_id);
+ if !promoted {
+ return Ok(None);
}
- Ok(promoted)
+ self.refresh_active_browser_context_loader_async().await;
+ self.notify_target_host_activated(target_id);
+
+ let target_changed = previous_active_target_id.as_deref() != Some(target_id);
+ let mut protocol_events = Vec::new();
+ if target_changed {
+ // Chromium's PageHandler reports RenderWidgetHost visibility only
+ // while that attachment has an active screencast. Hide the old
+ // surface before exposing the promoted one.
+ protocol_events.extend(hidden_screencast_sessions.into_iter().map(|session_id| {
+ BackgroundProtocolEvent::page_screencast_visibility_changed(
+ session_id.as_deref(),
+ false,
+ )
+ }));
+ protocol_events.extend(
+ self.page_screencast_session_ids_for_target(target_id)
+ .into_iter()
+ .map(|session_id| {
+ BackgroundProtocolEvent::page_screencast_visibility_changed(
+ session_id.as_deref(),
+ true,
+ )
+ }),
+ );
+ }
+ Ok(Some(CompletedTargetActivation::new(protocol_events)))
+ }
+
+ fn page_screencast_session_ids_for_target(&mut self, target_id: &str) -> Vec<Option<String>> {
+ let Some(route) = self.target_session_route_for_target_id(target_id) else {
+ return Vec::new();
+ };
+ let mut route_scope = self.scoped_none_session_owner_route_override(route);
+ let conn = route_scope.conn_mut();
+ conn.page_event_session_ids_for_session_owner(None)
+ .into_iter()
+ .filter(|session_id| {
+ conn.target_page_session_state_for_session(session_id.as_deref())
+ .is_some_and(|state| state.page_screencast.is_active())
+ })
+ .collect()
}
pub(crate) fn enqueue_deferred_main_document_load_completion(
@@ -3388,6 +3464,22 @@ impl CdpConnection {
.tab_target_id_for_page_target_id(page_target_id)
}
+ /// Resolves the protocol tab and browser-context identities used by the
+ /// protocol server's DevTools foreground surface adapter.
+ #[doc(hidden)]
+ pub fn frontend_tab_target_identity(
+ &self,
+ page_target_id: &str,
+ ) -> Option<(String, Option<String>)> {
+ let tab_target_id = self
+ .tab_target_id_for_page_target_id(page_target_id)?
+ .to_owned();
+ let browser_context_id = self
+ .browser_context_id_for_target(page_target_id)
+ .map(str::to_owned);
+ Some((tab_target_id, browser_context_id))
+ }
+
pub(crate) fn page_target_id_for_tab_target_id(&self, tab_target_id: &str) -> Option<&str> {
self.target_control
.page_target_id_for_tab_target_id(tab_target_id)
diff --git a/moli-protocol/src/conn/browser_context/page_owner.rs b/moli-protocol/src/conn/browser_context/page_owner.rs
index 3709f9cfa..63dc7c603 100644
--- a/moli-protocol/src/conn/browser_context/page_owner.rs
+++ b/moli-protocol/src/conn/browser_context/page_owner.rs
@@ -896,6 +896,16 @@ impl CdpConnection {
.flatten()
}
+ pub(crate) fn page_screencast_visible_for_session_owner(
+ &self,
+ session_id: Option<&str>,
+ ) -> Option<bool> {
+ let (browser_context_id, target_id) = self.target_owner_identity_for_session(session_id)?;
+ let browser_context = self.browser_context_by_id(&browser_context_id)?;
+ let target_id = target_id.or_else(|| browser_context.active_target_id_owned())?;
+ Some(browser_context.is_active_target(&target_id))
+ }
+
pub(crate) fn stop_page_screencast_for_session_owner(
&mut self,
session_id: Option<&str>,
diff --git a/moli-protocol/src/conn/browser_context/session_owner.rs b/moli-protocol/src/conn/browser_context/session_owner.rs
index 68248ebd0..17bbc5bb7 100644
--- a/moli-protocol/src/conn/browser_context/session_owner.rs
+++ b/moli-protocol/src/conn/browser_context/session_owner.rs
@@ -1352,6 +1352,11 @@ impl CdpConnection {
self.target_control.attached_sessions_for_target(target_id)
}
+ pub(crate) fn target_has_waiting_for_debugger_session(&self, target_id: &str) -> bool {
+ self.target_control
+ .target_has_waiting_for_debugger_session(target_id)
+ }
+
pub(crate) fn auto_attached_sessions_for_owner(
&self,
owner_session_id: Option<&str>,
diff --git a/moli-protocol/src/conn/target/control.rs b/moli-protocol/src/conn/target/control.rs
index c2aec9b45..5671bd8af 100644
--- a/moli-protocol/src/conn/target/control.rs
+++ b/moli-protocol/src/conn/target/control.rs
@@ -470,6 +470,11 @@ impl TargetControlPlane {
self.sessions.attached_sessions_for_target(target_id)
}
+ pub(crate) fn target_has_waiting_for_debugger_session(&self, target_id: &str) -> bool {
+ self.sessions
+ .target_has_waiting_for_debugger_session(target_id)
+ }
+
pub(crate) fn auto_attached_sessions_for_owner(
&self,
owner_session_id: Option<&str>,
diff --git a/moli-protocol/src/conn/target/session.rs b/moli-protocol/src/conn/target/session.rs
index af38fbec7..e6df6a11a 100644
--- a/moli-protocol/src/conn/target/session.rs
+++ b/moli-protocol/src/conn/target/session.rs
@@ -355,6 +355,18 @@ impl TargetSessionRegistry {
sorted_index_values(self.attached_sessions_by_target.get(target_id))
}
+ pub(crate) fn target_has_waiting_for_debugger_session(&self, target_id: &str) -> bool {
+ self.attached_sessions_by_target
+ .get(target_id)
+ .is_some_and(|session_ids| {
+ session_ids.iter().any(|session_id| {
+ self.attached_sessions
+ .get(session_id)
+ .is_some_and(|session| session.waiting_for_debugger)
+ })
+ })
+ }
+
pub(crate) fn attached_session_owner_session_id(&self, session_id: &str) -> Option<&str> {
self.attached_sessions
.get(session_id)?
@@ -736,6 +748,31 @@ mod tests {
);
}
+ #[test]
+ fn target_session_registry_scopes_waiting_for_debugger_to_attached_target() {
+ let mut registry = TargetSessionRegistry::default();
+ registry.commit_attached_session(PreparedAttachSession::new(
+ "SID-waiting".to_owned(),
+ Some("SID-owner"),
+ "TID-waiting",
+ None,
+ true,
+ true,
+ ));
+ registry.commit_attached_session(PreparedAttachSession::new(
+ "SID-running".to_owned(),
+ Some("SID-owner"),
+ "TID-running",
+ None,
+ true,
+ false,
+ ));
+
+ assert!(registry.target_has_waiting_for_debugger_session("TID-waiting"));
+ assert!(!registry.target_has_waiting_for_debugger_session("TID-running"));
+ assert!(!registry.target_has_waiting_for_debugger_session("TID-unattached"));
+ }
+
#[test]
fn target_session_registry_clears_attached_session_and_auto_attached_indexes() {
let mut registry = TargetSessionRegistry::default();
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index 2ba093d34..3ac052d64 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -1381,9 +1381,9 @@ fn start_bring_to_front_command(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Page
async fn bring_session_route_to_front_async(
conn: &mut CdpConnection,
route: CdpSessionRoute,
-) -> Result<(), String> {
+) -> Result<Vec<BackgroundProtocolEvent>, String> {
let (browser_context_id, target_id) = match route {
- CdpSessionRoute::Browser => return Ok(()),
+ CdpSessionRoute::Browser => return Ok(Vec::new()),
CdpSessionRoute::ActiveTarget {
browser_context_id, ..
} => {
@@ -1393,7 +1393,7 @@ async fn bring_session_route_to_front_async(
{
return Err("BrowserContextNotLoaded".into());
}
- return Ok(());
+ return Ok(Vec::new());
}
CdpSessionRoute::AuxiliaryTarget {
browser_context_id,
@@ -1424,15 +1424,15 @@ async fn bring_session_route_to_front_async(
.and_then(|bc| bc.active_target_identity())
.is_some_and(|(active_target_id, _)| active_target_id == target_id);
if target_is_active {
- return Ok(());
+ return Ok(Vec::new());
}
match conn
.promote_background_target_to_active_for_connection_async(&target_id)
.await
{
- Ok(true) => Ok(()),
- Ok(false) => Err("UnknownTargetId".into()),
+ Ok(Some(activation)) => Ok(activation.into_protocol_events()),
+ Ok(None) => Err("UnknownTargetId".into()),
Err(message) => Err(message),
}
}
@@ -1801,10 +1801,13 @@ fn start_screencast_command(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> CommandO
conn.push_scheduler_event(crate::conn::CdpSchedulerEvent::PageScreencastStarted {
registration: PageScreencastRegistration::new(owner_scope, generation, every_nth_frame),
});
+ let visible = conn
+ .page_screencast_visible_for_session_owner(cmd.session_id)
+ .unwrap_or(true);
let mut plan = CommandOutputPlan::default();
plan.push_background_event(BackgroundProtocolEvent::page_screencast_visibility_changed(
cmd.session_id,
- true,
+ visible,
));
plan.push_success();
plan
@@ -6480,7 +6483,7 @@ fn try_start_page_enable_command(
"BrowserContextNotLoaded",
)));
}
- if conn.auto_attach_wait_for_debugger_on_start {
+ if conn.session_owner_target_has_waiting_for_debugger_session(cmd.session_id) {
return Some(PageCommandTaskStep::Complete(CommandOutputPlan::success()));
}
match conn.runtime_session_owner_slot(cmd.session_id) {
@@ -7462,7 +7465,12 @@ async fn complete_pending_page_command_inner(
restore_page_bring_to_front_context_async(conn, restore_browser_context_id.as_deref())
.await;
match result {
- Ok(()) => CommandOutputPlan::success(),
+ Ok(events) => {
+ let mut plan = CommandOutputPlan::default();
+ plan.extend_background_events(events);
+ plan.push_success();
+ plan
+ }
Err(message) => CommandOutputPlan::error(-31998, message),
}
}
diff --git a/moli-protocol/src/domains/page/tests/navigation.rs b/moli-protocol/src/domains/page/tests/navigation.rs
index 462c1efff..0493218be 100644
--- a/moli-protocol/src/domains/page/tests/navigation.rs
+++ b/moli-protocol/src/domains/page/tests/navigation.rs
@@ -1235,6 +1235,7 @@ async fn navigation_history_is_preserved_per_parked_target() {
.promote_background_target_to_active_for_connection_async("TID-B")
.await
.unwrap()
+ .is_some()
);
ctx.process_async(json!({
@@ -1265,6 +1266,7 @@ async fn navigation_history_is_preserved_per_parked_target() {
.promote_background_target_to_active_for_connection_async("TID-A")
.await
.unwrap()
+ .is_some()
);
}
diff --git a/moli-protocol/src/domains/target.rs b/moli-protocol/src/domains/target.rs
index 0dfecb2d9..9b17f263c 100644
--- a/moli-protocol/src/domains/target.rs
+++ b/moli-protocol/src/domains/target.rs
@@ -650,10 +650,10 @@ pub(crate) async fn execute_devtools_target_command_async_with_protocol_events(
(result, protocol_events)
}
DevToolsCommand::ActivateTarget(command) => {
- let result = lifecycle::execute_devtools_activate_target_command_async(conn, command)
- .await
- .map(|()| DevToolsCommandResult::Empty);
- (result, Vec::new())
+ match lifecycle::execute_devtools_activate_target_command_async(conn, command).await {
+ Ok(events) => (Ok(DevToolsCommandResult::Empty), events),
+ Err(error) => (Err(error), Vec::new()),
+ }
}
DevToolsCommand::RemoveBrowserContext(_) => {
let DevToolsCommand::RemoveBrowserContext(command) = command else {
diff --git a/moli-protocol/src/domains/target/lifecycle.rs b/moli-protocol/src/domains/target/lifecycle.rs
index 826f94904..a380d4ea6 100644
--- a/moli-protocol/src/domains/target/lifecycle.rs
+++ b/moli-protocol/src/domains/target/lifecycle.rs
@@ -725,7 +725,7 @@ pub(crate) async fn create_popup_target_from_renderer_output_background_events_a
&target_id,
target_info,
);
- if !conn.auto_attach_wait_for_debugger_on_start
+ if !conn.target_has_waiting_for_debugger_session(&target_id)
&& let Some(navigation) = PopupTargetNavigationOwnerAction::capture(
conn,
&browser_context_id,
@@ -856,7 +856,7 @@ pub(super) async fn start_target_url_navigation_if_allowed_background_events_asy
out: &mut Vec<BackgroundProtocolEvent>,
target_id: &str,
) {
- if conn.auto_attach_wait_for_debugger_on_start {
+ if conn.target_has_waiting_for_debugger_session(target_id) {
return;
}
let Some(route) = conn.target_session_route_for_target_id(target_id) else {
@@ -1008,22 +1008,30 @@ pub(crate) async fn complete_popup_target_activation_action_async(
conn.take_scheduler_events(),
);
}
- if let Err(error) = activate_popup_target_async(conn, &browser_context_id, &target_id).await {
- tracing::debug!(
- browser_context_id,
- target_id,
- %error,
- "popup target could not be activated"
- );
- }
- crate::conn::CdpTurnOutcome::new_with_protocol_events(Vec::new(), conn.take_scheduler_events())
+ let protocol_events =
+ match activate_popup_target_async(conn, &browser_context_id, &target_id).await {
+ Ok(events) => events,
+ Err(error) => {
+ tracing::debug!(
+ browser_context_id,
+ target_id,
+ %error,
+ "popup target could not be activated"
+ );
+ Vec::new()
+ }
+ };
+ crate::conn::CdpTurnOutcome::new_with_protocol_events(
+ protocol_events,
+ conn.take_scheduler_events(),
+ )
}
async fn activate_popup_target_async(
conn: &mut CdpConnection,
browser_context_id: &str,
target_id: &str,
-) -> Result<(), String> {
+) -> Result<Vec<BackgroundProtocolEvent>, String> {
let restore_browser_context_id = previously_active_browser_context_id(conn);
let result = if let Err(message) = select_browser_context_for_target(conn, target_id) {
Err(message.to_owned())
@@ -1038,14 +1046,14 @@ async fn activate_popup_target_async(
.as_ref()
.is_some_and(|browser_context| browser_context.is_active_target(target_id))
{
- Ok(())
+ Ok(Vec::new())
} else {
match conn
.promote_background_target_to_active_for_connection_async(target_id)
.await
{
- Ok(true) => Ok(()),
- Ok(false) => Err("PopupTargetUnavailable".to_owned()),
+ Ok(Some(activation)) => Ok(activation.into_protocol_events()),
+ Ok(None) => Err("PopupTargetUnavailable".to_owned()),
Err(message) => Err(message),
}
};
@@ -2085,8 +2093,10 @@ async fn set_auto_attach_inner_async(
.promote_background_target_to_active_for_connection_async(&promote_target_id)
.await
{
- Ok(true) => {}
- Ok(false) => {}
+ Ok(Some(activation)) => {
+ out.extend_background_events(activation.into_protocol_events());
+ }
+ Ok(None) => {}
Err(message) => {
panic!(
"same-context target should remain promotable during auto-attach: {message}"
@@ -2852,7 +2862,12 @@ pub(super) async fn complete_activate_target_command_async(
command: DevToolsActivateTargetCommand,
) -> CommandOutputPlan {
match execute_devtools_activate_target_command_async(conn, command).await {
- Ok(()) => CommandOutputPlan::success(),
+ Ok(events) => {
+ let mut plan = CommandOutputPlan::default();
+ plan.extend_background_events(events);
+ plan.push_success();
+ plan
+ }
Err(error) => CommandOutputPlan::from_devtools_error(error),
}
}
@@ -2860,7 +2875,7 @@ pub(super) async fn complete_activate_target_command_async(
pub(super) async fn execute_devtools_activate_target_command_async(
conn: &mut CdpConnection,
command: DevToolsActivateTargetCommand,
-) -> Result<(), DevToolsError> {
+) -> Result<Vec<BackgroundProtocolEvent>, DevToolsError> {
let target_id = command.target_id.as_str().to_owned();
let previously_active_browser_context_id = previously_active_browser_context_id(conn);
if let Err(message) = select_browser_context_for_target(conn, &target_id) {
@@ -2888,21 +2903,21 @@ pub(super) async fn execute_devtools_activate_target_command_async(
conn,
previously_active_browser_context_id.as_deref(),
);
- return Ok(());
+ return Ok(Vec::new());
}
if bc.has_dedicated_worker_target(&target_id) {
restore_previously_active_browser_context(
conn,
previously_active_browser_context_id.as_deref(),
);
- return Ok(());
+ return Ok(Vec::new());
}
if bc.has_service_worker_target(&target_id) {
restore_previously_active_browser_context(
conn,
previously_active_browser_context_id.as_deref(),
);
- return Ok(());
+ return Ok(Vec::new());
}
if !bc.has_active_target() && bc.background_targets.is_empty() {
restore_previously_active_browser_context(
@@ -2914,7 +2929,7 @@ pub(super) async fn execute_devtools_activate_target_command_async(
"TargetNotLoaded",
));
}
- if !matches!(
+ let protocol_events = if !matches!(
bc.active_target_identity(),
Some((ref active_target_id, _)) if active_target_id == &target_id
) && bc.background_target(&target_id).is_some()
@@ -2923,8 +2938,8 @@ pub(super) async fn execute_devtools_activate_target_command_async(
.promote_background_target_to_active_for_connection_async(&target_id)
.await
{
- Ok(true) => {}
- Ok(false) => {
+ Ok(Some(activation)) => activation.into_protocol_events(),
+ Ok(None) => {
restore_previously_active_browser_context(
conn,
previously_active_browser_context_id.as_deref(),
@@ -2954,13 +2969,15 @@ pub(super) async fn execute_devtools_activate_target_command_async(
DevToolsErrorKind::NoSuchTarget,
"UnknownTargetId",
));
- }
+ } else {
+ Vec::new()
+ };
restore_previously_active_browser_context(
conn,
previously_active_browser_context_id.as_deref(),
);
- Ok(())
+ Ok(protocol_events)
}
#[cfg(test)]