Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(cdp): model stable tab and page targets
ldm03bca33377163
diff --git a/moli-protocol-server/src/cdp_frontend.rs b/moli-protocol-server/src/cdp_frontend.rsindex 760280583..38d10513f 100644--- a/moli-protocol-server/src/cdp_frontend.rs+++ b/moli-protocol-server/src/cdp_frontend.rs@@ -22,28 +22,17 @@ pub(crate) enum CdpFrontendControlRequest {sink: CdpSocketSink,completion_tx: oneshot::Sender<Result<u64>>,},- AttachPage {+ AttachTarget {target_id: String,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 {+ DetachTarget {frontend_id: u64,},- ForegroundTabChanged {- page_target_id: String,- },TargetDestroyed {target_id: String,},@@ -57,7 +46,7 @@ pub(crate) enum CdpFrontendControlRequest {},CreateManagedTarget {target_url: String,- completion_tx: oneshot::Sender<Result<String>>,+ completion_tx: oneshot::Sender<Result<CdpCreatedTarget>>,},Shutdown,}@@ -67,6 +56,12 @@ pub(crate) struct CdpFrontendCommand {pub(crate) raw: String,}+#[derive(Clone, Debug, Eq, PartialEq)]+pub(crate) struct CdpCreatedTarget {+ pub(crate) page_target_id: String,+ pub(crate) tab_target_id: String,+}+pub(crate) fn cdp_frontend_channel() -> (CdpFrontendEndpoint, CdpFrontendReceivers) {let (control_tx, control_rx) = mpsc::unbounded_channel();let (command_tx, command_rx) = mpsc::channel(FRONTEND_COMMAND_QUEUE_CAPACITY);@@ -104,29 +99,9 @@ impl CdpFrontendEndpoint {}}- pub(crate) async fn attach_page(&self, 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::AttachPage {- target_id,- sink,- completion_tx,- })- .context("CDP target owner is no longer available")?;- tokio::select! {- biased;- _ = self.wait_for_shutdown() => bail!("CDP target owner stopped before page frontend attach"),- completion = completion_rx => completion- .context("CDP target owner stopped before page frontend attach")?,- }- }-- pub(crate) async fn attach_foreground_tab(+ pub(crate) async fn attach_target(&self,- page_target_id: String,+ target_id: String,sink: CdpSocketSink,) -> Result<u64> {if self.is_shutting_down() {@@ -134,17 +109,17 @@ impl CdpFrontendEndpoint {}let (completion_tx, completion_rx) = oneshot::channel();self.control_tx- .send(CdpFrontendControlRequest::AttachForegroundTab {- page_target_id,+ .send(CdpFrontendControlRequest::AttachTarget {+ 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"),+ _ = self.wait_for_shutdown() => bail!("CDP target owner stopped before target frontend attach"),completion = completion_rx => completion- .context("CDP owner stopped before foreground tab attach")?,+ .context("CDP target owner stopped before target frontend attach")?,}}@@ -162,22 +137,10 @@ impl CdpFrontendEndpoint {.send(CdpFrontendControlRequest::DetachBrowser { frontend_id });}- pub(crate) fn detach_page(&self, frontend_id: u64) {- let _ = self- .control_tx- .send(CdpFrontendControlRequest::DetachPage { frontend_id });- }-- pub(crate) fn detach_foreground_tab(&self, frontend_id: u64) {+ pub(crate) fn detach_target(&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 });+ .send(CdpFrontendControlRequest::DetachTarget { frontend_id });}pub(crate) fn target_destroyed(&self, target_id: String) {@@ -224,7 +187,10 @@ impl CdpFrontendEndpoint {}}- pub(crate) async fn create_managed_target(&self, target_url: String) -> Result<String> {+ pub(crate) async fn create_managed_target(+ &self,+ target_url: String,+ ) -> Result<CdpCreatedTarget> {if self.is_shutting_down() {bail!("CDP target owner is shutting down");}diff --git a/moli-protocol-server/src/cdp_frontend_router.rs b/moli-protocol-server/src/cdp_frontend_router.rsindex 4d75a6ad9..0101298fe 100644--- a/moli-protocol-server/src/cdp_frontend_router.rs+++ b/moli-protocol-server/src/cdp_frontend_router.rs@@ -7,8 +7,6 @@ use serde_json::Value;use crate::{cdp_scheduler::ProtocolOutputSequence, cdp_writer::CdpSocketSink};-pub(crate) use self::routing::ForegroundTabFrontendRoute;-use self::routing::CdpFrontendRoutingState;mod routing;@@ -55,7 +53,7 @@ impl CdpFrontendRouter {.register_browser_frontend(frontend_id, session_id, sink)}- pub(crate) fn register_page_frontend(+ pub(crate) fn register_target_frontend(&self,frontend_id: u64,target_id: String,@@ -64,68 +62,21 @@ impl CdpFrontendRouter {) -> Result<()> {self.routing.lock()- .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,- )+ .register_target_frontend(frontend_id, 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)}- pub(crate) fn unregister_page_frontend(&self, frontend_id: u64) -> Option<String> {- 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_target_frontend(&self, frontend_id: u64) -> Option<String> {+ self.routing.lock().unregister_target_frontend(frontend_id)}- pub(crate) fn unregister_page_frontends_for_target(&self, target_id: &str) {+ pub(crate) fn unregister_frontends_for_target(&self, target_id: &str) {self.routing.lock()- .unregister_page_frontends_for_target(target_id);+ .unregister_frontends_for_target(target_id);}pub(crate) fn register_private_session(&self, session_id: String) -> Result<()> {diff --git a/moli-protocol-server/src/cdp_frontend_router/routing.rs b/moli-protocol-server/src/cdp_frontend_router/routing.rsindex e6cfa8023..0d9be67af 100644--- a/moli-protocol-server/src/cdp_frontend_router/routing.rs+++ b/moli-protocol-server/src/cdp_frontend_router/routing.rs@@ -10,8 +10,6 @@ mod frontend_registry;mod output;mod pending_commands;-pub(crate) use frontend_registry::ForegroundTabFrontendRoute;-pub(super) struct CdpRoutedFrontend {frontend_id: u64,sink: CdpSocketSink,@@ -46,7 +44,7 @@ impl CdpFrontendRoutingState {.register_browser_frontend(frontend_id, session_id, sink)}- pub(super) fn register_page_frontend(+ pub(super) fn register_target_frontend(&mut self,frontend_id: u64,target_id: String,@@ -54,24 +52,7 @@ impl CdpFrontendRoutingState {sink: CdpSocketSink,) -> Result<()> {self.frontends- .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,- )+ .register_target_frontend(frontend_id, target_id, session_id, sink)}pub(super) fn unregister_browser_frontend(&mut self, frontend_id: u64) -> Option<String> {@@ -82,59 +63,20 @@ impl CdpFrontendRoutingState {session_id}- pub(super) fn unregister_page_frontend(&mut self, frontend_id: u64) -> Option<String> {- let session_id = self.frontends.unregister_page_frontend(frontend_id);- if session_id.is_some() {- self.pending_commands.remove_frontend(frontend_id);- }- 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);+ pub(super) fn unregister_target_frontend(&mut self, frontend_id: u64) -> Option<String> {+ let session_id = self.frontends.unregister_target_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)}- pub(super) fn unregister_page_frontends_for_target(&mut self, target_id: &str) {- for frontend_id in self- .frontends- .unregister_page_frontends_for_target(target_id)- {+ pub(super) fn unregister_frontends_for_target(&mut self, target_id: &str) {+ for frontend_id in self.frontends.unregister_frontends_for_target(target_id) {self.pending_commands.remove_frontend(frontend_id);}}diff --git a/moli-protocol-server/src/cdp_frontend_router/routing/command.rs b/moli-protocol-server/src/cdp_frontend_router/routing/command.rsindex 46b0e5525..054225b5b 100644--- a/moli-protocol-server/src/cdp_frontend_router/routing/command.rs+++ b/moli-protocol-server/src/cdp_frontend_router/routing/command.rs@@ -60,21 +60,6 @@ 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.rsindex 06a8a892e..99b77336e 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,34 +1,22 @@use std::collections::{HashMap, HashSet};use anyhow::{Result, bail};-use serde_json::Value;use crate::cdp_writer::CdpSocketSink;#[derive(Clone, Copy, Eq, PartialEq)]pub(super) enum CdpSessionFrontendKind {Browser,- Page,- ForegroundTab,+ Target,}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,@@ -37,7 +25,7 @@ pub(super) struct FrontendSessionRoute {#[derive(Clone)]pub(super) enum FrontendSessionKind {- /// One hidden browser-target or page-target session owned by exactly one+ /// One hidden browser-target, tab-target, or page-target session owned by exactly one/// WebSocket frontend. Commands without a public sessionId dispatch here.Base,/// A client-visible session created underneath the base session (or one@@ -87,14 +75,13 @@ impl FrontendRegistry {frontend_id,CdpSessionFrontendKind::Browser,None,- None,session_id,sink,true,)}- pub(super) fn register_page_frontend(+ pub(super) fn register_target_frontend(&mut self,frontend_id: u64,target_id: String,@@ -103,28 +90,8 @@ impl FrontendRegistry {) -> Result<()> {self.register_session_frontend(frontend_id,- CdpSessionFrontendKind::Page,+ CdpSessionFrontendKind::Target,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,@@ -136,7 +103,6 @@ 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,@@ -166,9 +132,7 @@ impl FrontendRegistry {CdpSessionFrontendRoute {kind,target_id,- browser_context_id,base_session_id: session_id,- replayable_target_commands: Vec::new(),sink,},);@@ -194,16 +158,8 @@ impl FrontendRegistry {.map(|route| route.base_session_id)}- pub(super) fn unregister_page_frontend(&mut self, frontend_id: u64) -> Option<String> {- self.unregister_session_frontend(frontend_id, CdpSessionFrontendKind::Page)- .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)+ pub(super) fn unregister_target_frontend(&mut self, frontend_id: u64) -> Option<String> {+ self.unregister_session_frontend(frontend_id, CdpSessionFrontendKind::Target).map(|route| route.base_session_id)}@@ -226,118 +182,22 @@ impl FrontendRegistry {Some(route)}- pub(super) fn unregister_page_frontends_for_target(&mut self, target_id: &str) -> Vec<u64> {+ pub(super) fn unregister_frontends_for_target(&mut self, target_id: &str) -> Vec<u64> {let frontend_ids = self.frontends.iter().filter_map(|(frontend_id, route)| {- (matches!(- route.kind,- CdpSessionFrontendKind::Page | CdpSessionFrontendKind::ForegroundTab- ) && route.target_id.as_deref() == Some(target_id))+ (route.kind == CdpSessionFrontendKind::Target+ && route.target_id.as_deref() == Some(target_id)).then_some(*frontend_id)}).collect::<Vec<_>>();for frontend_id in &frontend_ids {- 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 => {}- }+ self.unregister_target_frontend(*frontend_id);}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)@@ -553,13 +413,13 @@ mod tests {.expect("register control session");let error = registry- .register_page_frontend(+ .register_target_frontend(10,"TID-page".to_owned(),"SID-control".to_owned(),test_sink(),)- .expect_err("page frontend must not claim control session");+ .expect_err("target frontend must not claim control session");assert!(error.to_string().contains("internal control"));assert!(registry.is_internal_control_session("SID-control"));}diff --git a/moli-protocol-server/src/cdp_frontend_router/routing/output.rs b/moli-protocol-server/src/cdp_frontend_router/routing/output.rsindex f3ee51f85..8905ee1d8 100644--- a/moli-protocol-server/src/cdp_frontend_router/routing/output.rs+++ b/moli-protocol-server/src/cdp_frontend_router/routing/output.rs@@ -48,13 +48,6 @@ impl CdpFrontendRoutingState {);}}- PendingCommandEffect::ReplayForegroundTabTargetCommand { method, params } => {- self.frontends.remember_foreground_tab_target_command(- frontend_id,- method,- params,- );- }PendingCommandEffect::None => {}}}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.rsindex e2b8e4f36..714c6ea8c 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,8 +1,6 @@use std::collections::HashMap;use anyhow::{Context, Result};-use serde_json::Value;-#[derive(Clone)]pub(super) struct CdpCommandFrontend {pub(super) frontend_id: u64,@@ -13,7 +11,6 @@ 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_frontend_router/routing/tests.rs b/moli-protocol-server/src/cdp_frontend_router/routing/tests.rsindex 580fa69af..5ea1cf7d3 100644--- a/moli-protocol-server/src/cdp_frontend_router/routing/tests.rs+++ b/moli-protocol-server/src/cdp_frontend_router/routing/tests.rs@@ -33,8 +33,8 @@ fn browser_and_page_client_command_ids_are_isolated_and_restored() {.register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");routing- .register_page_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())- .expect("register page frontend");+ .register_target_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())+ .expect("register target frontend");let browser_command = expect_prepared_command(routing.prepare_command(@@ -763,8 +763,8 @@ fn browser_frontend_hides_base_session_on_wire() {fn frontend_route_rewrite_preserves_unknown_command_fields() {let mut routing = CdpFrontendRoutingState::default();routing- .register_page_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())- .expect("register page frontend");+ .register_target_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())+ .expect("register target frontend");let command = expect_prepared_command(routing.prepare_command(@@ -790,8 +790,8 @@ fn malformed_command_keeps_its_originating_frontend() {.register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");routing- .register_page_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())- .expect("register page frontend");+ .register_target_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())+ .expect("register target frontend");assert!(matches!(routing.prepare_command_str(5, "{".to_owned()),@@ -841,8 +841,8 @@ fn private_page_session_detach_does_not_fall_back_to_browser_frontend() {.register_browser_frontend(5, "SID-browser".to_owned(), test_sink()).expect("register browser frontend");routing- .register_page_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())- .expect("register page frontend");+ .register_target_frontend(10, "TID-1".to_owned(), "SID-page".to_owned(), test_sink())+ .expect("register target frontend");routing.register_child_session(5,Some("SID-browser"),@@ -887,11 +887,11 @@ fn private_page_session_detach_does_not_fall_back_to_browser_frontend() {fn page_child_sessions_are_scoped_to_their_frontend_and_removed_on_detach() {let mut routing = CdpFrontendRoutingState::default();routing- .register_page_frontend(10, "TID-1".to_owned(), "SID-page-1".to_owned(), test_sink())- .expect("register first page frontend");+ .register_target_frontend(10, "TID-1".to_owned(), "SID-page-1".to_owned(), test_sink())+ .expect("register first target frontend");routing- .register_page_frontend(20, "TID-2".to_owned(), "SID-page-2".to_owned(), test_sink())- .expect("register second page frontend");+ .register_target_frontend(20, "TID-2".to_owned(), "SID-page-2".to_owned(), test_sink())+ .expect("register second target frontend");let attach = expect_prepared_command(routing.prepare_command(@@ -999,8 +999,8 @@ fn stalled_browser_writer_does_not_block_page_frontend_enqueue() {.register_browser_frontend(5, "SID-browser".to_owned(), root_sink).expect("register browser frontend");router- .register_page_frontend(10, "TID-page".to_owned(), "SID-page".to_owned(), page_sink)- .expect("register page frontend");+ .register_target_frontend(10, "TID-page".to_owned(), "SID-page".to_owned(), page_sink)+ .expect("register target frontend");assert!(router.enqueue_protocol_output_sequence(ProtocolOutputSequence::from_messages(vec![diff --git a/moli-protocol-server/src/cdp_scheduler.rs b/moli-protocol-server/src/cdp_scheduler.rsindex f37c083d9..df16133d5 100644--- a/moli-protocol-server/src/cdp_scheduler.rs+++ b/moli-protocol-server/src/cdp_scheduler.rs@@ -58,22 +58,26 @@ pub(crate) use runtime_dispatch::{pub(crate) struct CdpTargetHostIntegration {target_id_allocator: Arc<AtomicU64>,+ tab_target_id_allocator: Arc<AtomicU64>,lifecycle_observer: CdpTargetHostLifecycleObserver,}impl CdpTargetHostIntegration {pub(crate) fn new(target_id_allocator: Arc<AtomicU64>,+ tab_target_id_allocator: Arc<AtomicU64>,lifecycle_observer: CdpTargetHostLifecycleObserver,) -> Self {Self {target_id_allocator,+ tab_target_id_allocator,lifecycle_observer,}}fn install(self, conn: &mut CdpConnection) {conn.set_shared_target_id_allocator(self.target_id_allocator);+ conn.set_shared_tab_target_id_allocator(self.tab_target_id_allocator);conn.set_target_host_lifecycle_observer(self.lifecycle_observer);}}diff --git a/moli-protocol-server/src/cdp_scheduler/frontend_control.rs b/moli-protocol-server/src/cdp_scheduler/frontend_control.rsindex 24e38a9b5..612d8e7fa 100644--- a/moli-protocol-server/src/cdp_scheduler/frontend_control.rs+++ b/moli-protocol-server/src/cdp_scheduler/frontend_control.rs@@ -91,19 +91,19 @@ impl CdpFrontendControlState {}true}- CdpFrontendControlRequest::AttachPage {+ CdpFrontendControlRequest::AttachTarget {target_id,sink,completion_tx,} => {let result = match self.target_control- .attach_page(scheduler, frontend_router, &target_id)+ .attach_target(scheduler, frontend_router, &target_id).await{Ok(session_id) => {let frontend_id = self.allocate_frontend_id();- match frontend_router.register_page_frontend(+ match frontend_router.register_target_frontend(frontend_id,target_id,session_id.clone(),@@ -128,57 +128,7 @@ impl CdpFrontendControlState {Ok(()) => {}Err(Ok(frontend_id)) => {if let Some(session_id) =- frontend_router.unregister_page_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::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)+ frontend_router.unregister_target_frontend(frontend_id){self.target_control.detach_frontend_session(scheduler, frontend_router, &session_id)@@ -199,8 +149,8 @@ impl CdpFrontendControlState {}true}- CdpFrontendControlRequest::DetachPage { frontend_id } => {- if let Some(session_id) = frontend_router.unregister_page_frontend(frontend_id) {+ CdpFrontendControlRequest::DetachTarget { frontend_id } => {+ if let Some(session_id) = frontend_router.unregister_target_frontend(frontend_id) {self.target_control.detach_frontend_session(scheduler, frontend_router, &session_id).await;@@ -208,25 +158,8 @@ 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);+ frontend_router.unregister_frontends_for_target(&target_id);true}CdpFrontendControlRequest::ActivateTarget {@@ -260,10 +193,10 @@ impl CdpFrontendControlState {.target_control.create_managed_target(scheduler, frontend_router, &target_url).await;- if let Err(Ok(target_id)) = completion_tx.send(result) {+ if let Err(Ok(target)) = completion_tx.send(result) {let _ = self.target_control- .close_target(scheduler, frontend_router, &target_id)+ .close_target(scheduler, frontend_router, &target.page_target_id).await;}send_cookie_checkpoint(scheduler, owner_lifecycle);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.rsindex 4313bd3fe..357b05387 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@@ -1,64 +1,49 @@use anyhow::{Context, Result, bail};use serde_json::{Value, json};-use crate::cdp_frontend_router::CdpFrontendRouter;+use crate::{cdp_frontend::CdpCreatedTarget, cdp_frontend_router::CdpFrontendRouter};use super::super::{CdpScheduler, ProtocolOutputSequence};pub(super) struct CdpFrontendTargetControl {next_command_id: u64,- page_control_session_id: Option<String>,- default_target_materialized: bool,-}--struct ForegroundTabRoute {- browser_context_id: Option<String>,- page_target_id: String,- tab_target_id: String,+ browser_control_session_id: Option<String>,+ default_page_materialized: bool,}impl Default for CdpFrontendTargetControl {fn default() -> Self {Self {next_command_id: u64::MAX,- page_control_session_id: None,- default_target_materialized: false,+ browser_control_session_id: None,+ default_page_materialized: false,}}}impl CdpFrontendTargetControl {- pub(super) async fn attach_page(+ pub(super) async fn attach_target(&mut self,scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,target_id: &str,) -> Result<String> {- self.attach_target(scheduler, frontend_router, target_id)+ if target_id == scheduler.conn.default_tab_target_id() {+ self.ensure_default_target_is_materialized(scheduler, frontend_router)+ .await?;+ }+ self.attach_target_session(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(+ async fn attach_target_session(&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)+ .ensure_browser_control_session(scheduler, frontend_router).await?;let response = self.execute_command(@@ -74,90 +59,11 @@ impl CdpFrontendTargetControl {.with_context(|| format!("CDP target {target_id} did not return an attach session"))?.to_owned();if target_id == scheduler.conn.default_target_id() {- self.default_target_materialized = true;+ self.default_page_materialized = true;}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,@@ -222,7 +128,7 @@ impl CdpFrontendTargetControl {scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,target_url: &str,- ) -> Result<String> {+ ) -> Result<CdpCreatedTarget> {self.ensure_default_target_is_materialized(scheduler, frontend_router).await?;let response = self@@ -234,10 +140,19 @@ impl CdpFrontendTargetControl {json!({ "url": target_url }),).await?;- response["result"]["targetId"]+ let page_target_id = response["result"]["targetId"].as_str().map(str::to_owned)- .context("Target.createTarget returned no targetId")+ .context("Target.createTarget returned no targetId")?;+ let tab_target_id = scheduler+ .conn+ .tab_target_id_for_page_target_id(&page_target_id)+ .map(str::to_owned)+ .context("created page target has no tab target")?;+ Ok(CdpCreatedTarget {+ page_target_id,+ tab_target_id,+ })}pub(super) async fn close_target(@@ -261,12 +176,12 @@ impl CdpFrontendTargetControl {Ok(())}- async fn ensure_page_control_session(+ async fn ensure_browser_control_session(&mut self,scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,) -> Result<String> {- if let Some(control_session_id) = self.page_control_session_id.as_ref() {+ if let Some(control_session_id) = self.browser_control_session_id.as_ref() {return Ok(control_session_id.clone());}let response = self@@ -282,7 +197,7 @@ impl CdpFrontendTargetControl {.as_str().context("CDP browser target did not return an attach session")?.to_owned();- self.page_control_session_id = Some(session_id.clone());+ self.browser_control_session_id = Some(session_id.clone());Ok(session_id)}@@ -291,7 +206,7 @@ impl CdpFrontendTargetControl {scheduler: &mut CdpScheduler,frontend_router: &CdpFrontendRouter,) -> Result<()> {- if self.default_target_materialized {+ if self.default_page_materialized {return Ok(());}// A fresh connection may reuse its unclaimed default placeholder for@@ -299,7 +214,7 @@ impl CdpFrontendTargetControl {// ID permanently, so materialize it before creating another target.let default_target_id = scheduler.conn.default_target_id().to_owned();let control_session_id = self- .ensure_page_control_session(scheduler, frontend_router)+ .ensure_browser_control_session(scheduler, frontend_router).await?;let response = self.execute_command(@@ -322,7 +237,7 @@ impl CdpFrontendTargetControl {json!({ "sessionId": reservation_session_id }),).await?;- self.default_target_materialized = true;+ self.default_page_materialized = true;Ok(())}@@ -387,21 +302,6 @@ 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.rsindex c84c8eeab..c0d481ab4 100644--- a/moli-protocol-server/src/protocol_server/cdp.rs+++ b/moli-protocol-server/src/protocol_server/cdp.rs@@ -6,13 +6,16 @@ use axum::{http::{StatusCode, Uri, header},response::{IntoResponse, Response},};-use moli_protocol::{DevToolsTargetInfo, version};+use moli_protocol::{+ DEFAULT_CDP_PAGE_TARGET_ID, DEFAULT_CDP_TAB_TARGET_ID, DevToolsTargetInfo, DevToolsTargetKind,+ version,+};use moli_protocol_cdp::CDP_PROTOCOL_JSON;use percent_encoding::percent_decode_str;use serde_json::json;use super::{- AppState, DEFAULT_BROWSER_ID, DEFAULT_TARGET_ID, DEFAULT_TARGET_URL,+ AppState, DEFAULT_BROWSER_ID, DEFAULT_TARGET_URL,cdp_owner::SharedCdpOwnerRegistry,cdp_socket::{CdpFrontendSocketKind, run_cdp_frontend_socket},};@@ -29,14 +32,28 @@ pub(super) async fn json_version(State(state): State<AppState>) -> impl IntoResp}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 include_tab_targets = requests_tab_targets(&uri);+ let target_infos = state+ .cdp_agent_host_directory+ .remote_debugging_target_infos(include_tab_targets);let targets = if target_infos.is_empty() {- vec![target_json(&state, DEFAULT_TARGET_URL, for_tab)]+ let mut targets = vec![default_target_json(+ &state,+ DEFAULT_TARGET_URL,+ DevToolsTargetKind::Page,+ )];+ if include_tab_targets {+ targets.push(default_target_json(+ &state,+ DEFAULT_TARGET_URL,+ DevToolsTargetKind::Tab,+ ));+ }+ targets} else {target_infos.into_iter()- .filter_map(|target_info| dynamic_target_json(&state, target_info, for_tab))+ .filter_map(|target_info| target_json(&state, target_info)).collect()};axum::Json(json!(targets))@@ -50,7 +67,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 kind = requested_target_kind(&uri);let endpoint = match state.cdp_owner_registry.shared_owner() {Ok(endpoint) => endpoint,Err(error) => {@@ -61,11 +78,11 @@ pub(super) async fn json_new_target(State(state): State<AppState>, uri: Uri) ->.into_response();}};- let target_id = match endpoint+ let created = match endpoint.create_managed_target(requested_target_url(&uri)).await{- Ok(target_id) => target_id,+ Ok(created) => created,Err(error) => {return (StatusCode::INTERNAL_SERVER_ERROR,@@ -74,16 +91,21 @@ pub(super) async fn json_new_target(State(state): State<AppState>, uri: Uri) ->.into_response();}};- let Some(route) = state.cdp_agent_host_directory.lookup_page(&target_id) else {- rollback_unpublished_target(&endpoint, &target_id).await;+ let target_id = match kind {+ DevToolsTargetKind::Page => &created.page_target_id,+ DevToolsTargetKind::Tab => &created.tab_target_id,+ _ => unreachable!("remote debugging discovery only selects page or tab targets"),+ };+ let Some(route) = state.cdp_agent_host_directory.lookup_target(target_id) else {+ rollback_unpublished_target(&endpoint, &created.page_target_id).await;return (StatusCode::INTERNAL_SERVER_ERROR,format!("Created target was not published: {target_id}"),).into_response();};- let Some(target) = dynamic_target_json(&state, route.target_info, for_tab) else {- rollback_unpublished_target(&endpoint, &target_id).await;+ let Some(target) = target_json(&state, route.target_info) else {+ rollback_unpublished_target(&endpoint, &created.page_target_id).await;return (StatusCode::INTERNAL_SERVER_ERROR,format!("Created target descriptor was invalid: {target_id}"),@@ -95,11 +117,11 @@ pub(super) async fn json_new_target(State(state): State<AppState>, uri: Uri) ->async fn rollback_unpublished_target(endpoint: &crate::cdp_frontend::CdpFrontendEndpoint,- target_id: &str,+ page_target_id: &str,) {- if let Err(error) = endpoint.close_target(target_id.to_owned()).await {+ if let Err(error) = endpoint.close_target(page_target_id.to_owned()).await {tracing::warn!(- target_id,+ target_id = page_target_id,?error,"failed to roll back unpublished CDP target");@@ -110,8 +132,8 @@ pub(super) async fn json_activate_target(Path(target_id): Path<String>,State(state): State<AppState>,) -> Response {- let route = state.cdp_agent_host_directory.lookup_page(&target_id);- if target_id == DEFAULT_TARGET_ID && route.is_none() {+ let route = state.cdp_agent_host_directory.lookup_target(&target_id);+ if is_default_target_id(&target_id) && route.is_none() {return (StatusCode::OK, "Target activated").into_response();}let Some(route) = route else {@@ -131,10 +153,10 @@ pub(super) async fn json_close_target(Path(target_id): Path<String>,State(state): State<AppState>,) -> Response {- if target_id == DEFAULT_TARGET_ID {+ if is_default_target_id(&target_id) {return (StatusCode::OK, "Target is closing").into_response();}- let Some(route) = state.cdp_agent_host_directory.lookup_page(&target_id) else {+ let Some(route) = state.cdp_agent_host_directory.lookup_target(&target_id) else {return no_such_target_response(&target_id);};match route.endpoint.close_target(target_id.clone()).await {@@ -155,16 +177,22 @@ fn no_such_target_response(target_id: &str) -> Response {.into_response()}-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)+fn default_target_json(+ state: &AppState,+ target_url: &str,+ kind: DevToolsTargetKind,+) -> serde_json::Value {+ let (target_id, target_type) = match kind {+ DevToolsTargetKind::Page => (DEFAULT_CDP_PAGE_TARGET_ID, "page"),+ DevToolsTargetKind::Tab => (DEFAULT_CDP_TAB_TARGET_ID, "tab"),+ _ => unreachable!("remote debugging discovery only selects page or tab targets"),};+ let (devtools_frontend_url, websocket_debugger_url) =+ target_endpoint_urls(state, target_id).expect("default target URL prefixes must be valid");json!({"description": "","devtoolsFrontendUrl": devtools_frontend_url,- "id": DEFAULT_TARGET_ID,+ "id": target_id,"title": target_url,"type": target_type,"url": target_url,@@ -172,33 +200,14 @@ fn target_json(state: &AppState, target_url: &str, for_tab: bool) -> serde_json:})}-fn dynamic_target_json(- state: &AppState,- target_info: DevToolsTargetInfo,- for_tab: bool,-) -> Option<serde_json::Value> {+fn target_json(state: &AppState, target_info: DevToolsTargetInfo) -> Option<serde_json::Value> {let target_id = target_info.target_id.as_ref()?.as_str();- 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}"),- )+ let target_type = match target_info.kind {+ DevToolsTargetKind::Page => "page",+ DevToolsTargetKind::Tab => "tab",+ _ => return None,};+ let (devtools_frontend_url, websocket_debugger_url) = target_endpoint_urls(state, target_id)?;Some(json!({"description": "","devtoolsFrontendUrl": devtools_frontend_url,@@ -210,6 +219,17 @@ fn dynamic_target_json(}))}+fn target_endpoint_urls(state: &AppState, target_id: &str) -> Option<(String, String)> {+ let websocket_prefix = state.page_ws_url.strip_suffix(DEFAULT_CDP_PAGE_TARGET_ID)?;+ let frontend_prefix = state+ .devtools_frontend_url+ .strip_suffix(DEFAULT_CDP_PAGE_TARGET_ID)?;+ Some((+ format!("{frontend_prefix}{target_id}"),+ format!("{websocket_prefix}{target_id}"),+ ))+}+fn requested_target_url(uri: &Uri) -> String {let target = uri.query()@@ -227,11 +247,26 @@ fn requested_target_url(uri: &Uri) -> String {.unwrap_or_else(|| DEFAULT_TARGET_URL.to_owned())}-fn requests_tab_target(uri: &Uri) -> bool {+fn requested_target_kind(uri: &Uri) -> DevToolsTargetKind {+ if requests_tab_targets(uri) {+ DevToolsTargetKind::Tab+ } else {+ DevToolsTargetKind::Page+ }+}++fn requests_tab_targets(uri: &Uri) -> bool {uri.query().is_some_and(|query| query.split('&').any(|component| component == "for_tab"))}+fn is_default_target_id(target_id: &str) -> bool {+ matches!(+ target_id,+ DEFAULT_CDP_PAGE_TARGET_ID | DEFAULT_CDP_TAB_TARGET_ID+ )+}+pub(super) async fn ws_browser_upgrade_handler(Path(browser_id): Path<String>,ws: WebSocketUpgrade,@@ -246,59 +281,25 @@ pub(super) async fn ws_browser_upgrade_handler(})}-pub(super) async fn ws_page_upgrade_handler(+pub(super) async fn ws_target_upgrade_handler(Path(target_id): Path<String>,ws: WebSocketUpgrade,State(state): State<AppState>,) -> Response {- if target_id == DEFAULT_TARGET_ID {+ if is_default_target_id(&target_id) {let owner_registry = state.cdp_owner_registry;return ws.on_upgrade(move |socket| {run_shared_frontend_socket(socket,owner_registry,- CdpFrontendSocketKind::Page {- target_id: DEFAULT_TARGET_ID.to_owned(),- },+ CdpFrontendSocketKind::Target { target_id },)});}- let Some(route) = state.cdp_agent_host_directory.lookup_page(&target_id) else {+ let Some(route) = state.cdp_agent_host_directory.lookup_target(&target_id) else {return StatusCode::NOT_FOUND.into_response();};- 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;- })+ target_ws_upgrade_response(ws, target_id, route.endpoint)}async fn run_shared_frontend_socket(@@ -316,12 +317,17 @@ async fn run_shared_frontend_socket(run_cdp_frontend_socket(socket, endpoint, kind).await;}-fn page_ws_upgrade_response(+fn target_ws_upgrade_response(ws: WebSocketUpgrade,target_id: String,endpoint: crate::cdp_frontend::CdpFrontendEndpoint,) -> Response {ws.on_upgrade(move |socket| async move {- run_cdp_frontend_socket(socket, endpoint, CdpFrontendSocketKind::Page { target_id }).await;+ run_cdp_frontend_socket(+ socket,+ endpoint,+ CdpFrontendSocketKind::Target { target_id },+ )+ .await;})}diff --git a/moli-protocol-server/src/protocol_server/cdp_agent_host.rs b/moli-protocol-server/src/protocol_server/cdp_agent_host.rsindex 506911dba..91b242a8b 100644--- a/moli-protocol-server/src/protocol_server/cdp_agent_host.rs+++ b/moli-protocol-server/src/protocol_server/cdp_agent_host.rs@@ -22,11 +22,11 @@ pub(super) struct SharedCdpAgentHostDirectory {#[derive(Default)]struct CdpAgentHostDirectoryState {- page_hosts: HashMap<String, CdpPageAgentHost>,+ hosts: HashMap<String, CdpAgentHost>,}#[derive(Clone)]-struct CdpPageAgentHost {+struct CdpAgentHost {owner_id: u64,target_info: DevToolsTargetInfo,endpoint: CdpFrontendEndpoint,@@ -34,12 +34,12 @@ struct CdpPageAgentHost {}#[derive(Clone)]-pub(super) struct CdpPageAgentHostRoute {+pub(super) struct CdpAgentHostRoute {pub(super) endpoint: CdpFrontendEndpoint,pub(super) target_info: DevToolsTargetInfo,}-impl CdpPageAgentHost {+impl CdpAgentHost {fn browser_context_id(&self) -> Option<&str> {self.target_info.browser_context_id@@ -49,22 +49,29 @@ impl CdpPageAgentHost {}impl CdpAgentHostDirectoryState {- fn activate_page_host(&mut self, owner_id: u64, target_id: &str) -> bool {- let browser_context_id = self- .page_hosts+ fn activate_host(&mut self, owner_id: u64, target_id: &str) -> bool {+ let identity = self+ .hosts.get(target_id).filter(|host| host.owner_id == owner_id)- .map(|host| host.browser_context_id().map(str::to_owned));- let Some(browser_context_id) = browser_context_id else {+ .map(|host| {+ (+ host.browser_context_id().map(str::to_owned),+ host.target_info.kind,+ )+ });+ let Some((browser_context_id, kind)) = identity else {return false;};- for host in self.page_hosts.values_mut().filter(|host| {- host.owner_id == owner_id && host.browser_context_id() == browser_context_id.as_deref()+ for host in self.hosts.values_mut().filter(|host| {+ host.owner_id == owner_id+ && host.target_info.kind == kind+ && host.browser_context_id() == browser_context_id.as_deref()}) {host.is_active = false;}- if let Some(host) = self.page_hosts.get_mut(target_id) {+ if let Some(host) = self.hosts.get_mut(target_id) {host.is_active = true;return true;}@@ -88,18 +95,28 @@ impl SharedCdpAgentHostDirectory {})}- pub(super) fn lookup_page(&self, target_id: &str) -> Option<CdpPageAgentHostRoute> {+ pub(super) fn lookup_target(&self, target_id: &str) -> Option<CdpAgentHostRoute> {let state = self.inner.lock();- let host = state.page_hosts.get(target_id)?;- Some(CdpPageAgentHostRoute {+ let host = state.hosts.get(target_id)?;+ Some(CdpAgentHostRoute {endpoint: host.endpoint.clone(),target_info: host.target_info.clone(),})}- pub(super) fn page_target_infos(&self) -> Vec<DevToolsTargetInfo> {+ pub(super) fn remote_debugging_target_infos(+ &self,+ include_tab_targets: bool,+ ) -> Vec<DevToolsTargetInfo> {let state = self.inner.lock();- let mut hosts = state.page_hosts.iter().collect::<Vec<_>>();+ let mut hosts = state+ .hosts+ .iter()+ .filter(|(_, host)| {+ host.target_info.kind == DevToolsTargetKind::Page+ || (include_tab_targets && host.target_info.kind == DevToolsTargetKind::Tab)+ })+ .collect::<Vec<_>>();hosts.sort_by(|(left_id, left), (right_id, right)| {right.is_active@@ -115,7 +132,7 @@ impl SharedCdpAgentHostDirectory {pub(super) fn remove_owner(&self, owner_id: u64) {self.inner.lock()- .page_hosts+ .hosts.retain(|_, host| host.owner_id != owner_id);}@@ -127,24 +144,24 @@ impl SharedCdpAgentHostDirectory {) {match delta {CdpTargetHostLifecycleDelta::Created(target_info) => {- let Some(target_id) = page_target_id(&target_info) else {+ let Some(target_id) = remote_debugging_target_id(&target_info) else {return;};let mut state = self.inner.lock();- if let Some(existing) = state.page_hosts.get(&target_id)+ if let Some(existing) = state.hosts.get(&target_id)&& existing.owner_id != owner_id{tracing::warn!(target_id,existing_owner_id = existing.owner_id,owner_id,- "refusing to replace a live CDP page agent host"+ "refusing to replace a live CDP agent host");return;}- state.page_hosts.insert(+ state.hosts.insert(target_id,- CdpPageAgentHost {+ CdpAgentHost {owner_id,target_info,endpoint: endpoint.clone(),@@ -153,33 +170,28 @@ impl SharedCdpAgentHostDirectory {);}CdpTargetHostLifecycleDelta::InfoChanged(target_info) => {- let Some(target_id) = page_target_id(&target_info) else {+ let Some(target_id) = remote_debugging_target_id(&target_info) else {return;};let mut state = self.inner.lock();- if let Some(host) = state.page_hosts.get_mut(&target_id)+ if let Some(host) = state.hosts.get_mut(&target_id)&& host.owner_id == owner_id{host.target_info = target_info;}}CdpTargetHostLifecycleDelta::Activated { target_id } => {- if self.inner.lock().activate_page_host(owner_id, &target_id) {- endpoint.foreground_tab_changed(target_id);- }+ self.inner.lock().activate_host(owner_id, &target_id);}CdpTargetHostLifecycleDelta::Destroyed { target_id } => {let endpoint = {let mut state = self.inner.lock();if state- .page_hosts+ .hosts.get(&target_id).is_some_and(|host| host.owner_id == owner_id){- state- .page_hosts- .remove(&target_id)- .map(|host| host.endpoint)+ state.hosts.remove(&target_id).map(|host| host.endpoint)} else {None}@@ -192,8 +204,11 @@ impl SharedCdpAgentHostDirectory {}}-fn page_target_id(target_info: &DevToolsTargetInfo) -> Option<String> {- if target_info.kind != DevToolsTargetKind::Page {+fn remote_debugging_target_id(target_info: &DevToolsTargetInfo) -> Option<String> {+ if !matches!(+ target_info.kind,+ DevToolsTargetKind::Page | DevToolsTargetKind::Tab+ ) {return None;}target_infodiff --git a/moli-protocol-server/src/protocol_server/cdp_owner.rs b/moli-protocol-server/src/protocol_server/cdp_owner.rsindex 807ee6d7c..e41544f49 100644--- a/moli-protocol-server/src/protocol_server/cdp_owner.rs+++ b/moli-protocol-server/src/protocol_server/cdp_owner.rs@@ -53,6 +53,7 @@ struct CdpOwnerRecord {struct CdpOwnerRuntimeConfig {directory: SharedCdpAgentHostDirectory,target_id_allocator: Arc<AtomicU64>,+ tab_target_id_allocator: Arc<AtomicU64>,cookie_profile: SharedCookieProfile,storage_partition: Arc<StoragePartitionState>,navigation_runtime_config: NavigationRuntimeConfig,@@ -62,6 +63,7 @@ impl SharedCdpOwnerRegistry {pub(super) fn new(directory: SharedCdpAgentHostDirectory,target_id_allocator: Arc<AtomicU64>,+ tab_target_id_allocator: Arc<AtomicU64>,cookie_profile: SharedCookieProfile,storage_partition: Arc<StoragePartitionState>,navigation_runtime_config: NavigationRuntimeConfig,@@ -71,6 +73,7 @@ impl SharedCdpOwnerRegistry {config: CdpOwnerRuntimeConfig {directory,target_id_allocator,+ tab_target_id_allocator,cookie_profile,storage_partition,navigation_runtime_config,@@ -132,6 +135,7 @@ impl SharedCdpOwnerRegistry {self.inner.config.navigation_runtime_config.clone(),Some(CdpTargetHostIntegration::new(self.inner.config.target_id_allocator.clone(),+ self.inner.config.tab_target_id_allocator.clone(),lifecycle_observer,)),Some(CdpOwnerActorLifecycle {diff --git a/moli-protocol-server/src/protocol_server/cdp_socket.rs b/moli-protocol-server/src/protocol_server/cdp_socket.rsindex ccda9dd84..e5f34edf3 100644--- a/moli-protocol-server/src/protocol_server/cdp_socket.rs+++ b/moli-protocol-server/src/protocol_server/cdp_socket.rs@@ -6,8 +6,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 },+ Target { target_id: String },}pub(super) async fn run_cdp_frontend_socket(@@ -20,13 +19,8 @@ pub(super) async fn run_cdp_frontend_socket(let socket_sink = sink.clone();let frontend_id = match &kind {CdpFrontendSocketKind::Browser => endpoint.attach_browser(sink).await,- 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+ CdpFrontendSocketKind::Target { target_id } => {+ endpoint.attach_target(target_id.clone(), sink).await}};let frontend_id = match frontend_id {@@ -41,8 +35,7 @@ pub(super) async fn run_cdp_frontend_socket(frontend_id: Some(frontend_id),kind: match kind {CdpFrontendSocketKind::Browser => CdpFrontendKind::Browser,- CdpFrontendSocketKind::Page { .. } => CdpFrontendKind::Page,- CdpFrontendSocketKind::ForegroundTab { .. } => CdpFrontendKind::ForegroundTab,+ CdpFrontendSocketKind::Target { .. } => CdpFrontendKind::Target,},};@@ -101,8 +94,7 @@ async fn wait_for_peer_close(socket_rx: &mut futures_util::stream::SplitStream<Wenum CdpFrontendKind {Browser,- Page,- ForegroundTab,+ Target,}struct CdpFrontendDetachGuard {@@ -118,10 +110,7 @@ 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);- }+ CdpFrontendKind::Target => self.endpoint.detach_target(frontend_id),}}}diff --git a/moli-protocol-server/src/protocol_server/mod.rs b/moli-protocol-server/src/protocol_server/mod.rsindex cd31c96aa..bf93f07c9 100644--- a/moli-protocol-server/src/protocol_server/mod.rs+++ b/moli-protocol-server/src/protocol_server/mod.rs@@ -22,7 +22,9 @@ use moli_core::{runtime::{NavigationRuntimeConfig, storage_partition::StoragePartitionState},};use moli_fetch::FetchConfig;-use moli_protocol::CdpInitialStoragePartition;+#[cfg(test)]+use moli_protocol::DEFAULT_CDP_TAB_TARGET_ID;+use moli_protocol::{CdpInitialStoragePartition, DEFAULT_CDP_PAGE_TARGET_ID};#[cfg(test)]use parking_lot::Mutex;use tokio::net::TcpListener;@@ -49,7 +51,9 @@ use webdriver_bidi::SharedBidiSessionRegistry;use webdriver_classic::SharedClassicSessionRegistry;const DEFAULT_BROWSER_ID: &str = "moli-browser";-const DEFAULT_TARGET_ID: &str = "moli-default";+const DEFAULT_TARGET_ID: &str = DEFAULT_CDP_PAGE_TARGET_ID;+#[cfg(test)]+const DEFAULT_TAB_TARGET_ID: &str = DEFAULT_CDP_TAB_TARGET_ID;const DEFAULT_TARGET_URL: &str = "about:blank";#[derive(Debug, Clone)]@@ -195,19 +199,11 @@ fn build_router(app_state: AppState) -> Router {).route("/devtools/page/{target_id}",- get(cdp::ws_page_upgrade_handler),+ get(cdp::ws_target_upgrade_handler),).route("/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),+ get(cdp::ws_target_upgrade_handler),).route("/session",@@ -742,14 +738,12 @@ 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,9 +794,11 @@ impl AppState {) -> Self {let cdp_agent_host_directory = SharedCdpAgentHostDirectory::default();let cdp_target_id_allocator = Arc::new(AtomicU64::new(0));+ let cdp_tab_target_id_allocator = Arc::new(AtomicU64::new(0));let cdp_owner_registry = SharedCdpOwnerRegistry::new(cdp_agent_host_directory.clone(),cdp_target_id_allocator,+ cdp_tab_target_id_allocator,cookie_profile.clone(),storage_partition.clone(),navigation_runtime_config.clone(),@@ -810,17 +806,13 @@ 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?targetType=tab&ws={addr}/devtools/tab/{DEFAULT_TARGET_ID}"- ),- tab_devtools_frontend_url: format!(- "/devtools/inspector.html?ws={addr}/devtools/tab/{DEFAULT_TARGET_ID}"+ "/devtools/inspector.html?ws={addr}/devtools/page/{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.rsindex b9b6fab07..37dc8909a 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,33 +26,42 @@ 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 {+async fn discovered_tab_websocket_url(addr: std::net::SocketAddr, tab_target_id: &str) -> String {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");+ .find(|target| target["id"] == json!(tab_target_id))+ .expect("discovered tab target");assert_eq!(target["type"], json!("tab"));+ assert_eq!(+ target["devtoolsFrontendUrl"],+ json!(format!(+ "/devtools/inspector.html?ws={addr}/devtools/page/{tab_target_id}"+ )),+ "remote discovery uses the same inspector URL shape for Page and Tab hosts"+ );let websocket_url = target["webSocketDebuggerUrl"].as_str()- .expect("foreground tab websocket URL");- assert!(websocket_url.contains("/devtools/tab/"));+ .expect("tab websocket URL");+ assert!(websocket_url.contains("/devtools/page/"));+ websocket_url.to_owned()+}++async fn connect_discovered_tab(addr: std::net::SocketAddr, tab_target_id: &str) -> TestCdpSocket {+ let websocket_url = discovered_tab_websocket_url(addr, tab_target_id).await;connect_async(websocket_url).await- .expect("foreground tab websocket should connect")+ .expect("tab websocket should connect").0}-async fn enable_foreground_tab_page(+async fn enable_tab_page(socket: &mut TestCdpSocket,command_id: u64,- target_id: &str,+ page_target_id: &str,) -> String {send_cdp_command_without_wait(socket,@@ -71,7 +80,7 @@ async fn enable_foreground_tab_page(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)+ && message["params"]["targetInfo"]["targetId"] == json!(page_target_id){attached_session_id = message["params"]["sessionId"].as_str().map(str::to_owned);}@@ -79,41 +88,7 @@ async fn enable_foreground_tab_page(}).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+ attached_session_id.expect("tab child page session")}async fn wait_for_websocket_close(socket: &mut TestCdpSocket, label: &str) {@@ -198,8 +173,8 @@ async fn puppeteer_auto_attach_existing_page(browser: &mut TestCdpSocket,command_id: u64,page_target_id: &str,+ tab_target_id: &str,) -> String {- let tab_target_id = format!("TAB-{page_target_id}");send_cdp_command_without_wait(browser,command_id,@@ -547,7 +522,7 @@ async fn websocket_cdp_dynamic_page_routes_to_existing_target_owner() {assert_eq!(listed_target["devtoolsFrontendUrl"],json!(format!(- "/devtools/inspector.html?targetType=tab&ws={addr}/devtools/tab/{target_id}"+ "/devtools/inspector.html?ws={addr}/devtools/page/{target_id}")));let mut page = connect_dynamic_page(addr, &target_id).await;@@ -566,6 +541,17 @@ async fn websocket_cdp_dynamic_page_routes_to_existing_target_owner() {panic!("browser frontend received direct-page parse output: {message:#?}");}+ let page_owner_info =+ send_cdp_command(&mut page, 7000, "Target.getTargetInfo", None, json!({})).await;+ assert_eq!(+ response_by_id(&page_owner_info, 7000)["result"]["targetInfo"]["targetId"],+ json!(target_id)+ );+ assert_eq!(+ response_by_id(&page_owner_info, 7000)["result"]["targetInfo"]["type"],+ json!("page")+ );+let frame_tree = send_cdp_command(&mut page, 1, "Page.getFrameTree", None, json!({})).await;let frame_tree_response = response_by_id(&frame_tree, 1);assert_eq!(@@ -598,6 +584,16 @@ async fn websocket_cdp_dynamic_page_routes_to_existing_target_owner() {.all(|message| message["method"] != json!("Target.attachedToTarget")),"private page frontend attach leaked to browser frontend: {browser_probe:#?}");+ let browser_page_command =+ send_cdp_command(&mut browser, 3, "Page.getFrameTree", None, json!({})).await;+ assert_eq!(+ response_by_id(&browser_page_command, 3)["error"],+ json!({+ "code": -32601,+ "message": "'Page.getFrameTree' wasn't found"+ }),+ "the Browser AgentHost must not proxy Page commands to the active target"+ );let attach = send_cdp_command(&mut browser,@@ -669,18 +665,313 @@ async fn websocket_cdp_dynamic_page_routes_to_existing_target_owner() {}#[tokio::test(flavor = "multi_thread", worker_threads = 2)]-async fn foreground_blank_click_activates_popup_browser_surface() {+async fn target_create_for_tab_exposes_distinct_chromium_agent_hosts() {+ let (addr, server) = spawn_test_protocol_server().await;+ let (mut browser, _) =+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))+ .await+ .expect("connect browser websocket");++ let discover = send_cdp_command(+ &mut browser,+ 1,+ "Target.setDiscoverTargets",+ None,+ json!({ "discover": true, "filter": [{}] }),+ )+ .await;+ assert_eq!(response_by_id(&discover, 1)["result"], json!({}));++ send_cdp_command_without_wait(+ &mut browser,+ 2,+ "Target.createTarget",+ None,+ json!({ "url": "about:blank", "forTab": true }),+ )+ .await;+ let mut saw_response = false;+ let mut page_target_id = None;+ let mut tab_target_id = None;+ let created = recv_until_match(&mut browser, |message| {+ saw_response |= message["id"] == json!(2_u64);+ if message["method"] == json!("Target.targetCreated") {+ let info = &message["params"]["targetInfo"];+ let target_id = info["targetId"].as_str().map(str::to_owned);+ match info["type"].as_str() {+ Some("page") if target_id.as_deref() != Some(DEFAULT_TARGET_ID) => {+ page_target_id = target_id;+ }+ Some("tab") if target_id.as_deref() != Some(DEFAULT_TAB_TARGET_ID) => {+ tab_target_id = target_id;+ }+ _ => {}+ }+ }+ saw_response && page_target_id.is_some() && tab_target_id.is_some()+ })+ .await;+ let page_target_id = page_target_id.expect("created Page target id");+ let tab_target_id = tab_target_id.expect("created Tab target id");+ assert_ne!(page_target_id, tab_target_id);+ assert_eq!(+ response_by_id(&created, 2)["result"]["targetId"],+ json!(tab_target_id),+ "forTab=true must return the stable Tab AgentHost"+ );+ let tab_created = created+ .iter()+ .position(|message| {+ message["method"] == json!("Target.targetCreated")+ && message["params"]["targetInfo"]["targetId"] == json!(tab_target_id)+ })+ .expect("Tab targetCreated");+ let page_created = created+ .iter()+ .position(|message| {+ message["method"] == json!("Target.targetCreated")+ && message["params"]["targetInfo"]["targetId"] == json!(page_target_id)+ })+ .expect("Page targetCreated");+ assert!(+ tab_created < page_created,+ "Chromium publishes the WebContents Tab host before its primary Page host: {created:#?}"+ );++ let mut tab = connect_discovered_tab(addr, &tab_target_id).await;+ let tab_info = send_cdp_command(&mut tab, 1, "Target.getTargetInfo", None, json!({})).await;+ assert_eq!(+ response_by_id(&tab_info, 1)["result"]["targetInfo"]["targetId"],+ json!(tab_target_id)+ );+ assert_eq!(+ response_by_id(&tab_info, 1)["result"]["targetInfo"]["type"],+ json!("tab")+ );+ let tab_page_session = enable_tab_page(&mut tab, 2, &page_target_id).await;+ let child_info = send_cdp_command(+ &mut tab,+ 4,+ "Target.getTargetInfo",+ Some(&tab_page_session),+ json!({}),+ )+ .await;+ assert_eq!(+ response_by_id(&child_info, 4)["result"]["targetInfo"]["targetId"],+ json!(page_target_id)+ );+ assert_eq!(+ response_by_id(&child_info, 4)["result"]["targetInfo"]["type"],+ json!("page")+ );++ send_cdp_command_without_wait(+ &mut browser,+ 3,+ "Target.closeTarget",+ None,+ json!({ "targetId": tab_target_id }),+ )+ .await;+ let mut saw_close_response = false;+ let mut saw_page_destroyed = false;+ let mut saw_tab_destroyed = false;+ let closed = recv_until_match(&mut browser, |message| {+ saw_close_response |= message["id"] == json!(3_u64);+ if message["method"] == json!("Target.targetDestroyed") {+ saw_page_destroyed |= message["params"]["targetId"] == json!(page_target_id);+ saw_tab_destroyed |= message["params"]["targetId"] == json!(tab_target_id);+ }+ saw_close_response && saw_page_destroyed && saw_tab_destroyed+ })+ .await;+ assert_eq!(response_by_id(&closed, 3)["result"]["success"], json!(true));+ let page_destroyed = closed+ .iter()+ .position(|message| {+ message["method"] == json!("Target.targetDestroyed")+ && message["params"]["targetId"] == json!(page_target_id)+ })+ .expect("Page targetDestroyed");+ let tab_destroyed = closed+ .iter()+ .position(|message| {+ message["method"] == json!("Target.targetDestroyed")+ && message["params"]["targetId"] == json!(tab_target_id)+ })+ .expect("Tab targetDestroyed");+ assert!(+ page_destroyed < tab_destroyed,+ "Chromium destroys the Page host before its owning Tab host: {closed:#?}"+ );++ abort_test_cdp_server(server).await;+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn page_agent_host_and_tab_host_survive_document_navigation() {+ let (addr, server) = spawn_test_protocol_server().await;+ let (mut browser, _) =+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))+ .await+ .expect("connect browser websocket");+ let (mut page, _) = connect_async(format!("ws://{addr}/devtools/page/{DEFAULT_TARGET_ID}"))+ .await+ .expect("connect default Page websocket");+ let mut tab = connect_discovered_tab(addr, DEFAULT_TAB_TARGET_ID).await;++ let discover = send_cdp_command(+ &mut browser,+ 1,+ "Target.setDiscoverTargets",+ None,+ json!({ "discover": true, "filter": [{}] }),+ )+ .await;+ assert_eq!(response_by_id(&discover, 1)["result"], json!({}));++ let page_before = send_cdp_command(&mut page, 1, "Target.getTargetInfo", None, json!({})).await;+ let tab_before = send_cdp_command(&mut tab, 1, "Target.getTargetInfo", None, json!({})).await;+ assert_eq!(+ response_by_id(&page_before, 1)["result"]["targetInfo"]["targetId"],+ json!(DEFAULT_TARGET_ID)+ );+ assert_eq!(+ response_by_id(&tab_before, 1)["result"]["targetInfo"]["targetId"],+ json!(DEFAULT_TAB_TARGET_ID)+ );++ let destination = "data:text/html,<title>Stable Navigation Host</title>";+ let navigation = send_cdp_command(+ &mut page,+ 2,+ "Page.navigate",+ None,+ json!({ "url": destination }),+ )+ .await;+ assert_eq!(+ response_by_id(&navigation, 2)["result"]["frameId"],+ json!(DEFAULT_TARGET_ID),+ "the stable Page AgentHost id is also the main Frame id"+ );+ let title = send_cdp_command(+ &mut page,+ 3,+ "Runtime.evaluate",+ None,+ json!({ "expression": "document.title", "returnByValue": true }),+ )+ .await;+ assert_eq!(+ response_by_id(&title, 3)["result"]["result"]["value"],+ json!("Stable Navigation Host")+ );++ let mut target_events = recv_until_match(&mut browser, |message| {+ message["method"] == json!("Target.targetInfoChanged")+ && message["params"]["targetInfo"]["targetId"] == json!(DEFAULT_TARGET_ID)+ && message["params"]["targetInfo"]["url"] == json!(destination)+ })+ .await;+ target_events+ .extend(send_cdp_command(&mut browser, 2, "Browser.getVersion", None, json!({})).await);+ target_events.extend(recv_cdp_messages_for(&mut browser, Duration::from_millis(100)).await);+ assert!(+ target_events.iter().all(|message| {+ message["method"] != json!("Target.targetInfoChanged")+ || message["params"]["targetInfo"]["targetId"] != json!(DEFAULT_TAB_TARGET_ID)+ }),+ "document navigation must update the Page target without mirroring a Tab event: {target_events:#?}"+ );++ let descriptors = timeout(Duration::from_secs(5), async {+ loop {+ let descriptors = fetch_server_json(addr, "/json/list?for_tab").await;+ if descriptors.as_array().is_some_and(|targets| {+ targets.iter().any(|target| {+ target["id"] == json!(DEFAULT_TAB_TARGET_ID)+ && target["url"] == json!(destination)+ && target["title"] == json!("Stable Navigation Host")+ })+ }) {+ break descriptors;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("Tab discovery metadata should follow its primary Page");+ assert!(descriptors.as_array().is_some_and(|targets| {+ targets.iter().any(|target| {+ target["id"] == json!(DEFAULT_TARGET_ID)+ && target["type"] == json!("page")+ && target["url"] == json!(destination)+ })+ }));++ let frame_tree = send_cdp_command(&mut page, 4, "Page.getFrameTree", None, json!({})).await;+ assert_eq!(+ response_by_id(&frame_tree, 4)["result"]["frameTree"]["frame"]["id"],+ json!(DEFAULT_TARGET_ID)+ );+ let page_after = send_cdp_command(&mut page, 5, "Target.getTargetInfo", None, json!({})).await;+ let tab_after = send_cdp_command(&mut tab, 2, "Target.getTargetInfo", None, json!({})).await;+ assert_eq!(+ response_by_id(&page_after, 5)["result"]["targetInfo"]["targetId"],+ json!(DEFAULT_TARGET_ID)+ );+ assert_eq!(+ response_by_id(&tab_after, 2)["result"]["targetInfo"]["targetId"],+ json!(DEFAULT_TAB_TARGET_ID)+ );++ abort_test_cdp_server(server).await;+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn tab_websocket_stays_bound_to_its_page_when_a_popup_becomes_active() {let (addr, server) = spawn_test_protocol_server().await;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_tab_websocket_url = discovered_tab_websocket_url(addr, DEFAULT_TAB_TARGET_ID).await;+ let mut opener_tab = connect_async(&opener_tab_websocket_url)+ .await+ .expect("connect opener tab websocket")+ .0;+ let tab_owner_info = send_cdp_command(+ &mut opener_tab,+ 9001,+ "Target.getTargetInfo",+ None,+ json!({}),+ )+ .await;+ assert_eq!(+ response_by_id(&tab_owner_info, 9001)["result"]["targetInfo"]["targetId"],+ json!(DEFAULT_TAB_TARGET_ID)+ );+ assert_eq!(+ response_by_id(&tab_owner_info, 9001)["result"]["targetInfo"]["type"],+ json!("tab")+ );+ let tab_page_command =+ send_cdp_command(&mut opener_tab, 9002, "Page.getFrameTree", None, json!({})).await;+ assert_eq!(+ response_by_id(&tab_page_command, 9002)["error"],+ json!({+ "code": -32601,+ "message": "'Page.getFrameTree' wasn't found"+ }),+ "the Tab AgentHost must expose its Page through Target auto-attach"+ );+ let opener_page_session = enable_tab_page(&mut opener_tab, 1, DEFAULT_TARGET_ID).await;+ let popup_url = "data:text/html,%3Ctitle%3EStable%20Popup%3C/title%3E";+ let popup_final_url = "data:text/html,<title>Stable Popup</title>";let opener_url = format!(- "data:text/html,<title>Popup Opener</title>\+ "data:text/html,<title>Stable Opener</title>\<a id='popup' href='{popup_url}' \target='_blank' style='display:block;width:200px;height:100px'>open</a>");@@ -726,11 +1017,11 @@ async fn foreground_blank_click_activates_popup_browser_surface() {.any(|message| is_screencast_visibility(message, true)));- let foreground_link = send_cdp_command(- &mut foreground_tab,+ let opener_link = send_cdp_command(+ &mut opener_tab,3,"Runtime.evaluate",- Some(&opener_foreground_session),+ Some(&opener_page_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@@ -738,18 +1029,11 @@ async fn foreground_blank_click_activates_popup_browser_surface() {).await;assert_eq!(- response_by_id(&foreground_link, 3)["result"]["result"]["value"]["link"],+ response_by_id(&opener_link, 3)["result"]["result"]["value"]["link"],json!(popup_final_url));- dispatch_primary_click(- &mut foreground_tab,- 5,- Some(&opener_foreground_session),- 20,- 20,- )- .await;+ dispatch_primary_click(&mut opener_tab, 5, Some(&opener_page_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)@@ -789,12 +1073,6 @@ async fn foreground_blank_click_activates_popup_browser_surface() {.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,@@ -802,17 +1080,21 @@ async fn foreground_blank_click_activates_popup_browser_surface() {|targets| {targets.len() == 2&& targets[0]["id"] != json!(DEFAULT_TARGET_ID)- && targets[0]["title"] == json!("Foreground Popup")- && targets[1]["title"] == json!("Popup Opener")+ && targets[0]["title"] == json!("Stable Popup")+ && targets[1]["title"] == json!("Stable Opener")},).await;assert_eq!(targets[0]["id"], json!(&popup_target_id));- let foreground_popup = send_cdp_command(- &mut foreground_tab,++ // A tab endpoint is a durable DevToolsAgentHost. Bringing another tab to+ // the foreground must not detach its child Page session or retarget the+ // socket to the new foreground Page.+ let opener_after_popup = send_cdp_command(+ &mut opener_tab,9,"Runtime.evaluate",- Some(&popup_foreground_session),+ Some(&opener_page_session),json!({"expression": "location.href","returnByValue": true@@ -820,14 +1102,76 @@ async fn foreground_blank_click_activates_popup_browser_surface() {).await;assert_eq!(- response_by_id(&foreground_popup, 9)["result"]["result"]["value"],- json!(popup_final_url)+ response_by_id(&opener_after_popup, 9)["result"]["result"]["value"],+ json!(&opener_url));- assert_eq!(targets[0]["title"], json!("Foreground Popup"));+ assert!(+ opener_after_popup.iter().all(|message| {+ let detached_from_opener = message["method"] == json!("Target.detachedFromTarget")+ && message["params"]["sessionId"] == json!(opener_page_session);+ let attached_to_popup = message["method"] == json!("Target.attachedToTarget")+ && message["params"]["targetInfo"]["targetId"] == json!(popup_target_id);+ !(detached_from_opener || attached_to_popup)+ }),+ "the opener tab socket migrated to the foreground popup: {opener_after_popup:#?}"+ );+ assert_eq!(targets[0]["title"], json!("Stable Popup"));assert_eq!(targets[1]["id"], json!(DEFAULT_TARGET_ID));- assert_eq!(targets[1]["title"], json!("Popup Opener"));+ assert_eq!(targets[1]["title"], json!("Stable Opener"));assert_eq!(targets[1]["url"], json!(&opener_url));+ let tab_targets = fetch_server_json(addr, "/json/list?for_tab").await;+ let tab_targets = tab_targets.as_array().expect("tab target list");+ let opener_tab_descriptor = tab_targets+ .iter()+ .find(|target| target["id"] == json!(DEFAULT_TAB_TARGET_ID))+ .expect("stable opener tab descriptor");+ assert_eq!(opener_tab_descriptor["title"], json!("Stable Opener"));+ assert_eq!(opener_tab_descriptor["url"], json!(&opener_url));+ let popup_tab_target_id = tab_targets+ .iter()+ .find(|target| target["type"] == json!("tab") && target["title"] == json!("Stable Popup"))+ .and_then(|target| target["id"].as_str())+ .expect("stable popup tab target id")+ .to_owned();+ assert_ne!(popup_tab_target_id, DEFAULT_TAB_TARGET_ID);++ // This URL was discovered before popup activation. It still identifies+ // the opener tab after the browser context's active page has changed.+ let mut late_opener_tab = connect_async(&opener_tab_websocket_url)+ .await+ .expect("connect opener tab from stale discovery descriptor")+ .0;+ let late_opener_page_session =+ enable_tab_page(&mut late_opener_tab, 1, DEFAULT_TARGET_ID).await;+ let late_opener_location = send_cdp_command(+ &mut late_opener_tab,+ 3,+ "Runtime.evaluate",+ Some(&late_opener_page_session),+ json!({ "expression": "location.href", "returnByValue": true }),+ )+ .await;+ assert_eq!(+ response_by_id(&late_opener_location, 3)["result"]["result"]["value"],+ json!(&opener_url)+ );++ let mut popup_tab = connect_discovered_tab(addr, &popup_tab_target_id).await;+ let popup_page_session = enable_tab_page(&mut popup_tab, 1, &popup_target_id).await;+ let popup_location = send_cdp_command(+ &mut popup_tab,+ 3,+ "Runtime.evaluate",+ Some(&popup_page_session),+ json!({ "expression": "location.href", "returnByValue": true }),+ )+ .await;+ assert_eq!(+ response_by_id(&popup_location, 3)["result"]["result"]["value"],+ json!(popup_final_url)+ );+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);@@ -858,8 +1202,12 @@ async fn foreground_blank_click_activates_popup_browser_surface() {.any(|message| is_screencast_visibility(message, true)));- let (activate_status, _) =- fetch_server_response(addr, "GET", "/json/activate/moli-default").await;+ let (activate_status, _) = fetch_server_response(+ addr,+ "GET",+ &format!("/json/activate/{DEFAULT_TAB_TARGET_ID}"),+ )+ .await;assert_eq!(activate_status, 200);wait_for_target_list(addr,@@ -875,17 +1223,11 @@ async fn foreground_blank_click_activates_popup_browser_surface() {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,+ let restored_opener = send_cdp_command(+ &mut opener_tab,10,"Runtime.evaluate",- Some(&restored_foreground_session),+ Some(&opener_page_session),json!({"expression": "location.href","returnByValue": true@@ -893,12 +1235,24 @@ async fn foreground_blank_click_activates_popup_browser_surface() {).await;assert_eq!(- response_by_id(&foreground_opener, 10)["result"]["result"]["value"],+ response_by_id(&restored_opener, 10)["result"]["result"]["value"],json!(&opener_url));+ let parked_popup = send_cdp_command(+ &mut popup_tab,+ 4,+ "Runtime.evaluate",+ Some(&popup_page_session),+ json!({ "expression": "location.href", "returnByValue": true }),+ )+ .await;+ assert_eq!(+ response_by_id(&parked_popup, 4)["result"]["result"]["value"],+ json!(popup_final_url)+ );- let restored_opener = evaluate_page_surface(&mut opener, 11).await;- assert_page_surface_active(&restored_opener, true);+ let restored_opener_surface = evaluate_page_surface(&mut opener, 11).await;+ assert_page_surface_active(&restored_opener_surface, true);let demoted_popup = evaluate_page_surface(&mut popup, 12).await;assert_page_surface_active(&demoted_popup, false);@@ -2256,7 +2610,9 @@ async fn websocket_cdp_puppeteer_reconnect_replays_existing_runtime_context() {connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}")).await.expect("connect first browser websocket");- let page_session_id = puppeteer_auto_attach_existing_page(&mut browser, 1, &target_id).await;+ let page_session_id =+ puppeteer_auto_attach_existing_page(&mut browser, 1, &target_id, DEFAULT_TAB_TARGET_ID)+ .await;let page_enabled = send_cdp_command(&mut browser,3,@@ -2303,7 +2659,8 @@ async fn websocket_cdp_puppeteer_reconnect_replays_existing_runtime_context() {.await.expect("connect replacement browser websocket");let replacement_page_session_id =- puppeteer_auto_attach_existing_page(&mut replacement, 1, &target_id).await;+ puppeteer_auto_attach_existing_page(&mut replacement, 1, &target_id, DEFAULT_TAB_TARGET_ID)+ .await;assert_ne!(replacement_page_session_id, page_session_id);let page_enabled = send_cdp_command(&mut replacement,diff --git a/moli-protocol-server/src/protocol_server/tests/misc.rs b/moli-protocol-server/src/protocol_server/tests/misc.rsindex 2683443a8..2fb753890 100644--- a/moli-protocol-server/src/protocol_server/tests/misc.rs+++ b/moli-protocol-server/src/protocol_server/tests/misc.rs@@ -240,9 +240,7 @@ async fn discovery_endpoints_accept_trailing_slashes() {assert_eq!(list[0]["description"], json!(""));assert_eq!(list[0]["devtoolsFrontendUrl"],- json!(- "/devtools/inspector.html?targetType=tab&ws=127.0.0.1:9222/devtools/tab/moli-default"- )+ json!("/devtools/inspector.html?ws=127.0.0.1:9222/devtools/page/moli-default"));assert_eq!(list[0]["id"], json!(DEFAULT_TARGET_ID));assert_eq!(list[0]["title"], json!(DEFAULT_TARGET_URL));@@ -521,14 +519,28 @@ async fn chromium_devtools_json_list_accepts_non_get_methods_and_for_tab() {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.as_array().map(Vec::len), Some(2));+ assert!(tab_list.as_array().is_some_and(|targets| {+ targets.iter().any(|target| {+ target["id"] == json!(DEFAULT_TARGET_ID) && target["type"] == json!("page")+ })+ }));+ let tab = tab_list+ .as_array()+ .and_then(|targets| {+ targets+ .iter()+ .find(|target| target["id"] == json!(DEFAULT_TAB_TARGET_ID))+ })+ .expect("for_tab discovery should add the stable tab target");+ assert_eq!(tab["type"], json!("tab"));assert_eq!(- tab_list[0]["devtoolsFrontendUrl"],- json!("/devtools/inspector.html?ws=127.0.0.1:9222/devtools/tab/moli-default")+ tab["devtoolsFrontendUrl"],+ json!("/devtools/inspector.html?ws=127.0.0.1:9222/devtools/page/moli-default-tab"));assert_eq!(- tab_list[0]["webSocketDebuggerUrl"],- json!("ws://127.0.0.1:9222/devtools/tab/moli-default")+ tab["webSocketDebuggerUrl"],+ json!("ws://127.0.0.1:9222/devtools/page/moli-default-tab"));}@@ -560,7 +572,7 @@ async fn chromium_devtools_json_new_uses_put_and_decodes_first_query_component()assert!(target["webSocketDebuggerUrl"].as_str()- .is_some_and(|url| url.contains("/devtools/tab/"))+ .is_some_and(|url| url.contains("/devtools/page/TAB-")));let target = request_json_with_method(Method::PUT, "/json/new?url=about%3Ablank%23named").await;diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rsindex 71fd47054..ea8ef8571 100644--- a/moli-protocol/src/conn.rs+++ b/moli-protocol/src/conn.rs@@ -27,6 +27,9 @@ use moli_core::{},};+pub const DEFAULT_CDP_PAGE_TARGET_ID: &str = "moli-default";+pub const DEFAULT_CDP_TAB_TARGET_ID: &str = "moli-default-tab";+mod activity_source;mod bidi_channel_work;mod body_spool;@@ -1129,6 +1132,8 @@ pub struct CdpConnection {next_bc_id: u32,next_target_id: u32,shared_target_id_allocator: Option<Arc<AtomicU64>>,+ next_tab_target_id: u32,+ shared_tab_target_id_allocator: Option<Arc<AtomicU64>>,next_session_id: u32,next_page_domain_subscription_generation: u64,next_internal_runtime_command_id: u64,@@ -1370,6 +1375,8 @@ impl CdpConnection {next_global_io_stream_id: 0,next_target_id: 0,shared_target_id_allocator: None,+ next_tab_target_id: 0,+ shared_tab_target_id_allocator: None,next_session_id: 0,next_page_domain_subscription_generation: 0,next_internal_runtime_command_id: 902_000_000,@@ -1409,6 +1416,10 @@ impl CdpConnection {self.shared_target_id_allocator = Some(allocator);}+ pub fn set_shared_tab_target_id_allocator(&mut self, allocator: Arc<AtomicU64>) {+ self.shared_tab_target_id_allocator = Some(allocator);+ }+pub fn set_target_host_lifecycle_observer(&mut self, observer: CdpTargetHostLifecycleObserver) {self.target_host_lifecycle_observer = Some(observer);}@@ -3429,19 +3440,27 @@ impl CdpConnection {}pub fn default_target_id(&self) -> &'static str {- "moli-default"+ DEFAULT_CDP_PAGE_TARGET_ID}- pub(crate) fn derived_tab_target_id(page_target_id: &str) -> String {- format!("TAB-{page_target_id}")+ pub fn default_tab_target_id(&self) -> &'static str {+ DEFAULT_CDP_TAB_TARGET_ID}pub(crate) fn register_top_level_page_target(&mut self, page_target_id: &str) -> String {- let tab_target_id = Self::derived_tab_target_id(page_target_id);+ let tab_target_id = if page_target_id == self.default_target_id() {+ self.default_tab_target_id().to_owned()+ } else {+ self.gen_tab_target_id()+ };self.target_control- .register_top_level_page(page_target_id.to_owned(), tab_target_id.clone());- if let Some(target_info) = self.target_info_for_host_delta(page_target_id) {- self.notify_target_host_lifecycle(CdpTargetHostLifecycleDelta::Created(target_info));+ .register_tab(tab_target_id.clone(), page_target_id.to_owned());+ for target_id in [&tab_target_id, page_target_id] {+ if let Some(target_info) = self.target_info_for_host_delta(target_id) {+ self.notify_target_host_lifecycle(CdpTargetHostLifecycleDelta::Created(+ target_info,+ ));+ }}tab_target_id}@@ -3459,30 +3478,18 @@ impl CdpConnection {self.target_control.remove_worker(target_id)}- pub(crate) fn tab_target_id_for_page_target_id(&self, page_target_id: &str) -> Option<&str> {+ #[doc(hidden)]+ pub fn tab_target_id_for_page_target_id(&self, page_target_id: &str) -> Option<&str> {self.target_control.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(+ pub(crate) fn primary_page_target_id_for_tab_target_id(&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> {+ tab_target_id: &str,+ ) -> Option<&str> {self.target_control- .page_target_id_for_tab_target_id(tab_target_id)+ .primary_page_target_id_for_tab_target_id(tab_target_id)}pub(crate) fn primary_session_id_for_tab_target_id(&self, tab_target_id: &str) -> Option<&str> {@@ -3504,16 +3511,18 @@ impl CdpConnection {self.target_control.remove_tab_session(session_id)}- pub(crate) fn remove_top_level_page_target_by_page_target_id(+ pub(crate) fn remove_tab_for_page_target(&mut self,page_target_id: &str,) -> Option<TargetClosurePlan> {let closure_plan = self.target_control- .remove_top_level_page_by_page_target_id(page_target_id)?;- self.notify_target_host_lifecycle(CdpTargetHostLifecycleDelta::Destroyed {- target_id: page_target_id.to_owned(),- });+ .remove_tab_by_page_target_id(page_target_id)?;+ for target_id in closure_plan.destroyed_target_ids() {+ self.notify_target_host_lifecycle(CdpTargetHostLifecycleDelta::Destroyed {+ target_id: target_id.to_owned(),+ });+ }Some(closure_plan)}@@ -3522,9 +3531,7 @@ impl CdpConnection {page_target_id: &str,reason: Option<&str>,) -> TargetEventPlan {- let Some(closure_plan) =- self.remove_top_level_page_target_by_page_target_id(page_target_id)- else {+ let Some(closure_plan) = self.remove_tab_for_page_target(page_target_id) else {return TargetEventPlan::default();};debug_assert!(@@ -3532,9 +3539,9 @@ impl CdpConnection {.destroyed_target_ids().any(|target_id| target_id == page_target_id));- let target = closure_plan.top_level_target();- let tab_target_id = target.tab_target_id().to_owned();- let tab_session_ids = target.tab_session_ids();+ let target = closure_plan.tab_target();+ let tab_target_id = target.id().to_owned();+ let tab_session_ids = target.session_ids();self.detach_target_closure_cleanup_event_plan(TargetClosureCleanupPlan::new(tab_target_id, reason, tab_session_ids),None,@@ -3545,12 +3552,10 @@ impl CdpConnection {&mut self,page_target_id: &str,) {- let Some(closure_plan) =- self.remove_top_level_page_target_by_page_target_id(page_target_id)- else {+ let Some(closure_plan) = self.remove_tab_for_page_target(page_target_id) else {return;};- for session_id in closure_plan.top_level_target().tab_session_ids() {+ for session_id in closure_plan.tab_target().session_ids() {self.clear_auto_attach_owner(Some(&session_id));self.rollback_attached_session_without_event(&session_id);}@@ -3564,7 +3569,7 @@ impl CdpConnection {&self,tab_target_id: &str,) -> Option<String> {- let page_target_id = self.page_target_id_for_tab_target_id(tab_target_id)?;+ let page_target_id = self.primary_page_target_id_for_tab_target_id(tab_target_id)?;self.browser_contexts().find(|browser_context| {browser_context@@ -3586,7 +3591,7 @@ impl CdpConnection {}pub(crate) fn tab_target_info(&self, tab_target_id: &str) -> Option<DevToolsTargetInfo> {- let page_target_id = self.page_target_id_for_tab_target_id(tab_target_id)?;+ let page_target_id = self.primary_page_target_id_for_tab_target_id(tab_target_id)?;let page_target_info = self.browser_contexts().find_map(|browser_context| browser_context.devtools_target_info(page_target_id))?;@@ -3692,15 +3697,7 @@ impl CdpConnection {}fn target_created_event_plan_for_target_delta(&mut self, target_id: &str) -> TargetEventPlan {- let deltas = self.target_deltas_for_target_id(target_id, TargetHostDelta::created);- self.target_host_delta_events(deltas)- }-- pub(crate) fn target_info_changed_event_plan_for_target_delta(- &mut self,- target_id: &str,- ) -> TargetEventPlan {- let deltas = self.target_deltas_for_target_id(target_id, TargetHostDelta::info_changed);+ let deltas = self.target_control.target_created_deltas(target_id);self.target_host_delta_events(deltas)}@@ -3715,11 +3712,17 @@ impl CdpConnection {else {return TargetEventPlan::default();};+ let tab_target_info = self.tab_target_info_for_page_target_info(&target_info);self.notify_target_host_lifecycle(CdpTargetHostLifecycleDelta::InfoChanged(target_info));+ if let Some(tab_target_info) = tab_target_info {+ self.notify_target_host_lifecycle(CdpTargetHostLifecycleDelta::InfoChanged(+ tab_target_info,+ ));+ }if !self.has_any_target_info_observer() {return TargetEventPlan::default();}- self.target_info_changed_event_plan_for_target_delta(target_id)+ self.exact_target_info_changed_event_plan_for_target_delta(target_id)}pub(crate) fn target_info_changed_event_plan_for_session_owner(@@ -3741,15 +3744,6 @@ impl CdpConnection {self.target_host_delta_events([TargetHostDelta::info_changed(target_id.to_owned())])}- fn target_deltas_for_target_id(- &self,- target_id: &str,- build_delta: fn(String) -> TargetHostDelta,- ) -> Vec<TargetHostDelta> {- self.target_control- .target_deltas_for_target_id(target_id, build_delta)- }-fn target_host_delta_events(&mut self,deltas: impl IntoIterator<Item = TargetHostDelta>,@@ -3808,7 +3802,7 @@ impl CdpConnection {pub(crate) fn prepare_target_host_closure(&self, target_id: &str) -> PreparedTargetHostClosure {let mut detached_info_deltas = Vec::new();let mut destroyed_deltas = Vec::new();- for delta in self.target_deltas_for_target_id(target_id, TargetHostDelta::destroyed) {+ for delta in self.target_control.target_destroyed_deltas(target_id) {let target_id = delta.target_id().to_owned();let Some(target_info) = self.target_info_for_host_delta(&target_id) else {continue;@@ -3911,19 +3905,21 @@ impl CdpConnection {&self,target_info: DevToolsTargetInfo,) -> Vec<BackgroundProtocolEvent> {- target_destroyed_automation_events(self.project_tab_page_target_infos(target_info))+ target_destroyed_automation_events(+ self.project_page_tab_target_infos_for_destruction(target_info),+ )}- fn project_tab_page_target_infos(+ fn project_page_tab_target_infos_for_destruction(&self,target_info: DevToolsTargetInfo,) -> Vec<DevToolsTargetInfo> {self.target_control- .project_tab_page_target_infos(target_info)+ .project_page_tab_target_infos_for_destruction(target_info)}#[cfg(test)]- pub(crate) fn top_level_target_graph_len(&self) -> usize {+ pub(crate) fn tab_target_count(&self) -> usize {self.target_control.len()}@@ -3992,6 +3988,29 @@ impl CdpConnection {}}+ fn gen_tab_target_id(&mut self) -> String {+ loop {+ let id = if let Some(allocator) = self.shared_tab_target_id_allocator.as_ref() {+ allocator+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {+ current.checked_add(1)+ })+ .expect("shared tab target id space exhausted")+ + 1+ } else {+ self.next_tab_target_id = self+ .next_tab_target_id+ .checked_add(1)+ .expect("tab target id space exhausted");+ u64::from(self.next_tab_target_id)+ };+ let target_id = format!("TAB-{id}");+ if self.target_control.host_kind(&target_id).is_none() {+ return target_id;+ }+ }+ }+pub fn gen_session_id(&mut self) -> String {loop {self.next_session_id = self@@ -4034,6 +4053,11 @@ impl CdpConnection {self.notify_target_host_lifecycle(CdpTargetHostLifecycleDelta::Activated {target_id: target_id.to_owned(),});+ if let Some(tab_target_id) = self.tab_target_id_for_page_target_id(target_id) {+ self.notify_target_host_lifecycle(CdpTargetHostLifecycleDelta::Activated {+ target_id: tab_target_id.to_owned(),+ });+ }}}diff --git a/moli-protocol/src/conn/browser_context/session_owner.rs b/moli-protocol/src/conn/browser_context/session_owner.rsindex 17bbc5bb7..a88f19208 100644--- a/moli-protocol/src/conn/browser_context/session_owner.rs+++ b/moli-protocol/src/conn/browser_context/session_owner.rs@@ -62,6 +62,35 @@ impl CdpSessionRoute {} => Some(browser_context_id),}}++ /// Whether Chromium installs a handler for this CDP domain on the routed+ /// DevToolsAgentHost.+ ///+ /// Page and worker capability checks remain in their domain handlers for+ /// now. Browser and Tab hosts are browser-only sessions in Chromium; they+ /// must not fall through to whichever Page happens to be active.+ pub(crate) fn supports_cdp_domain(&self, domain: &str) -> bool {+ match self {+ Self::Browser => matches!(+ domain,+ "Browser"+ | "Fetch"+ | "IO"+ | "Security"+ | "Storage"+ | "SystemInfo"+ | "Target"+ | "Tracing"+ ),+ Self::TabTarget { .. } => matches!(domain, "IO" | "Target" | "Tracing"),+ Self::ActiveTarget { .. }+ | Self::AuxiliaryTarget { .. }+ | Self::BackgroundTarget { .. }+ | Self::SharedWorkerTarget { .. }+ | Self::DedicatedWorkerTarget { .. }+ | Self::ServiceWorkerTarget { .. } => true,+ }+ }}pub(super) enum TargetSessionOwner {@@ -100,7 +129,9 @@ impl CdpConnection {&self,target_id: &str,) -> Option<CdpSessionRoute> {- if self.page_target_id_for_tab_target_id(target_id).is_some()+ if self+ .primary_page_target_id_for_tab_target_id(target_id)+ .is_some()&& let Some(browser_context_id) = self.browser_context_id_for_tab_target_id(target_id){return Some(CdpSessionRoute::TabTarget {@@ -142,6 +173,41 @@ impl CdpConnection {})}+ /// Returns the DevToolsAgentHost owned by a non-browser session.+ ///+ /// Chromium's Target domain uses its handler's `owner_target_id` when+ /// `Target.getTargetInfo` omits `targetId`. A tab session therefore owns+ /// the stable Tab target, while a page or worker session owns its exact+ /// execution target.+ pub(crate) fn non_browser_target_id_for_session(+ &self,+ session_id: Option<&str>,+ ) -> Option<String> {+ match self.session_route(session_id)? {+ CdpSessionRoute::TabTarget {+ tab_target_id: target_id,+ ..+ }+ | CdpSessionRoute::AuxiliaryTarget { target_id, .. }+ | CdpSessionRoute::BackgroundTarget { target_id, .. }+ | CdpSessionRoute::SharedWorkerTarget { target_id, .. }+ | CdpSessionRoute::DedicatedWorkerTarget { target_id, .. }+ | CdpSessionRoute::ServiceWorkerTarget { target_id, .. }+ | CdpSessionRoute::ActiveTarget {+ target_id: Some(target_id),+ ..+ } => Some(target_id),+ CdpSessionRoute::ActiveTarget {+ browser_context_id,+ target_id: None,+ } => self+ .browser_context_by_id(&browser_context_id)+ .and_then(|browser_context| browser_context.active_target_id())+ .map(str::to_owned),+ CdpSessionRoute::Browser => None,+ }+ }+pub fn worker_target_id_for_session(&self, session_id: Option<&str>) -> Option<String> {match self.session_route(session_id)? {CdpSessionRoute::SharedWorkerTarget { target_id, .. }@@ -409,7 +475,7 @@ impl CdpConnection {session_id: String,owner_session_id: Option<&str>,) {- let target_id = self.target_id_for_auto_attached_session(&session_id);+ let target_id = self.non_browser_target_id_for_session(Some(&session_id));self.register_auto_attached_session_for_target(session_id,owner_session_id,@@ -1386,31 +1452,6 @@ impl CdpConnection {.auto_attached_session_cascade_for_owner(owner_session_id)}- #[cfg(test)]- fn target_id_for_auto_attached_session(&self, session_id: &str) -> Option<String> {- match self.session_route(Some(session_id))? {- CdpSessionRoute::TabTarget {- tab_target_id: target_id,- ..- }- | CdpSessionRoute::BackgroundTarget { target_id, .. }- | CdpSessionRoute::AuxiliaryTarget { target_id, .. }- | CdpSessionRoute::SharedWorkerTarget { target_id, .. }- | CdpSessionRoute::DedicatedWorkerTarget { target_id, .. }- | CdpSessionRoute::ServiceWorkerTarget { target_id, .. } => Some(target_id),- CdpSessionRoute::ActiveTarget {- target_id: Some(target_id),- ..- } => Some(target_id),- CdpSessionRoute::ActiveTarget {- target_id: None, ..- } => self- .target_owner_identity_for_session(Some(session_id))- .and_then(|(_, target_id)| target_id),- CdpSessionRoute::Browser => None,- }- }-pub(crate) fn set_service_worker_auto_attach_related_owner(&mut self,owner_session_id: Option<&str>,diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rsindex cc4435e98..76cb20e9b 100644--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs@@ -2723,6 +2723,7 @@ impl CdpConnection {pub(crate) async fn close_active_page_target_for_target_close_async(&mut self,+ out: &mut Vec<BackgroundProtocolEvent>,) -> Option<ClosedPageTarget> {let (target_id,@@ -2768,6 +2769,16 @@ impl CdpConnection {self.refresh_active_browser_context_loader_async().await;if let Some(promoted_target_id) = promoted_target_id {self.notify_target_host_activated(&promoted_target_id);+ out.extend(+ self.page_screencast_session_ids_for_target(&promoted_target_id)+ .into_iter()+ .map(|session_id| {+ BackgroundProtocolEvent::page_screencast_visibility_changed(+ session_id.as_deref(),+ true,+ )+ }),+ );}Some(ClosedPageTarget {diff --git a/moli-protocol/src/conn/dispatch.rs b/moli-protocol/src/conn/dispatch.rsindex fdb097aea..9fb85296f 100644--- a/moli-protocol/src/conn/dispatch.rs+++ b/moli-protocol/src/conn/dispatch.rs@@ -547,15 +547,26 @@ impl CdpConnection {req.session_id(),);}- if let Some(session_id) = req.session_id()- && self.session_route(Some(session_id)).is_none()- {- return self.complete_with_output_plan(- command_context,- CommandOutputPlan::error(-32001, "Unknown sessionId"),- Some(req.id()),- Some(session_id),- );+ let session_route = req+ .session_id()+ .and_then(|session_id| self.session_route(Some(session_id)));+ if let Some(session_id) = req.session_id() {+ let Some(session_route) = session_route.as_ref() else {+ return self.complete_with_output_plan(+ command_context,+ CommandOutputPlan::error(-32001, "Unknown sessionId"),+ Some(req.id()),+ Some(session_id),+ );+ };+ if !session_route.supports_cdp_domain(domain) {+ return self.complete_with_output_plan(+ command_context,+ CommandOutputPlan::error(-32601, format!("'{}' wasn't found", req.method())),+ Some(req.id()),+ Some(session_id),+ );+ }}let cmd = Cmd::from_parsed(command).expect("validated domain-qualified command must produce a command view")diff --git a/moli-protocol/src/conn/target/control.rs b/moli-protocol/src/conn/target/control.rsindex 5671bd8af..4ace53b1b 100644--- a/moli-protocol/src/conn/target/control.rs+++ b/moli-protocol/src/conn/target/control.rs@@ -1,5 +1,6 @@use std::collections::HashSet;+use super::graph::TabTarget;use crate::devtools_runtime::{DevToolsSessionId, DevToolsTargetFilterEntry, DevToolsTargetId, DevToolsTargetInfo,DevToolsTargetKind, TargetAttachmentEvent, TargetDetachmentEvent,@@ -20,13 +21,9 @@ pub(crate) struct TargetControlPlane {}impl TargetControlPlane {- pub(crate) fn register_top_level_page(- &mut self,- page_target_id: String,- tab_target_id: String,- ) {+ pub(crate) fn register_tab(&mut self, tab_target_id: String, primary_page_target_id: String) {self.registry- .register_top_level_page(page_target_id, tab_target_id);+ .register_tab(tab_target_id, primary_page_target_id);}pub(crate) fn register_worker(&mut self, target_id: String, kind: DevToolsTargetKind) {@@ -42,9 +39,12 @@ impl TargetControlPlane {.tab_target_id_for_page_target_id(page_target_id)}- pub(crate) fn page_target_id_for_tab_target_id(&self, tab_target_id: &str) -> Option<&str> {+ pub(crate) fn primary_page_target_id_for_tab_target_id(+ &self,+ tab_target_id: &str,+ ) -> Option<&str> {self.registry- .page_target_id_for_tab_target_id(tab_target_id)+ .primary_page_target_id_for_tab_target_id(tab_target_id)}pub(crate) fn primary_session_id_for_tab_target_id(&self, tab_target_id: &str) -> Option<&str> {@@ -66,12 +66,11 @@ impl TargetControlPlane {self.registry.remove_tab_session(session_id)}- pub(crate) fn remove_top_level_page_by_page_target_id(+ pub(crate) fn remove_tab_by_page_target_id(&mut self,page_target_id: &str,) -> Option<TargetClosurePlan> {- self.registry- .remove_top_level_page_by_page_target_id(page_target_id)+ self.registry.remove_tab_by_page_target_id(page_target_id)}pub(crate) fn tab_target_id_for_session_id(&self, session_id: &str) -> Option<&str> {@@ -86,42 +85,50 @@ impl TargetControlPlane {return None;}let page_target_id = page_target_info.target_id.as_ref()?.as_str();- let target = self- .registry- .top_level_target_for_page_target_id(page_target_id)?;+ let target = self.registry.tab_for_page_target_id(page_target_id)?;Some(super::projection::tab_target_info_from_page_target_info(target,page_target_info,))}- pub(crate) fn project_tab_page_target_infos(+ pub(crate) fn project_page_tab_target_infos_for_destruction(&self,target_info: DevToolsTargetInfo,) -> Vec<DevToolsTargetInfo> {- let target = target_info.target_id.as_ref().and_then(|target_id| {- self.registry- .top_level_target_for_page_target_id(target_id.as_str())- });- super::projection::project_tab_page_target_infos(target, target_info)+ let target = target_info+ .target_id+ .as_ref()+ .and_then(|target_id| self.registry.tab_for_page_target_id(target_id.as_str()));+ super::projection::project_page_tab_target_infos_for_destruction(target, target_info)}- pub(crate) fn target_deltas_for_target_id(- &self,- target_id: &str,- build_delta: fn(String) -> TargetHostDelta,- ) -> Vec<TargetHostDelta> {- if let Some(target) = self- .registry- .top_level_target_for_page_target_id(target_id)- .or_else(|| self.registry.top_level_target_for_tab_target_id(target_id))- {- return vec![- build_delta(target.tab_target_id().to_owned()),- build_delta(target.page_target_id().to_owned()),- ];+ fn paired_tab_target(&self, target_id: &str) -> Option<&TabTarget> {+ self.registry+ .tab_for_page_target_id(target_id)+ .or_else(|| self.registry.tab(target_id))+ }++ pub(crate) fn target_created_deltas(&self, target_id: &str) -> Vec<TargetHostDelta> {+ let Some(target) = self.paired_tab_target(target_id) else {+ return vec![TargetHostDelta::created(target_id.to_owned())];+ };+ target+ .target_ids_in_creation_order()+ .into_iter()+ .map(TargetHostDelta::created)+ .collect()+ }++ pub(crate) fn target_destroyed_deltas(&self, target_id: &str) -> Vec<TargetHostDelta> {+ if let Some(target) = self.paired_tab_target(target_id) {+ return target+ .target_ids_in_destruction_order()+ .into_iter()+ .map(TargetHostDelta::destroyed)+ .collect();}- vec![build_delta(target_id.to_owned())]+ vec![TargetHostDelta::destroyed(target_id.to_owned())]}pub(crate) fn set_discover_targets(diff --git a/moli-protocol/src/conn/target/graph.rs b/moli-protocol/src/conn/target/graph.rsindex 354c370e7..869de7418 100644--- a/moli-protocol/src/conn/target/graph.rs+++ b/moli-protocol/src/conn/target/graph.rs@@ -40,103 +40,107 @@ impl TargetSessionSet {}}+/// One stable browser tab and its current top-level page target.+///+/// Moli keeps the same page target across ordinary document navigations and+/// does not yet expose prerender page targets, so the supported relationship+/// is intentionally one-to-one. The tab identity is still independent: it is+/// the durable browser surface and owns its own DevTools sessions.#[derive(Clone, Debug, PartialEq, Eq)]-pub(crate) struct TopLevelTarget {- page_target_id: String,+pub(crate) struct TabTarget {tab_target_id: String,- tab_sessions: TargetSessionSet,+ primary_page_target_id: String,+ sessions: TargetSessionSet,}-impl TopLevelTarget {- fn new(page_target_id: String, tab_target_id: String) -> Self {+impl TabTarget {+ fn new(tab_target_id: String, primary_page_target_id: String) -> Self {Self {- page_target_id,tab_target_id,- tab_sessions: TargetSessionSet::default(),+ primary_page_target_id,+ sessions: TargetSessionSet::default(),}}- pub(crate) fn page_target_id(&self) -> &str {- &self.page_target_id+ pub(crate) fn id(&self) -> &str {+ &self.tab_target_id}- pub(crate) fn tab_target_id(&self) -> &str {- &self.tab_target_id+ pub(crate) fn primary_page_target_id(&self) -> &str {+ &self.primary_page_target_id+ }++ pub(crate) fn session_ids(&self) -> Vec<String> {+ self.sessions.session_ids()}- pub(crate) fn tab_session_ids(&self) -> Vec<String> {- self.tab_sessions.session_ids()+ pub(crate) fn has_session(&self) -> bool {+ self.sessions.has_session()+ }++ /// Chromium publishes a WebContents-backed Tab host before its primary+ /// RenderFrame-backed Page host becomes observable.+ pub(crate) fn target_ids_in_creation_order(&self) -> [&str; 2] {+ [self.id(), self.primary_page_target_id()]}- pub(crate) fn tab_has_session(&self) -> bool {- self.tab_sessions.has_session()+ /// The primary Page host goes away before the WebContents-backed Tab host.+ pub(crate) fn target_ids_in_destruction_order(&self) -> [&str; 2] {+ [self.primary_page_target_id(), self.id()]}}#[derive(Clone, Debug, Default, PartialEq, Eq)]pub(crate) struct TargetGraph {- top_level_targets: HashMap<String, TopLevelTarget>,+ tabs: HashMap<String, TabTarget>,page_to_tab: HashMap<String, String>,- tab_to_page: HashMap<String, String>,tab_session_to_tab: HashMap<String, String>,}impl TargetGraph {- pub(crate) fn register_top_level_page(- &mut self,- page_target_id: String,- tab_target_id: String,- ) {- self.remove_top_level_page_by_page_target_id(&page_target_id);- self.remove_top_level_page_by_tab_target_id(&tab_target_id);+ pub(crate) fn register_tab(&mut self, tab_target_id: String, primary_page_target_id: String) {+ self.remove_tab_by_page_target_id(&primary_page_target_id);+ self.remove_tab_by_target_id(&tab_target_id);self.page_to_tab- .insert(page_target_id.clone(), tab_target_id.clone());- self.tab_to_page- .insert(tab_target_id.clone(), page_target_id.clone());- self.top_level_targets.insert(- page_target_id.clone(),- TopLevelTarget::new(page_target_id, tab_target_id),+ .insert(primary_page_target_id.clone(), tab_target_id.clone());+ self.tabs.insert(+ tab_target_id.clone(),+ TabTarget::new(tab_target_id, primary_page_target_id),);}- pub(crate) fn remove_top_level_page_by_page_target_id(+ pub(crate) fn remove_tab_by_page_target_id(&mut self,page_target_id: &str,- ) -> Option<TopLevelTarget> {- let target = self.top_level_targets.remove(page_target_id)?;- if let Some(session_id) = target.tab_sessions.primary_session_id() {- self.tab_session_to_tab.remove(session_id);- }- for session_id in &target.tab_sessions.auxiliary_session_ids {- self.tab_session_to_tab.remove(session_id);- }- self.page_to_tab.remove(target.page_target_id());- self.tab_to_page.remove(target.tab_target_id());- Some(target)+ ) -> Option<TabTarget> {+ let tab_target_id = self.page_to_tab.get(page_target_id)?.clone();+ self.remove_tab_by_target_id(&tab_target_id)}- pub(crate) fn remove_top_level_page_by_tab_target_id(- &mut self,- tab_target_id: &str,- ) -> Option<TopLevelTarget> {- let page_target_id = self.tab_to_page.get(tab_target_id)?.clone();- self.remove_top_level_page_by_page_target_id(&page_target_id)+ pub(crate) fn remove_tab_by_target_id(&mut self, tab_target_id: &str) -> Option<TabTarget> {+ let target = self.tabs.remove(tab_target_id)?;+ for session_id in target.sessions.session_ids() {+ self.tab_session_to_tab.remove(&session_id);+ }+ self.page_to_tab.remove(target.primary_page_target_id());+ Some(target)}pub(crate) fn tab_target_id_for_page_target_id(&self, page_target_id: &str) -> Option<&str> {self.page_to_tab.get(page_target_id).map(String::as_str)}- pub(crate) fn page_target_id_for_tab_target_id(&self, tab_target_id: &str) -> Option<&str> {- self.tab_to_page.get(tab_target_id).map(String::as_str)+ pub(crate) fn primary_page_target_id_for_tab_target_id(+ &self,+ tab_target_id: &str,+ ) -> Option<&str> {+ self.tabs+ .get(tab_target_id)+ .map(TabTarget::primary_page_target_id)}pub(crate) fn primary_session_id_for_tab_target_id(&self, tab_target_id: &str) -> Option<&str> {- let page_target_id = self.tab_to_page.get(tab_target_id)?;- self.top_level_targets- .get(page_target_id)?- .tab_sessions- .primary_session_id()+ self.tabs.get(tab_target_id)?.sessions.primary_session_id()}pub(crate) fn assign_session_to_tab_target(@@ -146,14 +150,11 @@ impl TargetGraph {auxiliary: bool,) -> bool {self.remove_tab_session(&session_id);- let Some(page_target_id) = self.tab_to_page.get(tab_target_id).cloned() else {- return false;- };- let Some(target) = self.top_level_targets.get_mut(&page_target_id) else {+ let Some(target) = self.tabs.get_mut(tab_target_id) else {return false;};target- .tab_sessions+ .sessions.insert_session(session_id.clone(), auxiliary);self.tab_session_to_tab.insert(session_id, tab_target_id.to_owned());@@ -162,9 +163,8 @@ impl TargetGraph {pub(crate) fn remove_tab_session(&mut self, session_id: &str) -> Option<String> {let tab_target_id = self.tab_session_to_tab.remove(session_id)?;- let page_target_id = self.tab_to_page.get(&tab_target_id)?;- let target = self.top_level_targets.get_mut(page_target_id)?;- target.tab_sessions.remove_session(session_id);+ let target = self.tabs.get_mut(&tab_target_id)?;+ target.sessions.remove_session(session_id);Some(tab_target_id)}@@ -172,21 +172,23 @@ impl TargetGraph {self.tab_session_to_tab.get(session_id).map(String::as_str)}- pub(crate) fn top_level_target_for_page_target_id(- &self,- page_target_id: &str,- ) -> Option<&TopLevelTarget> {- self.top_level_targets.get(page_target_id)+ pub(crate) fn tab_for_page_target_id(&self, page_target_id: &str) -> Option<&TabTarget> {+ let tab_target_id = self.page_to_tab.get(page_target_id)?;+ self.tabs.get(tab_target_id)+ }++ pub(crate) fn tab(&self, tab_target_id: &str) -> Option<&TabTarget> {+ self.tabs.get(tab_target_id)}#[cfg(test)]pub(crate) fn len(&self) -> usize {- self.top_level_targets.len()+ self.tabs.len()}#[cfg(test)]pub(crate) fn is_empty(&self) -> bool {- self.top_level_targets.is_empty()+ self.tabs.is_empty()}}@@ -195,45 +197,44 @@ mod tests {use super::TargetGraph;#[test]- fn target_graph_registers_top_level_page_tab_pair() {+ fn target_graph_registers_stable_tab_with_primary_page() {let mut graph = TargetGraph::default();- graph.register_top_level_page("TID-page".to_owned(), "TAB-TID-page".to_owned());+ graph.register_tab("TAB-1".to_owned(), "TID-page".to_owned());assert_eq!(graph.len(), 1);assert_eq!(graph.tab_target_id_for_page_target_id("TID-page"),- Some("TAB-TID-page")+ Some("TAB-1"));assert_eq!(- graph.page_target_id_for_tab_target_id("TAB-TID-page"),+ graph.primary_page_target_id_for_tab_target_id("TAB-1"),Some("TID-page"));- let target = graph- .top_level_target_for_page_target_id("TID-page")- .expect("top level target");- assert_eq!(target.page_target_id(), "TID-page");- assert_eq!(target.tab_target_id(), "TAB-TID-page");- assert!(!target.tab_has_session());+ let tab = graph+ .tab_for_page_target_id("TID-page")+ .expect("tab target");+ assert_eq!(tab.id(), "TAB-1");+ assert_eq!(tab.primary_page_target_id(), "TID-page");+ assert!(!tab.has_session());}#[test]fn target_graph_rekey_removes_stale_reverse_entries() {let mut graph = TargetGraph::default();- graph.register_top_level_page("TID-a".to_owned(), "TAB-a".to_owned());- graph.register_top_level_page("TID-a".to_owned(), "TAB-b".to_owned());+ graph.register_tab("TAB-a".to_owned(), "TID-a".to_owned());+ graph.register_tab("TAB-b".to_owned(), "TID-a".to_owned());assert_eq!(graph.len(), 1);assert_eq!(graph.tab_target_id_for_page_target_id("TID-a"),Some("TAB-b"));- assert_eq!(graph.page_target_id_for_tab_target_id("TAB-a"), None);assert_eq!(- graph.page_target_id_for_tab_target_id("TAB-b"),- Some("TID-a")+ graph.primary_page_target_id_for_tab_target_id("TAB-a"),+ None);- graph.register_top_level_page("TID-b".to_owned(), "TAB-b".to_owned());+ graph.register_tab("TAB-b".to_owned(), "TID-b".to_owned());assert_eq!(graph.len(), 1);assert_eq!(graph.tab_target_id_for_page_target_id("TID-a"), None);assert_eq!(@@ -241,22 +242,36 @@ mod tests {Some("TAB-b"));assert_eq!(- graph.page_target_id_for_tab_target_id("TAB-b"),+ graph.primary_page_target_id_for_tab_target_id("TAB-b"),Some("TID-b"));}#[test]- fn target_graph_removes_pair_from_either_side() {+ fn target_graph_removes_tab_from_either_identity() {let mut graph = TargetGraph::default();- graph.register_top_level_page("TID-page".to_owned(), "TAB-TID-page".to_owned());+ graph.register_tab("TAB-1".to_owned(), "TID-page".to_owned());- let removed = graph- .remove_top_level_page_by_tab_target_id("TAB-TID-page")- .expect("removed target");- assert_eq!(removed.page_target_id(), "TID-page");+ let removed = graph.remove_tab_by_target_id("TAB-1").expect("removed tab");+ assert_eq!(removed.primary_page_target_id(), "TID-page");assert!(graph.is_empty());assert_eq!(graph.tab_target_id_for_page_target_id("TID-page"), None);- assert_eq!(graph.page_target_id_for_tab_target_id("TAB-TID-page"), None);+ assert_eq!(+ graph.primary_page_target_id_for_tab_target_id("TAB-1"),+ None+ );+ }++ #[test]+ fn target_graph_exposes_chromium_host_lifecycle_order() {+ let mut graph = TargetGraph::default();+ graph.register_tab("TAB-1".to_owned(), "TID-page".to_owned());+ let target = graph.tab("TAB-1").expect("tab target");++ assert_eq!(target.target_ids_in_creation_order(), ["TAB-1", "TID-page"]);+ assert_eq!(+ target.target_ids_in_destruction_order(),+ ["TID-page", "TAB-1"]+ );}}diff --git a/moli-protocol/src/conn/target/host.rs b/moli-protocol/src/conn/target/host.rsindex 954460914..86d0d22e1 100644--- a/moli-protocol/src/conn/target/host.rs+++ b/moli-protocol/src/conn/target/host.rs@@ -1,56 +1,19 @@use crate::devtools_runtime::DevToolsTargetKind;-#[derive(Clone, Debug, PartialEq, Eq)]-pub(crate) enum TargetHostParent {- Browser,- Tab { tab_target_id: String },-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(crate) enum TargetHostLifecycle {- Live,-}-+/// Stable protocol identity for one live CDP target.+///+/// Ownership and association belong to `TargetGraph`; keeping them out of the+/// host avoids conflating Moli's internal Tab/Page relationship with CDP's+/// public `parentId` semantics.#[derive(Clone, Debug, PartialEq, Eq)]pub(crate) struct TargetHost {id: String,kind: DevToolsTargetKind,- parent: TargetHostParent,- lifecycle: TargetHostLifecycle,}impl TargetHost {- pub(crate) fn tab(id: String) -> Self {- Self {- id,- kind: DevToolsTargetKind::Tab,- parent: TargetHostParent::Browser,- lifecycle: TargetHostLifecycle::Live,- }- }-- pub(crate) fn page(id: String, tab_target_id: String) -> Self {- Self {- id,- kind: DevToolsTargetKind::Page,- parent: TargetHostParent::Tab { tab_target_id },- lifecycle: TargetHostLifecycle::Live,- }- }-- pub(crate) fn worker(id: String, kind: DevToolsTargetKind) -> Self {- debug_assert!(matches!(- kind,- DevToolsTargetKind::Worker- | DevToolsTargetKind::SharedWorker- | DevToolsTargetKind::ServiceWorker- ));- Self {- id,- kind,- parent: TargetHostParent::Browser,- lifecycle: TargetHostLifecycle::Live,- }+ pub(crate) fn new(id: String, kind: DevToolsTargetKind) -> Self {+ Self { id, kind }}pub(crate) fn id(&self) -> &str {@@ -60,12 +23,4 @@ impl TargetHost {pub(crate) fn kind(&self) -> DevToolsTargetKind {self.kind}-- pub(crate) fn parent(&self) -> &TargetHostParent {- &self.parent- }-- pub(crate) fn is_live(&self) -> bool {- self.lifecycle == TargetHostLifecycle::Live- }}diff --git a/moli-protocol/src/conn/target/projection.rs b/moli-protocol/src/conn/target/projection.rsindex 86d8e9547..ceeea064c 100644--- a/moli-protocol/src/conn/target/projection.rs+++ b/moli-protocol/src/conn/target/projection.rs@@ -1,16 +1,16 @@-use super::graph::TopLevelTarget;+use super::graph::TabTarget;use crate::devtools_runtime::{DevToolsTargetId, DevToolsTargetInfo, DevToolsTargetKind};pub(crate) fn tab_target_info_from_page_target_info(- target: &TopLevelTarget,+ target: &TabTarget,page_target_info: DevToolsTargetInfo,) -> DevToolsTargetInfo {DevToolsTargetInfo {- target_id: Some(DevToolsTargetId::from(target.tab_target_id())),+ target_id: Some(DevToolsTargetId::from(target.id())),kind: DevToolsTargetKind::Tab,title: page_target_info.title,url: page_target_info.url,- attached: target.tab_has_session(),+ attached: target.has_session(),// Chromium's tab DevToolsAgentHost delegates opener identity and// access to its primary frame host. Preserve the same relationship// when projecting our page target into a tab target.@@ -22,20 +22,16 @@ pub(crate) fn tab_target_info_from_page_target_info(}}-pub(crate) fn project_tab_page_target_infos(- target: Option<&TopLevelTarget>,+pub(crate) fn project_page_tab_target_infos_for_destruction(+ target: Option<&TabTarget>,target_info: DevToolsTargetInfo,) -> Vec<DevToolsTargetInfo> {- let mut target_infos = Vec::new();+ let mut target_infos = vec![target_info.clone()];if target_info.kind == DevToolsTargetKind::Page&& let Some(target) = target{- target_infos.push(tab_target_info_from_page_target_info(- target,- target_info.clone(),- ));+ target_infos.push(tab_target_info_from_page_target_info(target, target_info));}- target_infos.push(target_info);target_infos}@@ -52,10 +48,10 @@ mod tests {#[test]fn tab_projection_preserves_noopener_creator_identity_and_access_policy() {let mut graph = TargetGraph::default();- graph.register_top_level_page("TID-page".to_owned(), "TID-tab".to_owned());+ graph.register_tab("TID-tab".to_owned(), "TID-page".to_owned());let target = graph- .top_level_target_for_page_target_id("TID-page")- .expect("registered top-level target");+ .tab_for_page_target_id("TID-page")+ .expect("registered tab target");let tab = tab_target_info_from_page_target_info(target,DevToolsTargetInfo {diff --git a/moli-protocol/src/conn/target/registry.rs b/moli-protocol/src/conn/target/registry.rsindex 39b77bddb..cc0b2ab3d 100644--- a/moli-protocol/src/conn/target/registry.rs+++ b/moli-protocol/src/conn/target/registry.rs@@ -1,7 +1,7 @@use std::collections::HashMap;-use super::graph::{TargetGraph, TopLevelTarget};-use super::host::{TargetHost, TargetHostParent};+use super::graph::{TabTarget, TargetGraph};+use super::host::TargetHost;use crate::devtools_runtime::DevToolsTargetKind;#[derive(Clone, Debug, PartialEq, Eq)]@@ -41,24 +41,25 @@ impl TargetHostDelta {#[derive(Clone, Debug, PartialEq, Eq)]pub(crate) struct TargetClosurePlan {- top_level_target: TopLevelTarget,+ tab_target: TabTarget,deltas: Vec<TargetHostDelta>,}impl TargetClosurePlan {- fn from_top_level_target(target: TopLevelTarget) -> Self {- let deltas = vec![- TargetHostDelta::destroyed(target.tab_target_id()),- TargetHostDelta::destroyed(target.page_target_id()),- ];+ fn from_tab_target(target: TabTarget) -> Self {+ let deltas = target+ .target_ids_in_destruction_order()+ .into_iter()+ .map(TargetHostDelta::destroyed)+ .collect();Self {- top_level_target: target,+ tab_target: target,deltas,}}- pub(crate) fn top_level_target(&self) -> &TopLevelTarget {- &self.top_level_target+ pub(crate) fn tab_target(&self) -> &TabTarget {+ &self.tab_target}pub(crate) fn destroyed_target_ids(&self) -> impl Iterator<Item = &str> {@@ -72,27 +73,23 @@ impl TargetClosurePlan {#[derive(Clone, Debug, Default, PartialEq, Eq)]pub(crate) struct TargetRegistry {hosts: HashMap<String, TargetHost>,- top_level: TargetGraph,+ graph: TargetGraph,}impl TargetRegistry {- pub(crate) fn register_top_level_page(- &mut self,- page_target_id: String,- tab_target_id: String,- ) {- self.remove_top_level_page_by_page_target_id(&page_target_id);- self.remove_top_level_page_by_tab_target_id(&tab_target_id);+ pub(crate) fn register_tab(&mut self, tab_target_id: String, primary_page_target_id: String) {+ self.remove_tab_by_page_target_id(&primary_page_target_id);+ self.remove_tab_by_target_id(&tab_target_id);self.hosts.insert(tab_target_id.clone(),- TargetHost::tab(tab_target_id.clone()),+ TargetHost::new(tab_target_id.clone(), DevToolsTargetKind::Tab),);self.hosts.insert(- page_target_id.clone(),- TargetHost::page(page_target_id.clone(), tab_target_id.clone()),+ primary_page_target_id.clone(),+ TargetHost::new(primary_page_target_id.clone(), DevToolsTargetKind::Page),);- self.top_level- .register_top_level_page(page_target_id, tab_target_id);+ self.graph+ .register_tab(tab_target_id, primary_page_target_id);}pub(crate) fn register_worker(&mut self, target_id: String, kind: DevToolsTargetKind) {@@ -103,7 +100,7 @@ impl TargetRegistry {| DevToolsTargetKind::ServiceWorker));self.hosts- .insert(target_id.clone(), TargetHost::worker(target_id, kind));+ .insert(target_id.clone(), TargetHost::new(target_id, kind));}pub(crate) fn remove_worker(&mut self, target_id: &str) -> Option<TargetHost> {@@ -119,54 +116,53 @@ impl TargetRegistry {self.hosts.remove(target_id)}- pub(crate) fn remove_top_level_page_by_page_target_id(+ pub(crate) fn remove_tab_by_page_target_id(&mut self,page_target_id: &str,) -> Option<TargetClosurePlan> {- let target = self- .top_level- .remove_top_level_page_by_page_target_id(page_target_id)?;- self.hosts.remove(target.page_target_id());- self.hosts.remove(target.tab_target_id());- Some(TargetClosurePlan::from_top_level_target(target))+ let target = self.graph.remove_tab_by_page_target_id(page_target_id)?;+ self.remove_tab_hosts(&target);+ Some(TargetClosurePlan::from_tab_target(target))}- pub(crate) fn remove_top_level_page_by_tab_target_id(+ pub(crate) fn remove_tab_by_target_id(&mut self,tab_target_id: &str,) -> Option<TargetClosurePlan> {- let page_target_id = self- .top_level- .page_target_id_for_tab_target_id(tab_target_id)?- .to_owned();- self.remove_top_level_page_by_page_target_id(&page_target_id)+ let target = self.graph.remove_tab_by_target_id(tab_target_id)?;+ self.remove_tab_hosts(&target);+ Some(TargetClosurePlan::from_tab_target(target))+ }++ fn remove_tab_hosts(&mut self, target: &TabTarget) {+ self.hosts.remove(target.id());+ self.hosts.remove(target.primary_page_target_id());}pub(crate) fn tab_target_id_for_page_target_id(&self, page_target_id: &str) -> Option<&str> {let host = self.hosts.get(page_target_id)?;debug_assert_eq!(host.id(), page_target_id);- if host.kind() != crate::devtools_runtime::DevToolsTargetKind::Page || !host.is_live() {+ if host.kind() != DevToolsTargetKind::Page {return None;}- if !matches!(host.parent(), TargetHostParent::Tab { .. }) {- return None;- }- self.top_level- .tab_target_id_for_page_target_id(page_target_id)+ self.graph.tab_target_id_for_page_target_id(page_target_id)}- pub(crate) fn page_target_id_for_tab_target_id(&self, tab_target_id: &str) -> Option<&str> {+ pub(crate) fn primary_page_target_id_for_tab_target_id(+ &self,+ tab_target_id: &str,+ ) -> Option<&str> {let host = self.hosts.get(tab_target_id)?;debug_assert_eq!(host.id(), tab_target_id);- if host.kind() != crate::devtools_runtime::DevToolsTargetKind::Tab || !host.is_live() {+ if host.kind() != DevToolsTargetKind::Tab {return None;}- self.top_level- .page_target_id_for_tab_target_id(tab_target_id)+ self.graph+ .primary_page_target_id_for_tab_target_id(tab_target_id)}pub(crate) fn primary_session_id_for_tab_target_id(&self, tab_target_id: &str) -> Option<&str> {- self.top_level+ self.graph.primary_session_id_for_tab_target_id(tab_target_id)}@@ -177,42 +173,34 @@ impl TargetRegistry {auxiliary: bool,) -> bool {if self- .page_target_id_for_tab_target_id(tab_target_id)+ .primary_page_target_id_for_tab_target_id(tab_target_id).is_none(){return false;}- self.top_level+ self.graph.assign_session_to_tab_target(tab_target_id, session_id, auxiliary)}pub(crate) fn remove_tab_session(&mut self, session_id: &str) -> Option<String> {- self.top_level.remove_tab_session(session_id)+ self.graph.remove_tab_session(session_id)}pub(crate) fn tab_target_id_for_session_id(&self, session_id: &str) -> Option<&str> {- self.top_level.tab_target_id_for_session_id(session_id)+ self.graph.tab_target_id_for_session_id(session_id)}- pub(crate) fn top_level_target_for_page_target_id(- &self,- page_target_id: &str,- ) -> Option<&TopLevelTarget> {- self.top_level- .top_level_target_for_page_target_id(page_target_id)+ pub(crate) fn tab_for_page_target_id(&self, page_target_id: &str) -> Option<&TabTarget> {+ self.graph.tab_for_page_target_id(page_target_id)}- pub(crate) fn top_level_target_for_tab_target_id(- &self,- tab_target_id: &str,- ) -> Option<&TopLevelTarget> {- let page_target_id = self.page_target_id_for_tab_target_id(tab_target_id)?;- self.top_level_target_for_page_target_id(page_target_id)+ pub(crate) fn tab(&self, tab_target_id: &str) -> Option<&TabTarget> {+ self.graph.tab(tab_target_id)}#[cfg(test)]pub(crate) fn len(&self) -> usize {- self.top_level.len()+ self.graph.len()}#[cfg(test)]@@ -227,67 +215,59 @@ impl TargetRegistry {#[cfg(test)]mod tests {- use super::TargetHostParent;use crate::devtools_runtime::DevToolsTargetKind;use super::TargetRegistry;#[test]- fn target_registry_registers_page_tab_hosts() {+ fn target_registry_registers_distinct_page_and_tab_hosts() {let mut registry = TargetRegistry::default();- registry.register_top_level_page("TID-page".to_owned(), "TAB-TID-page".to_owned());+ registry.register_tab("TAB-1".to_owned(), "TID-page".to_owned());assert_eq!(registry.len(), 1);assert_eq!(registry.tab_target_id_for_page_target_id("TID-page"),- Some("TAB-TID-page")+ Some("TAB-1"));assert_eq!(- registry.page_target_id_for_tab_target_id("TAB-TID-page"),+ registry.primary_page_target_id_for_tab_target_id("TAB-1"),Some("TID-page"));let page = registry.host("TID-page").expect("page host");assert_eq!(page.id(), "TID-page");assert_eq!(page.kind(), DevToolsTargetKind::Page);- assert_eq!(- page.parent(),- &TargetHostParent::Tab {- tab_target_id: "TAB-TID-page".to_owned()- }- );- let tab = registry.host("TAB-TID-page").expect("tab host");- assert_eq!(tab.id(), "TAB-TID-page");+ let tab = registry.host("TAB-1").expect("tab host");+ assert_eq!(tab.id(), "TAB-1");assert_eq!(tab.kind(), DevToolsTargetKind::Tab);- assert_eq!(tab.parent(), &TargetHostParent::Browser);}#[test]fn target_registry_removes_page_and_tab_hosts_together() {let mut registry = TargetRegistry::default();- registry.register_top_level_page("TID-page".to_owned(), "TAB-TID-page".to_owned());+ registry.register_tab("TAB-1".to_owned(), "TID-page".to_owned());let removed = registry- .remove_top_level_page_by_tab_target_id("TAB-TID-page")- .expect("removed top-level target");- assert_eq!(removed.top_level_target().page_target_id(), "TID-page");- assert_eq!(removed.top_level_target().tab_target_id(), "TAB-TID-page");+ .remove_tab_by_target_id("TAB-1")+ .expect("removed tab target");+ assert_eq!(removed.tab_target().primary_page_target_id(), "TID-page");+ assert_eq!(removed.tab_target().id(), "TAB-1");assert_eq!(removed.destroyed_target_ids().collect::<Vec<_>>(),- vec!["TAB-TID-page", "TID-page"]+ vec!["TID-page", "TAB-1"]);assert_eq!(registry.host("TID-page"), None);- assert_eq!(registry.host("TAB-TID-page"), None);+ assert_eq!(registry.host("TAB-1"), None);assert_eq!(registry.tab_target_id_for_page_target_id("TID-page"), None);assert_eq!(- registry.page_target_id_for_tab_target_id("TAB-TID-page"),+ registry.primary_page_target_id_for_tab_target_id("TAB-1"),None);}#[test]- fn target_registry_registers_and_removes_worker_host_without_top_level_graph() {+ fn target_registry_registers_and_removes_worker_host_without_tab_graph() {let mut registry = TargetRegistry::default();registry.register_worker("TID-shared-worker".to_owned(),@@ -299,7 +279,6 @@ mod tests {let host = registry.host("TID-shared-worker").expect("worker host");assert_eq!(host.id(), "TID-shared-worker");assert_eq!(host.kind(), DevToolsTargetKind::SharedWorker);- assert_eq!(host.parent(), &TargetHostParent::Browser);let removed = registry.remove_worker("TID-shared-worker")diff --git a/moli-protocol/src/conn/tests/message.rs b/moli-protocol/src/conn/tests/message.rsindex 9e6b1dd5e..c2a44b068 100644--- a/moli-protocol/src/conn/tests/message.rs+++ b/moli-protocol/src/conn/tests/message.rs@@ -95,6 +95,36 @@ async fn session_scoped_unknown_method_error_keeps_session_id() {);}+#[tokio::test]+async fn browser_and_tab_sessions_do_not_fall_through_to_the_active_page() {+ let mut conn = CdpConnection::new();+ conn.install_default_browser_target();+ conn.register_browser_session("SID-browser".to_owned());+ let default_tab_target_id = conn.default_tab_target_id().to_owned();+ assert!(+ conn.assign_session_to_tab_target(&default_tab_target_id, "SID-tab".to_owned(), false,)+ );++ for session_id in ["SID-browser", "SID-tab"] {+ let response = conn+ .process_message_messages_only_for_test(&format!(+ r#"{{"id":19,"method":"Page.getFrameTree","sessionId":"{session_id}"}}"#+ ))+ .await;+ assert_eq!(+ response,+ vec![json!({+ "id": 19,+ "error": {+ "code": -32601,+ "message": "'Page.getFrameTree' wasn't found"+ },+ "sessionId": session_id+ })]+ );+ }+}+#[tokio::test]async fn session_scoped_handler_error_keeps_session_id_even_when_domain_uses_plain_error_helper() {let mut conn = CdpConnection::new();diff --git a/moli-protocol/src/domains/page/termination.rs b/moli-protocol/src/domains/page/termination.rsindex 6f15648bc..f582c9ca1 100644--- a/moli-protocol/src/domains/page/termination.rs+++ b/moli-protocol/src/domains/page/termination.rs@@ -673,7 +673,8 @@ pub(crate) async fn complete_page_target_termination_owner_action_async(browser_context.is_active_target(&expected_target_id)});if is_active_target {- conn.close_active_page_target_for_target_close_async().await+ conn.close_active_page_target_for_target_close_async(&mut out)+ .await} else {conn.close_background_page_target_for_target_close_async(&expected_target_id,diff --git a/moli-protocol/src/domains/target.rs b/moli-protocol/src/domains/target.rsindex 9b17f263c..af52a2332 100644--- a/moli-protocol/src/domains/target.rs+++ b/moli-protocol/src/domains/target.rs@@ -689,7 +689,7 @@ async fn created_target_response_plan_after_initial_document(response_plan: CommandOutputPlan,protocol_events: lifecycle::CreatedTargetProtocolEvents,) -> CommandOutputPlan {- let target_id = protocol_events.target_id().to_owned();+ let target_id = protocol_events.page_target_id().to_owned();let mut plan = CommandOutputPlan::default();let mut events = Vec::new();if let Err(error) =diff --git a/moli-protocol/src/domains/target/attachment.rs b/moli-protocol/src/domains/target/attachment.rsindex 5df0944a1..d9fca9988 100644--- a/moli-protocol/src/domains/target/attachment.rs+++ b/moli-protocol/src/domains/target/attachment.rs@@ -136,7 +136,10 @@ fn do_attach(conn: &mut CdpConnection, cmd: &Cmd<'_>, target_id: &str) -> Targetreturn TargetCommandTaskStep::Complete(attach_browser_target(conn, cmd.session_id));}let attach_from_browser_session = conn.is_browser_session_id(cmd.session_id);- if conn.page_target_id_for_tab_target_id(target_id).is_some() {+ if conn+ .primary_page_target_id_for_tab_target_id(target_id)+ .is_some()+ {return do_attach_tab_target(conn, cmd.session_id, target_id, attach_from_browser_session);}let restore_browser_context_id =diff --git a/moli-protocol/src/domains/target/browser_context_disposal.rs b/moli-protocol/src/domains/target/browser_context_disposal.rsindex 0dd224f2e..c4267b33c 100644--- a/moli-protocol/src/domains/target/browser_context_disposal.rs+++ b/moli-protocol/src/domains/target/browser_context_disposal.rs@@ -255,7 +255,8 @@ async fn close_page_target(.as_ref().is_some_and(|browser_context| browser_context.is_active_target(&target_id));let closed = if is_active_target {- conn.close_active_page_target_for_target_close_async().await+ conn.close_active_page_target_for_target_close_async(out.background_events_mut())+ .await} else {conn.close_background_page_target_for_target_close_async(&target_id,diff --git a/moli-protocol/src/domains/target/lifecycle.rs b/moli-protocol/src/domains/target/lifecycle.rsindex a380d4ea6..14d1e3f34 100644--- a/moli-protocol/src/domains/target/lifecycle.rs+++ b/moli-protocol/src/domains/target/lifecycle.rs@@ -22,17 +22,24 @@ pub(super) struct DevToolsCreateTargetExecution {}pub(super) struct CreatedTargetProtocolEvents {- target_id: String,+ page_target_id: String,+ tab_target_id: String,attached_tab_sessions: Vec<TargetAttachSessionCommit>,attached_sessions: Vec<TargetAttachSessionCommit>,}impl CreatedTargetProtocolEvents {- pub(super) fn target_id(&self) -> &str {- &self.target_id+ pub(super) fn page_target_id(&self) -> &str {+ &self.page_target_id}}+#[derive(Clone, Copy)]+enum CreateTargetResultHost {+ Page,+ Tab,+}+pub(super) fn emit_created_target_protocol_events(conn: &mut CdpConnection,events: CreatedTargetProtocolEvents,@@ -49,18 +56,18 @@ pub(super) fn emit_created_target_protocol_events(.browser_contexts().find(|browser_context| {browser_context- .devtools_target_info(&events.target_id)+ .devtools_target_info(&events.page_target_id).is_some()}).ok_or_else(|| DevToolsError::new(DevToolsErrorKind::NoSuchTarget, "UnknownTargetId"))?;let target_info = bc- .devtools_target_info(&events.target_id)+ .devtools_target_info(&events.page_target_id).ok_or_else(|| DevToolsError::new(DevToolsErrorKind::NoSuchTarget, "UnknownTargetId"))?;if let Some(message) = super::transient_no_page_devtools_target_info_error(conn, &target_info) {return Err(DevToolsError::new(DevToolsErrorKind::Internal, message));}if has_discovery {- for event in conn.target_created_event_plan(&events.target_id) {+ for event in conn.target_created_event_plan(&events.page_target_id) {out.push_target_background_event(event);}}@@ -80,7 +87,7 @@ pub(super) fn emit_created_target_protocol_events(}}let event_plan = conn.commit_prepared_attach_event_plan(PreparedTargetAttach::new(- events.target_id,+ events.page_target_id,target_info,events.attached_sessions,));@@ -106,6 +113,7 @@ struct CreateTargetParams {#[serde(default = "default_blank")]url: String,browser_context_id: Option<String>,+ for_tab: Option<bool>,}fn default_blank() -> String {@@ -133,17 +141,24 @@ pub(super) fn start_create_target_command(Ok(None) => CreateTargetParams {url: "about:blank".into(),browser_context_id: None,+ for_tab: None,},Err(e) => {return super::target_command_error(-32602, e);}};+ let result_host = if params.for_tab.unwrap_or(false) {+ CreateTargetResultHost::Tab+ } else {+ CreateTargetResultHost::Page+ };let command = build_cdp_create_target_command(cmd, params);- super::start_devtools_target_command(+ start_devtools_create_target_command_with_result_host(conn,cmd.id,cmd.session_id,- DevToolsCommand::CreateTarget(command),+ command,+ result_host,)}@@ -166,14 +181,38 @@ pub(super) fn start_devtools_create_target_command(command_id: Option<u64>,command_session_id: Option<&str>,command: DevToolsCreateTargetCommand,+) -> TargetCommandTaskStep {+ start_devtools_create_target_command_with_result_host(+ conn,+ command_id,+ command_session_id,+ command,+ CreateTargetResultHost::Page,+ )+}++fn start_devtools_create_target_command_with_result_host(+ conn: &mut CdpConnection,+ command_id: Option<u64>,+ command_session_id: Option<&str>,+ command: DevToolsCreateTargetCommand,+ result_host: CreateTargetResultHost,) -> TargetCommandTaskStep {let mut plan = CommandOutputPlan::default();let execution = execute_devtools_create_target_command(conn, command);let (created_target_id, created_target_protocol_events) = match execution {Ok(execution) => {let target_id = execution.result.target_id.clone();+ let response_target_id = match result_host {+ CreateTargetResultHost::Page => execution.result.target_id,+ CreateTargetResultHost::Tab => {+ DevToolsTargetId::from(execution.protocol_events.tab_target_id.as_str())+ }+ };plan.extend(CommandOutputPlan::from_devtools_result(- DevToolsCommandResult::CreateTarget(execution.result),+ DevToolsCommandResult::CreateTarget(DevToolsCreateTargetResult {+ target_id: response_target_id,+ }),));(target_id, execution.protocol_events)}@@ -367,7 +406,8 @@ pub(super) fn execute_devtools_create_target_command(target_id: DevToolsTargetId::from(created_target_id),},protocol_events: CreatedTargetProtocolEvents {- target_id,+ page_target_id: target_id,+ tab_target_id,attached_tab_sessions,attached_sessions,},@@ -1167,7 +1207,7 @@ async fn close_target_inner_async(target_id: String,) -> Result<DevToolsCloseTargetResult, DevToolsError> {let target_id = conn- .page_target_id_for_tab_target_id(&target_id)+ .primary_page_target_id_for_tab_target_id(&target_id).map(str::to_owned).unwrap_or(target_id);if let Err(message) = select_browser_context_for_target(conn, &target_id) {@@ -1401,12 +1441,30 @@ pub(super) fn execute_devtools_get_target_info_command(conn: &CdpConnection,command: DevToolsGetTargetInfoCommand,) -> Result<DevToolsGetTargetInfoResult, DevToolsError> {- let Some(target_id) = command.target_id.as_ref() else {+ let owner_target_id = command+ .context+ .target_id+ .as_ref()+ .map(|target_id| target_id.as_str().to_owned())+ .or_else(|| {+ conn.non_browser_target_id_for_session(+ command+ .context+ .session_id+ .as_ref()+ .map(|session_id| session_id.as_str()),+ )+ });+ let wanted = command+ .target_id+ .as_ref()+ .map(|target_id| target_id.as_str())+ .or(owner_target_id.as_deref());+ let Some(wanted) = wanted else {return Ok(DevToolsGetTargetInfoResult {target_info: super::browser_context::devtools_browser_target_info(),});};- let wanted = target_id.as_str();if wanted == super::browser_context::DEVTOOLS_BROWSER_TARGET_ID {return Ok(DevToolsGetTargetInfoResult {target_info: super::browser_context::devtools_browser_target_info(),@@ -2347,7 +2405,7 @@ async fn auto_attach_child_page_for_tab_session_async(return;}let Some(page_target_id) = conn- .page_target_id_for_tab_target_id(tab_target_id)+ .primary_page_target_id_for_tab_target_id(tab_target_id).map(str::to_owned)else {return;@@ -2876,7 +2934,10 @@ pub(super) async fn execute_devtools_activate_target_command_async(conn: &mut CdpConnection,command: DevToolsActivateTargetCommand,) -> Result<Vec<BackgroundProtocolEvent>, DevToolsError> {- let target_id = command.target_id.as_str().to_owned();+ let target_id = conn+ .primary_page_target_id_for_tab_target_id(command.target_id.as_str())+ .map(str::to_owned)+ .unwrap_or_else(|| 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) {restore_previously_active_browser_context(@@ -3009,6 +3070,7 @@ mod protocol_neutral_tests {CreateTargetParams {url: "https://example.com/new".to_owned(),browser_context_id: Some("BID-create".to_owned()),+ for_tab: None,},);diff --git a/moli-protocol/src/domains/target/tests/test_support.rs b/moli-protocol/src/domains/target/tests/test_support.rsindex bf2638027..31f867763 100644--- a/moli-protocol/src/domains/target/tests/test_support.rs+++ b/moli-protocol/src/domains/target/tests/test_support.rs@@ -14,6 +14,13 @@ pub(super) fn load_bc_with_target(ctx: &mut TestContext, bc_id: &str, target_id:ctx.conn.browser_context = Some(bc);}+pub(super) fn tab_id_for_page(ctx: &TestContext, page_target_id: &str) -> String {+ ctx.conn+ .tab_target_id_for_page_target_id(page_target_id)+ .unwrap_or_else(|| panic!("page target {page_target_id} has no tab target"))+ .to_owned()+}+pub(super) fn push_background_target(ctx: &mut TestContext,target_id: &str,diff --git a/moli-protocol/src/domains/target/tests/tests_browser_context.rs b/moli-protocol/src/domains/target/tests/tests_browser_context.rsindex dd1004318..a13e4c745 100644--- a/moli-protocol/src/domains/target/tests/tests_browser_context.rs+++ b/moli-protocol/src/domains/target/tests/tests_browser_context.rs@@ -161,8 +161,8 @@ async fn dispose_browser_context_detaches_tab_session_and_clears_target_graph().as_str().expect("page target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);- assert_eq!(ctx.conn.top_level_target_graph_len(), 1);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);+ assert_eq!(ctx.conn.tab_target_count(), 1);ctx.sent.clear();ctx.process_async(json!({@@ -195,10 +195,10 @@ async fn dispose_browser_context_detaches_tab_session_and_clears_target_graph()"sessionId": tab_session_id})),);- assert_eq!(ctx.conn.top_level_target_graph_len(), 0);+ assert_eq!(ctx.conn.tab_target_count(), 0);assert!(ctx.conn- .page_target_id_for_tab_target_id(&tab_target_id)+ .primary_page_target_id_for_tab_target_id(&tab_target_id).is_none());assert!(ctx.conn.session_route(Some(&tab_session_id)).is_none());diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_page.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_page.rsindex 2ef212a5a..b8e4b03ae 100644--- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_page.rs+++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_page.rs@@ -93,7 +93,7 @@ async fn rust_cdp_p0_page_close_destroys_target() {ctx.expect_result(131_999, json!({}), None);let page = CdpPageHarness::attach(&mut ctx, 132_000).await;- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page.target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page.target_id);ctx.process_async(json!({"id": 132_005,"method": "Target.setDiscoverTargets",@@ -156,7 +156,7 @@ async fn rust_cdp_p0_page_close_destroys_target() {inspector_detached < target_info_changed&& target_info_changed < target_detached&& target_detached < target_destroyed- && target_detached < tab_destroyed,+ && target_destroyed < tab_destroyed,"Page.close terminal event order should match Chromium: {messages:?}");diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs b/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rsindex 17eb48629..294169179 100644--- a/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs+++ b/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs@@ -561,6 +561,72 @@ async fn close_active_target_promotes_background_target_to_active_slot() {assert!(bc.background_targets.is_empty());}+#[tokio::test(flavor = "multi_thread")]+async fn close_active_target_exposes_promoted_target_screencast() {+ let mut ctx = TestContext::new();+ load_bc_with_titled_page_async(&mut ctx, "BID-9", "TID-active", "<title>active</title>").await;+ ctx.conn+ .browser_context+ .as_mut()+ .unwrap()+ .attach_active_session("SID-active");++ ctx.process_async(json!({+ "id": 20,+ "method": "Target.createTarget",+ "params": {"browserContextId": "BID-9", "url": "about:blank#parked"}+ }))+ .await;+ let parked_target_id = take_created_target_id(&mut ctx, 20);++ ctx.process_async(json!({+ "id": 21,+ "method": "Target.attachToTarget",+ "params": {"targetId": parked_target_id}+ }))+ .await;+ let parked_session_id = take_response_by_id(&mut ctx, 21)["result"]["sessionId"]+ .as_str()+ .expect("parked target session")+ .to_owned();+ ctx.expect_event("Target.attachedToTarget", None);++ ctx.process_async(json!({+ "id": 22,+ "method": "Page.startScreencast",+ "sessionId": parked_session_id,+ "params": {}+ }))+ .await;+ let hidden = ctx.take_first_matching("parked screencast starts hidden", |message| {+ message["method"] == json!("Page.screencastVisibilityChanged")+ });+ assert_eq!(hidden["sessionId"], json!(parked_session_id));+ assert_eq!(hidden["params"]["visible"], json!(false));+ ctx.expect_result(22, json!({}), Some(&parked_session_id));++ ctx.process_async(json!({+ "id": 23,+ "method": "Target.closeTarget",+ "params": {"targetId": "TID-active"}+ }))+ .await;+ ctx.expect_result(23, json!({ "success": true }), None);+ let visible = ctx.take_first_matching("promoted screencast becomes visible", |message| {+ message["method"] == json!("Page.screencastVisibilityChanged")+ && message["sessionId"] == json!(parked_session_id)+ });+ assert_eq!(visible["params"]["visible"], json!(true));++ assert_eq!(+ ctx.conn+ .browser_context+ .as_ref()+ .and_then(BrowserContext::active_target_id),+ Some(parked_target_id.as_str())+ );+}+#[tokio::test(flavor = "multi_thread")]async fn close_active_target_promoted_background_session_can_navigate_and_evaluate() {let mut ctx = TestContext::new();diff --git a/moli-protocol/src/domains/target/tests/tests_target_attachment.rs b/moli-protocol/src/domains/target/tests/tests_target_attachment.rsindex ef88ccf0f..bdbee6d49 100644--- a/moli-protocol/src/domains/target/tests/tests_target_attachment.rs+++ b/moli-protocol/src/domains/target/tests/tests_target_attachment.rs@@ -136,7 +136,7 @@ async fn attach_to_target_tab_returns_control_plane_session() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -165,6 +165,19 @@ async fn attach_to_target_tab_returns_control_plane_session() {}) if route_tab_target_id == &tab_target_id));+ ctx.process_async(json!({+ "id": 11016,+ "sessionId": tab_session_id.clone(),+ "method": "Target.getTargetInfo"+ }))+ .await;+ let owner_info = take_response_by_id(&mut ctx, 11016);+ assert_eq!(+ owner_info["result"]["targetInfo"]["targetId"],+ json!(tab_target_id)+ );+ assert_eq!(owner_info["result"]["targetInfo"]["type"], json!("tab"));+ctx.process_async(json!({"id": 11014,"method": "Target.attachToTarget",@@ -202,9 +215,10 @@ async fn attach_to_target_tab_returns_control_plane_session() {})).await;let runtime_response = take_response_by_id(&mut ctx, 11012);- assert!(- runtime_response.get("error").is_some(),- "tab session must not route Runtime.evaluate to its page: {runtime_response:?}"+ assert_eq!(runtime_response["error"]["code"], json!(-32601));+ assert_eq!(+ runtime_response["error"]["message"],+ json!("'Runtime.evaluate' wasn't found"));ctx.process_async(json!({@@ -262,7 +276,7 @@ async fn detach_tab_session_detaches_auto_attached_child_page_session() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -2736,7 +2750,7 @@ async fn set_auto_attach_filter_page_exclude_catchall_auto_attaches_existing_tab.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({diff --git a/moli-protocol/src/domains/target/tests/tests_target_creation.rs b/moli-protocol/src/domains/target/tests/tests_target_creation.rsindex a5ebda810..71cca5ece 100644--- a/moli-protocol/src/domains/target/tests/tests_target_creation.rs+++ b/moli-protocol/src/domains/target/tests/tests_target_creation.rs@@ -66,20 +66,61 @@ async fn create_target_creates_browser_context_if_none() {.await;let bc = ctx.conn.browser_context.as_ref().unwrap();let tid = bc.active_target_id_owned().unwrap();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&tid);+ let tab_target_id = tab_id_for_page(&ctx, &tid);assert_eq!(ctx.conn.tab_target_id_for_page_target_id(&tid),Some(tab_target_id.as_str()));assert_eq!(- ctx.conn.page_target_id_for_tab_target_id(&tab_target_id),+ ctx.conn+ .primary_page_target_id_for_tab_target_id(&tab_target_id),Some(tid.as_str()));- assert_eq!(ctx.conn.top_level_target_graph_len(), 1);+ assert_eq!(ctx.conn.tab_target_count(), 1);ctx.expect_event("Target.targetCreated", None);ctx.expect_result(10, json!({ "targetId": tid }), None);}+#[tokio::test(flavor = "multi_thread")]+async fn create_target_for_tab_returns_the_stable_tab_host() {+ let mut ctx = TestContext::new();+ ctx.process_async(json!({+ "id": 10000,+ "method": "Target.createTarget",+ "params": { "url": "about:blank", "forTab": true }+ }))+ .await;++ let tab_target_id = take_response_by_id(&mut ctx, 10000)["result"]["targetId"]+ .as_str()+ .expect("created tab target id")+ .to_owned();+ let page_target_id = ctx+ .conn+ .primary_page_target_id_for_tab_target_id(&tab_target_id)+ .expect("created tab must expose its primary page")+ .to_owned();+ assert_ne!(tab_target_id, page_target_id);++ ctx.process_async(json!({+ "id": 10001,+ "method": "Target.getTargetInfo",+ "params": { "targetId": tab_target_id.clone() }+ }))+ .await;+ let tab_info = take_response_by_id(&mut ctx, 10001);+ assert_eq!(tab_info["result"]["targetInfo"]["type"], json!("tab"));++ ctx.process_async(json!({+ "id": 10002,+ "method": "Target.getTargetInfo",+ "params": { "targetId": page_target_id.clone() }+ }))+ .await;+ let page_info = take_response_by_id(&mut ctx, 10002);+ assert_eq!(page_info["result"]["targetInfo"]["type"], json!("page"));+}+#[tokio::test(flavor = "multi_thread")]async fn get_targets_default_filter_excludes_tab() {let mut ctx = TestContext::new();@@ -111,7 +152,7 @@ async fn get_targets_default_filter_excludes_tab() {}#[tokio::test(flavor = "multi_thread")]-async fn get_targets_tab_filter_returns_derived_tab_target() {+async fn get_targets_tab_filter_returns_stable_tab_target() {let mut ctx = TestContext::new();ctx.process_async(json!({"id": 10020,@@ -123,7 +164,7 @@ async fn get_targets_tab_filter_returns_derived_tab_target() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -159,7 +200,7 @@ async fn get_targets_catchall_includes_tab_and_page_with_attached_state() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -214,7 +255,7 @@ async fn get_target_info_returns_tab_target_info() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -246,7 +287,7 @@ async fn set_discover_targets_catchall_reports_tab_and_page() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -328,7 +369,7 @@ async fn get_targets_without_filter_reuses_discovery_filter() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -401,7 +442,7 @@ async fn target_destroyed_uses_reported_hosts_after_discovery_filter_changes() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -1871,7 +1912,7 @@ async fn window_open_named_target_reused_in_same_command_emits_one_page_event()}#[tokio::test(flavor = "multi_thread")]-async fn named_popup_reuse_with_catchall_discovery_emits_tab_and_page_target_info_changed() {+async fn named_popup_reuse_with_catchall_discovery_only_changes_the_page_target_info() {let mut ctx = TestContext::new();load_bc_with_titled_page_async(&mut ctx,@@ -1916,7 +1957,7 @@ async fn named_popup_reuse_with_catchall_discovery_emits_tab_and_page_target_inf.as_str().expect("popup page target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);assert!(first_sent.iter().any(|message| {message["method"] == json!("Target.targetCreated")@@ -1937,14 +1978,11 @@ async fn named_popup_reuse_with_catchall_discovery_emits_tab_and_page_target_inflet second_sent = ctx.take_all();assert!(- second_sent.iter().any(|message| {- message["method"] == json!("Target.targetInfoChanged")- && message["params"]["targetInfo"]["targetId"] == json!(tab_target_id)- && message["params"]["targetInfo"]["type"] == json!("tab")- && message["params"]["targetInfo"]["url"]- == json!("https://example.com/second-popup")+ second_sent.iter().all(|message| {+ message["method"] != json!("Target.targetInfoChanged")+ || message["params"]["targetInfo"]["targetId"] != json!(tab_target_id)}),- "catch-all discovery should report tab targetInfoChanged: {second_sent:?}"+ "document navigation must not mirror Page targetInfoChanged onto the stable Tab host: {second_sent:?}");assert!(second_sent.iter().any(|message| {@@ -2429,7 +2467,7 @@ async fn create_target_with_puppeteer_tab_filter_auto_attaches_tab() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&target_id);+ let tab_target_id = tab_id_for_page(&ctx, &target_id);let created = ctx.sent.iter()@@ -2483,7 +2521,7 @@ async fn closing_puppeteer_tab_auto_attach_clears_service_worker_pause_owner() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&target_id);+ let tab_target_id = tab_id_for_page(&ctx, &target_id);let tab_session_id = ctx.sent.iter()@@ -2592,7 +2630,7 @@ async fn window_open_with_puppeteer_tab_filter_auto_attaches_popup_tab() {.as_str().expect("popup page target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);let attached = sent.iter().find(|message| {@@ -2696,7 +2734,7 @@ async fn browser_session_auto_attach_routes_popup_tab_attached_event_to_owner_se.as_str().expect("popup page target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);let attached = sent.iter().find(|message| {@@ -2770,7 +2808,7 @@ async fn tab_session_auto_attach_catchall_attaches_child_page() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);let tab_attached = ctx.take_first_matching("tab attachedToTarget", |message| {message["method"] == json!("Target.attachedToTarget")&& message["params"]["targetInfo"]["targetId"] == json!(tab_target_id)@@ -2845,7 +2883,7 @@ async fn root_auto_attach_disable_detaches_auto_attached_tab_child_page_cascade(.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);let tab_attached = ctx.take_first_matching("tab attachedToTarget", |message| {message["method"] == json!("Target.attachedToTarget")&& message["params"]["targetInfo"]["targetId"] == json!(tab_target_id)@@ -2926,8 +2964,7 @@ async fn tab_session_auto_attach_only_attaches_its_own_child_page() {.as_str().expect("first target id").to_owned();- let first_tab_target_id =- crate::conn::CdpConnection::derived_tab_target_id(&first_page_target_id);+ let first_tab_target_id = tab_id_for_page(&ctx, &first_page_target_id);ctx.process_async(json!({"id": 9041,@@ -2939,8 +2976,7 @@ async fn tab_session_auto_attach_only_attaches_its_own_child_page() {.as_str().expect("second target id").to_owned();- let second_tab_target_id =- crate::conn::CdpConnection::derived_tab_target_id(&second_page_target_id);+ let second_tab_target_id = tab_id_for_page(&ctx, &second_page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -3032,7 +3068,7 @@ async fn incomplete_popup_rollback_clears_tab_page_sessions_and_target_graph() {.is_some());assert!(ctx.conn.session_route(Some("SID-popup-page-aux")).is_some());- assert_eq!(ctx.conn.top_level_target_graph_len(), 1);+ assert_eq!(ctx.conn.tab_target_count(), 1);lifecycle::rollback_incomplete_popup_target_async(&mut ctx.conn,@@ -3045,7 +3081,7 @@ async fn incomplete_popup_rollback_clears_tab_page_sessions_and_target_graph() {assert_eq!(ctx.conn.session_route(Some("SID-popup-page-primary")), None);assert_eq!(ctx.conn.session_route(Some("SID-popup-page-aux")), None);assert!(ctx.conn.auto_attached_sessions_for_owner(None).is_empty());- assert_eq!(ctx.conn.top_level_target_graph_len(), 0);+ assert_eq!(ctx.conn.tab_target_count(), 0);assert!(ctx.conn.browser_context@@ -3056,7 +3092,7 @@ async fn incomplete_popup_rollback_clears_tab_page_sessions_and_target_graph() {);assert!(ctx.conn- .page_target_id_for_tab_target_id(&tab_target_id)+ .primary_page_target_id_for_tab_target_id(&tab_target_id).is_none());}@@ -3106,7 +3142,7 @@ async fn incomplete_active_popup_rollback_clears_active_slot_sessions_and_target.session_route(Some("SID-active-popup-page-aux")).is_some());- assert_eq!(ctx.conn.top_level_target_graph_len(), 1);+ assert_eq!(ctx.conn.tab_target_count(), 1);lifecycle::rollback_incomplete_popup_target_async(&mut ctx.conn,@@ -3126,7 +3162,7 @@ async fn incomplete_active_popup_rollback_clears_active_slot_sessions_and_targetNone);assert!(ctx.conn.auto_attached_sessions_for_owner(None).is_empty());- assert_eq!(ctx.conn.top_level_target_graph_len(), 0);+ assert_eq!(ctx.conn.tab_target_count(), 0);assert_eq!(ctx.conn.browser_context@@ -3137,7 +3173,7 @@ async fn incomplete_active_popup_rollback_clears_active_slot_sessions_and_target);assert!(ctx.conn- .page_target_id_for_tab_target_id(&tab_target_id)+ .primary_page_target_id_for_tab_target_id(&tab_target_id).is_none());}diff --git a/moli-protocol/src/domains/target/tests/tests_target_management.rs b/moli-protocol/src/domains/target/tests/tests_target_management.rsindex 97bb2952c..a21120dd1 100644--- a/moli-protocol/src/domains/target/tests/tests_target_management.rs+++ b/moli-protocol/src/domains/target/tests/tests_target_management.rs@@ -149,7 +149,7 @@ async fn close_target_tab_id_closes_page_pair_and_detaches_tab_session() {.as_str().expect("created target id").to_owned();- let tab_target_id = crate::conn::CdpConnection::derived_tab_target_id(&page_target_id);+ let tab_target_id = tab_id_for_page(&ctx, &page_target_id);ctx.sent.clear();ctx.process_async(json!({@@ -188,7 +188,8 @@ async fn close_target_tab_id_closes_page_pair_and_detaches_tab_session() {.is_empty());assert_eq!(- ctx.conn.page_target_id_for_tab_target_id(&tab_target_id),+ ctx.conn+ .primary_page_target_id_for_tab_target_id(&tab_target_id),None);diff --git a/moli-protocol/src/lib.rs b/moli-protocol/src/lib.rsindex 787593f74..c1b1020c5 100644--- a/moli-protocol/src/lib.rs+++ b/moli-protocol/src/lib.rs@@ -24,7 +24,8 @@ pub use conn::{CdpTargetHostLifecycleDelta, CdpTargetHostLifecycleObserver, CdpTurnOutcome,CommandDispatchContext, CommandResponseFlushContext, CommandResponseFlushPermit,CompletedCdpCommandDispatch, CompletedDeferredMainDocumentLoadCompletion,- CompletedRuntimeProtocolMessageDispatch, DeferredMainDocumentLoadCompletionOutputAction,+ CompletedRuntimeProtocolMessageDispatch, DEFAULT_CDP_PAGE_TARGET_ID, DEFAULT_CDP_TAB_TARGET_ID,+ DeferredMainDocumentLoadCompletionOutputAction,DeferredMainDocumentLoadCompletionOutputInterest, DeferredMainDocumentLoadObservationId,DeferredMainDocumentLoadPredecessorCandidate, DevToolsCommandDispatchOutcome,DevToolsDocumentLifecycleWaitKey, DevToolsDocumentLifecycleWaitState,