Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(cdp): separate browser window selection from document activity

ldm0f1c5bf6618f7
diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rs
index af35f2481..f27d896d1 100644
--- a/moli-core/src/page/mod.rs
+++ b/moli-core/src/page/mod.rs
@@ -193,6 +193,7 @@ pub use crate::renderer::{
pub struct Page {
page_state: PageStateCache,
+ requested_document_activity: std::cell::Cell<moli_page_types::DocumentActivity>,
// Chromium owns this on RenderFrameHostImpl::IdleManager. Keep it on the
// current document handle instead of deriving browser-side navigation
// policy from whichever renderer snapshot the protocol actor consumed
@@ -223,6 +224,7 @@ impl Page {
) -> Self {
let idle_override = page_state.idle_override();
Self {
+ requested_document_activity: std::cell::Cell::new(page_state.document_activity),
page_state: PageStateCache::new(page_state),
idle_override,
handle,
@@ -239,6 +241,7 @@ impl Page {
) -> Self {
let idle_override = page_state.idle_override();
Self {
+ requested_document_activity: std::cell::Cell::new(page_state.document_activity),
page_state: PageStateCache::new(page_state),
idle_override,
handle,
diff --git a/moli-core/src/page/settings_support.rs b/moli-core/src/page/settings_support.rs
index 4161565f9..e13635159 100644
--- a/moli-core/src/page/settings_support.rs
+++ b/moli-core/src/page/settings_support.rs
@@ -535,28 +535,37 @@ impl Page {
navigator_overrides: moli_page_types::NavigatorOverrides,
document_activity: moli_page_types::DocumentActivity,
) -> Result<PendingPageCommand> {
- self.start_page_command(RendererPageCommand::SetNavigatorAndDocumentActivity {
- navigator_overrides,
- document_activity,
- })
+ let pending =
+ self.start_page_command(RendererPageCommand::SetNavigatorAndDocumentActivity {
+ navigator_overrides,
+ document_activity,
+ })?;
+ self.requested_document_activity.set(document_activity);
+ Ok(pending)
+ }
+
+ /// Last activity policy admitted by this Page. It includes queued updates,
+ /// so a focus reversal cannot be skipped while its renderer is busy.
+ pub fn document_activity(&self) -> moli_page_types::DocumentActivity {
+ self.requested_document_activity.get()
}
pub async fn set_document_activity_async(
&mut self,
activity: moli_page_types::DocumentActivity,
) -> Result<()> {
- self.dispatch_unit_page_command_async(
- RendererPageCommand::SetDocumentActivity(activity),
- "set document activity",
- )
- .await
+ let pending = self.start_set_document_activity(activity)?;
+ self.finish_set_document_activity(pending.wait().await?)
}
pub fn start_set_document_activity(
&self,
activity: moli_page_types::DocumentActivity,
) -> Result<PendingPageCommand> {
- self.start_page_command(RendererPageCommand::SetDocumentActivity(activity))
+ let pending =
+ self.start_page_command(RendererPageCommand::SetDocumentActivity(activity))?;
+ self.requested_document_activity.set(activity);
+ Ok(pending)
}
pub fn finish_set_document_activity(&mut self, completion: CompletedPageCommand) -> Result<()> {
diff --git a/moli-core/src/runtime/tests.rs b/moli-core/src/runtime/tests.rs
index c4cab5e13..6dfb26bdd 100644
--- a/moli-core/src/runtime/tests.rs
+++ b/moli-core/src/runtime/tests.rs
@@ -4503,6 +4503,7 @@ async fn renderer_owner_remove_unknown_page_keeps_never_tracked_state() -> Resul
navigation_redirect_chain: Vec::new(),
final_url: Url::parse("https://example.com/final")?,
document_title: String::new(),
+ document_activity: Default::default(),
status: 200,
headers: Vec::new(),
idle_override: None,
diff --git a/moli-protocol-server/src/cdp_scheduler.rs b/moli-protocol-server/src/cdp_scheduler.rs
index a5932898c..022bfc8bc 100644
--- a/moli-protocol-server/src/cdp_scheduler.rs
+++ b/moli-protocol-server/src/cdp_scheduler.rs
@@ -228,6 +228,8 @@ pub(crate) type CdpBackgroundNavigationCompletionReceiver =
mpsc::UnboundedReceiver<BackgroundNavigationCompletion>;
pub(crate) type CdpRendererPublicationReceiver = moli_core::RendererOutputTransportReceiver;
pub(crate) struct CdpSchedulerEventReceivers {
+ pub(crate) document_activity_completion_rx:
+ mpsc::UnboundedReceiver<moli_protocol::conn::CompletedDocumentActivityUpdate>,
pub(crate) background_event_rx: CdpBackgroundEventReceiver,
pub(crate) background_navigation_completion_rx: CdpBackgroundNavigationCompletionReceiver,
pub(crate) renderer_publication_rx: CdpRendererPublicationReceiver,
@@ -244,6 +246,7 @@ pub(crate) struct CdpSchedulerEventReceivers {
/// value in the caller makes ownership unambiguous: once dequeued, the input
/// is completed before the command wait selects again.
pub(crate) enum CdpSchedulerInterleavedInput {
+ DocumentActivityCompletion(moli_protocol::conn::CompletedDocumentActivityUpdate),
BackgroundNavigationCompletion(BackgroundNavigationCompletion),
BackgroundEvent(BackgroundProtocolEvent),
RendererPublication(RendererOutputTransportMessage),
@@ -253,6 +256,9 @@ impl CdpSchedulerEventReceivers {
pub(crate) async fn recv_interleaved_input(&mut self) -> Option<CdpSchedulerInterleavedInput> {
tokio::select! {
biased;
+ maybe_completion = self.document_activity_completion_rx.recv() => {
+ maybe_completion.map(CdpSchedulerInterleavedInput::DocumentActivityCompletion)
+ }
maybe_completion = self.background_navigation_completion_rx.recv() => {
maybe_completion.map(
CdpSchedulerInterleavedInput::BackgroundNavigationCompletion,
@@ -792,6 +798,11 @@ impl CdpScheduler {
scheduler
.conn
.set_background_event_sender(background_event_tx);
+ let (document_activity_completion_tx, document_activity_completion_rx) =
+ mpsc::unbounded_channel();
+ scheduler
+ .conn
+ .set_document_activity_completion_sender(document_activity_completion_tx);
let (background_navigation_completion_tx, background_navigation_completion_rx) =
mpsc::unbounded_channel();
scheduler
@@ -805,6 +816,7 @@ impl CdpScheduler {
(
scheduler,
CdpSchedulerEventReceivers {
+ document_activity_completion_rx,
background_event_rx,
background_navigation_completion_rx,
renderer_publication_rx,
@@ -2004,6 +2016,11 @@ impl CdpScheduler {
input: CdpSchedulerInterleavedInput,
) -> Result<ProtocolOutputSequence, RendererOutputTransportFailure> {
match input {
+ CdpSchedulerInterleavedInput::DocumentActivityCompletion(completion) => {
+ let outcome = self.conn.complete_document_activity_update(completion);
+ self.apply_renderer_owner_turn_outcome(receivers, outcome)
+ .await
+ }
CdpSchedulerInterleavedInput::BackgroundNavigationCompletion(completion) => {
self.drain_background_navigation_completion_with_progress_barrier(
completion, receivers,
diff --git a/moli-protocol-server/src/cdp_scheduler/actor.rs b/moli-protocol-server/src/cdp_scheduler/actor.rs
index efc067813..3d634ecf3 100644
--- a/moli-protocol-server/src/cdp_scheduler/actor.rs
+++ b/moli-protocol-server/src/cdp_scheduler/actor.rs
@@ -79,6 +79,7 @@ fn page_javascript_owner_is_blocked(
}
enum SchedulerInput {
+ DocumentActivityCompletion(moli_protocol::conn::CompletedDocumentActivityUpdate),
BackgroundNavigationCompletion(BackgroundNavigationCompletion),
BackgroundEvent(BackgroundProtocolEvent),
RendererPublication(RendererOutputTransportMessage),
@@ -87,6 +88,8 @@ enum SchedulerInput {
}
struct SchedulerInputReceivers {
+ document_activity_completion_rx:
+ mpsc::UnboundedReceiver<moli_protocol::conn::CompletedDocumentActivityUpdate>,
background_event_rx: CdpBackgroundEventReceiver,
background_navigation_completion_rx: CdpBackgroundNavigationCompletionReceiver,
renderer_publication_rx: CdpRendererPublicationReceiver,
@@ -97,6 +100,7 @@ struct SchedulerInputReceivers {
impl SchedulerInputReceivers {
fn new(receivers: CdpSchedulerEventReceivers) -> Self {
Self {
+ document_activity_completion_rx: receivers.document_activity_completion_rx,
background_event_rx: receivers.background_event_rx,
background_navigation_completion_rx: receivers.background_navigation_completion_rx,
renderer_publication_rx: receivers.renderer_publication_rx,
@@ -118,6 +122,10 @@ impl SchedulerInputReceivers {
// A correlated response carries an exact concrete output cursor; the
// cursor fence below consumes only concrete stream traffic until that
// position is admitted.
+ while let Ok(completion) = self.document_activity_completion_rx.try_recv() {
+ self.ready_background_inputs_before_runtime_response
+ .push_back(SchedulerInput::DocumentActivityCompletion(completion));
+ }
while let Ok(completion) = self.background_navigation_completion_rx.try_recv() {
self.ready_background_inputs_before_runtime_response
.push_back(SchedulerInput::BackgroundNavigationCompletion(completion));
@@ -176,6 +184,9 @@ impl SchedulerInputReceivers {
self.queue_ready_background_inputs_before_runtime_response(response);
self.ready_background_inputs_before_runtime_response.pop_front()
}
+ maybe_completion = self.document_activity_completion_rx.recv() => {
+ maybe_completion.map(SchedulerInput::DocumentActivityCompletion)
+ }
maybe_completion = self.background_navigation_completion_rx.recv() => {
maybe_completion.map(SchedulerInput::BackgroundNavigationCompletion)
}
@@ -192,6 +203,9 @@ impl SchedulerInputReceivers {
} else {
tokio::select! {
biased;
+ maybe_completion = self.document_activity_completion_rx.recv() => {
+ maybe_completion.map(SchedulerInput::DocumentActivityCompletion)
+ }
maybe_completion = self.background_navigation_completion_rx.recv() => {
maybe_completion.map(SchedulerInput::BackgroundNavigationCompletion)
}
@@ -442,6 +456,31 @@ async fn handle_scheduler_input(
);
}
let ok = match input {
+ SchedulerInput::DocumentActivityCompletion(completion) => {
+ let outcome = scheduler.conn.complete_document_activity_update(completion);
+ let (output, post_output, boundary, predecessor) =
+ scheduler.materialize_renderer_owner_turn_outcome(outcome);
+ assert!(boundary.is_none() && post_output.is_empty());
+ if !flush_renderer_publication_predecessor(
+ frontend_router,
+ scheduler,
+ scheduler_input_rx,
+ pending_runtime_deferred_replies,
+ adapter_scheduler,
+ predecessor.as_ref(),
+ )
+ .await
+ {
+ return false;
+ }
+ flush_protocol_output_with_runtime_deferred_reply_routing(
+ frontend_router,
+ scheduler,
+ pending_runtime_deferred_replies,
+ output,
+ )
+ .await
+ }
SchedulerInput::BackgroundNavigationCompletion(_) => {
if !flush_background_completion_input(
frontend_router,
@@ -1990,6 +2029,7 @@ fn trace_scheduler_input(input: &SchedulerInput, stage: &'static str) {
fn scheduler_input_kind(input: &SchedulerInput) -> &'static str {
match input {
+ SchedulerInput::DocumentActivityCompletion(_) => "document_activity_completion",
SchedulerInput::BackgroundNavigationCompletion(_) => "background_navigation_completion",
SchedulerInput::BackgroundEvent(_) => "background_event",
SchedulerInput::DeferredRuntimeInspectorResponse(_) => {
@@ -2065,7 +2105,9 @@ mod tests {
mpsc::unbounded_channel();
let (_renderer_publication_tx, renderer_publication_rx) =
moli_core::renderer_output_transport_channel();
+ let (_activity_tx, document_activity_completion_rx) = mpsc::unbounded_channel();
let mut receivers = SchedulerInputReceivers::new(CdpSchedulerEventReceivers {
+ document_activity_completion_rx,
background_event_rx,
background_navigation_completion_rx,
renderer_publication_rx,
diff --git a/moli-protocol-server/src/cdp_scheduler/tests.rs b/moli-protocol-server/src/cdp_scheduler/tests.rs
index 86fb45a8d..45f793ba2 100644
--- a/moli-protocol-server/src/cdp_scheduler/tests.rs
+++ b/moli-protocol-server/src/cdp_scheduler/tests.rs
@@ -1012,7 +1012,9 @@ async fn closed_renderer_transport_fails_an_unprojected_command_fence() {
tokio::sync::mpsc::unbounded_channel();
let (renderer_tx, renderer_publication_rx) = moli_core::renderer_output_transport_channel();
drop(renderer_tx);
+ let (_activity_tx, document_activity_completion_rx) = tokio::sync::mpsc::unbounded_channel();
let mut receivers = super::CdpSchedulerEventReceivers {
+ document_activity_completion_rx,
background_event_rx,
background_navigation_completion_rx,
renderer_publication_rx,
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
index 6ffae0ed5..4c443674f 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
@@ -1875,6 +1875,478 @@ async fn target_create_for_tab_exposes_distinct_chromium_agent_hosts() {
abort_test_cdp_server(server).await;
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn new_windows_keep_independent_tab_selection_and_bounds() {
+ for (first_new_window, background) in
+ [(false, false), (false, true), (true, false), (true, true)]
+ {
+ verify_independent_window_selection(first_new_window, background).await;
+ }
+}
+
+async fn verify_independent_window_selection(first_new_window: bool, background: bool) {
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let first_created = send_cdp_command(
+ &mut browser,
+ 1,
+ "Target.createTarget",
+ None,
+ json!({"url": "about:blank", "newWindow": first_new_window}),
+ )
+ .await;
+ let first_target = response_by_id(&first_created, 1)["result"]["targetId"]
+ .as_str()
+ .unwrap()
+ .to_owned();
+ let created = send_cdp_command(
+ &mut browser,
+ 2,
+ "Target.createTarget",
+ None,
+ json!({"url": "about:blank", "newWindow": true, "background": background}),
+ )
+ .await;
+ let second_target = response_by_id(&created, 2)["result"]["targetId"]
+ .as_str()
+ .unwrap()
+ .to_owned();
+ let third_target = create_dynamic_target(&mut browser, 3).await;
+ let mut windows = Vec::new();
+ for (index, target) in [&first_target, &second_target, &third_target]
+ .into_iter()
+ .enumerate()
+ {
+ let id = 10 + index as u64;
+ let messages = send_cdp_command(
+ &mut browser,
+ id,
+ "Browser.getWindowForTarget",
+ None,
+ json!({"targetId": target}),
+ )
+ .await;
+ windows.push(response_by_id(&messages, id)["result"]["windowId"].clone());
+ }
+ assert_ne!(windows[0], windows[1]);
+ assert_eq!(windows[if background { 0 } else { 1 }], windows[2]);
+ let mut first = connect_dynamic_page(addr, &first_target).await;
+ let mut second = connect_dynamic_page(addr, &second_target).await;
+ let mut third = connect_dynamic_page(addr, &third_target).await;
+ async fn activity(socket: &mut TestCdpSocket, id: u64) -> serde_json::Value {
+ let messages = send_cdp_command(socket, id, "Runtime.evaluate", None,
+ json!({"expression": "[document.hasFocus(), document.visibilityState]", "returnByValue": true})).await;
+ response_by_id(&messages, id)["result"]["result"]["value"].clone()
+ }
+ assert_eq!(
+ activity(&mut first, 1).await,
+ json!([false, if background { "hidden" } else { "visible" }])
+ );
+ assert_eq!(
+ activity(&mut second, 1).await,
+ json!([false, if background { "visible" } else { "hidden" }])
+ );
+ assert_eq!(activity(&mut third, 1).await, json!([true, "visible"]));
+ send_cdp_command(
+ &mut browser,
+ 20,
+ "Target.activateTarget",
+ None,
+ json!({"targetId": first_target}),
+ )
+ .await;
+ assert_eq!(activity(&mut first, 2).await, json!([true, "visible"]));
+ assert_eq!(
+ activity(&mut third, 2).await,
+ json!([false, if background { "hidden" } else { "visible" }])
+ );
+ send_cdp_command(
+ &mut browser,
+ 21,
+ "Target.closeTarget",
+ None,
+ json!({"targetId": third_target}),
+ )
+ .await;
+ assert_eq!(activity(&mut second, 2).await, json!([false, "visible"]));
+ for (index, target) in [&first_target, &second_target].into_iter().enumerate() {
+ let id = 30 + index as u64;
+ let set = send_cdp_command(&mut browser, id, "Browser.setWindowBounds", None,
+ json!({"windowId": windows[index], "bounds": {"width": 700 + index * 100, "height": 600}})).await;
+ assert_eq!(response_by_id(&set, id)["result"], json!({}));
+ let get = send_cdp_command(
+ &mut browser,
+ id + 10,
+ "Browser.getWindowForTarget",
+ None,
+ json!({"targetId": target}),
+ )
+ .await;
+ assert_eq!(
+ response_by_id(&get, id + 10)["result"]["bounds"]["width"],
+ json!(700 + index * 100)
+ );
+ }
+ send_cdp_command(
+ &mut browser,
+ 50,
+ "Target.activateTarget",
+ None,
+ json!({"targetId": second_target}),
+ )
+ .await;
+ send_cdp_command(
+ &mut browser,
+ 51,
+ "Target.closeTarget",
+ None,
+ json!({"targetId": second_target}),
+ )
+ .await;
+ assert_eq!(activity(&mut first, 3).await, json!([true, "visible"]));
+ let closed_window = send_cdp_command(
+ &mut browser,
+ 52,
+ "Browser.setWindowBounds",
+ None,
+ json!({"windowId": windows[1], "bounds": {"width": 900}}),
+ )
+ .await;
+ assert!(response_by_id(&closed_window, 52).get("error").is_some());
+ abort_test_cdp_server(server).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn browser_focus_moves_between_contexts_without_hiding_their_windows() {
+ async fn activity(socket: &mut TestCdpSocket, id: u64) -> serde_json::Value {
+ let messages = send_cdp_command(socket, id, "Runtime.evaluate", None,
+ json!({"expression": "[document.hasFocus(), document.visibilityState]", "returnByValue": true})).await;
+ response_by_id(&messages, id)["result"]["result"]["value"].clone()
+ }
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let first_target = create_dynamic_target(&mut browser, 1).await;
+ let mut first = connect_dynamic_page(addr, &first_target).await;
+ let created = send_cdp_command(
+ &mut browser,
+ 2,
+ "Target.createBrowserContext",
+ None,
+ json!({}),
+ )
+ .await;
+ let context_id = response_by_id(&created, 2)["result"]["browserContextId"]
+ .as_str()
+ .unwrap();
+ let created = send_cdp_command(
+ &mut browser,
+ 3,
+ "Target.createTarget",
+ None,
+ json!({"url": "about:blank", "browserContextId": context_id}),
+ )
+ .await;
+ let second_target = response_by_id(&created, 3)["result"]["targetId"]
+ .as_str()
+ .unwrap();
+ let mut second = connect_dynamic_page(addr, second_target).await;
+ assert_eq!(activity(&mut first, 1).await, json!([false, "visible"]));
+ assert_eq!(activity(&mut second, 1).await, json!([true, "visible"]));
+ send_cdp_command(
+ &mut browser,
+ 4,
+ "Target.activateTarget",
+ None,
+ json!({"targetId": first_target}),
+ )
+ .await;
+ assert_eq!(activity(&mut first, 2).await, json!([true, "visible"]));
+ assert_eq!(activity(&mut second, 2).await, json!([false, "visible"]));
+ send_cdp_command(&mut second, 3, "Page.bringToFront", None, json!({})).await;
+ assert_eq!(activity(&mut first, 3).await, json!([false, "visible"]));
+ assert_eq!(activity(&mut second, 4).await, json!([true, "visible"]));
+ send_cdp_command(
+ &mut browser,
+ 5,
+ "Target.disposeBrowserContext",
+ None,
+ json!({"browserContextId": context_id}),
+ )
+ .await;
+ assert_eq!(activity(&mut first, 4).await, json!([true, "visible"]));
+ abort_test_cdp_server(server).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn foreground_operations_do_not_wait_for_an_unchanged_busy_context() {
+ let entered = Arc::new(tokio::sync::Notify::new());
+ let witness = Arc::clone(&entered);
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new()
+ .route(
+ "/",
+ get(|| async { axum::response::Html("<title>Busy background</title>") }),
+ )
+ .route(
+ "/entered",
+ get(move || {
+ let witness = Arc::clone(&witness);
+ async move {
+ witness.notify_one();
+ "entered"
+ }
+ }),
+ ),
+ "unrelated-busy-context",
+ );
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let first_id = create_dynamic_target(&mut browser, 1).await;
+ let second_id = create_dynamic_target(&mut browser, 2).await;
+ let mut first = connect_dynamic_page(addr, &first_id).await;
+ let mut second = connect_dynamic_page(addr, &second_id).await;
+ let context = send_cdp_command(
+ &mut browser,
+ 3,
+ "Target.createBrowserContext",
+ None,
+ json!({}),
+ )
+ .await;
+ let context_id = response_by_id(&context, 3)["result"]["browserContextId"]
+ .as_str()
+ .unwrap();
+ let created = send_cdp_command(
+ &mut browser,
+ 4,
+ "Target.createTarget",
+ None,
+ json!({"url": "about:blank", "browserContextId": context_id}),
+ )
+ .await;
+ let busy_id = response_by_id(&created, 4)["result"]["targetId"]
+ .as_str()
+ .unwrap();
+ let mut busy = connect_dynamic_page(addr, busy_id).await;
+ send_cdp_command(&mut busy, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut busy, 2, &format!("http://{fixture_addr}/")).await;
+ send_cdp_command(
+ &mut browser,
+ 5,
+ "Target.activateTarget",
+ None,
+ json!({"targetId": first_id}),
+ )
+ .await;
+ assert_eq!(
+ evaluate_window_name_probe(
+ &mut busy,
+ 3,
+ "[document.hasFocus(), document.visibilityState]"
+ )
+ .await,
+ json!([false, "visible"])
+ );
+
+ send_cdp_command_without_wait(&mut busy, 4, "Runtime.evaluate", None, json!({
+ "expression": "const xhr = new XMLHttpRequest(); xhr.open('GET', '/entered', false); xhr.send(); const until = Date.now() + 20000; while (Date.now() < until) {} 'expired'",
+ "returnByValue": true,
+ })).await;
+ timeout(Duration::from_secs(5), entered.notified())
+ .await
+ .expect("busy script entered renderer");
+ let operations = timeout(Duration::from_secs(5), async {
+ let bring = send_cdp_command(&mut first, 1, "Page.bringToFront", None, json!({})).await;
+ let activate = send_cdp_command(
+ &mut browser,
+ 6,
+ "Target.activateTarget",
+ None,
+ json!({"targetId": second_id}),
+ )
+ .await;
+ let temporary = send_cdp_command(
+ &mut browser,
+ 7,
+ "Target.createTarget",
+ None,
+ json!({"url": "about:blank"}),
+ )
+ .await;
+ let temporary_id = response_by_id(&temporary, 7)["result"]["targetId"]
+ .as_str()
+ .unwrap();
+ let close = send_cdp_command(
+ &mut browser,
+ 8,
+ "Target.closeTarget",
+ None,
+ json!({"targetId": temporary_id}),
+ )
+ .await;
+ (bring, activate, temporary, close)
+ })
+ .await;
+ // Always release the witness script before asserting the liveness result.
+ // Its own deadline also bounds cleanup if the IO termination path fails.
+ let terminated =
+ send_cdp_command(&mut busy, 5, "Runtime.terminateExecution", None, json!({})).await;
+ assert!(
+ response_by_id(&terminated, 5)["error"].is_null(),
+ "{terminated:#?}"
+ );
+ assert!(
+ !terminated
+ .iter()
+ .any(|message| message["id"] == 4 && message["result"]["result"]["value"] == "expired"),
+ "the witness must still be busy until termination"
+ );
+ let (bring, activate, temporary, close) = operations.expect(
+ "foreground operations must complete while an unrelated context remains in synchronous JS",
+ );
+ for (response, id) in [(&bring, 1), (&activate, 6), (&temporary, 7), (&close, 8)] {
+ assert!(
+ response_by_id(response, id)["error"].is_null(),
+ "{response:#?}"
+ );
+ }
+ assert_eq!(
+ evaluate_window_name_probe(
+ &mut second,
+ 1,
+ "[document.hasFocus(), document.visibilityState]"
+ )
+ .await,
+ json!([true, "visible"])
+ );
+ assert_eq!(
+ evaluate_window_name_probe(
+ &mut busy,
+ 6,
+ "[document.hasFocus(), document.visibilityState]"
+ )
+ .await,
+ json!([false, "visible"])
+ );
+ abort_test_cdp_server(server).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn background_page_metadata_tracks_titles_and_same_document_navigation() {
+ let fixture_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let fixture_url = format!("http://{}/", fixture_listener.local_addr().unwrap());
+ let fixture_server = tokio::spawn(async move {
+ axum::serve(
+ fixture_listener,
+ axum::Router::new().route(
+ "/",
+ axum::routing::get(|| async {
+ axum::response::Html("<title>Background navigation</title><h1>loaded</h1>")
+ }),
+ ),
+ )
+ .await
+ });
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ send_cdp_command(
+ &mut browser,
+ 1,
+ "Target.setDiscoverTargets",
+ None,
+ json!({"discover": true}),
+ )
+ .await;
+ let background_target = create_dynamic_target(&mut browser, 2).await;
+ let mut page = connect_dynamic_page(addr, &background_target).await;
+ create_dynamic_target(&mut browser, 3).await;
+ send_cdp_command(&mut page, 1, "Page.enable", None, json!({})).await;
+ send_cdp_command_without_wait(
+ &mut page,
+ 2,
+ "Page.navigate",
+ None,
+ json!({"url": fixture_url}),
+ )
+ .await;
+ let mut response_received = false;
+ let mut loaded = false;
+ recv_until_match(&mut page, |message| {
+ response_received |= message["id"] == json!(2);
+ loaded |= message["method"] == json!("Page.loadEventFired");
+ response_received && loaded
+ })
+ .await;
+
+ let targets = send_cdp_command(&mut browser, 4, "Target.getTargets", None, json!({})).await;
+ let target = response_by_id(&targets, 4)["result"]["targetInfos"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|target| target["targetId"] == background_target)
+ .unwrap();
+ assert_eq!(target["title"], "Background navigation");
+
+ for (index, (expression, suffix)) in [
+ ("history.pushState({}, '', '/pushed')", "pushed"),
+ ("history.replaceState({}, '', '/replaced')", "replaced"),
+ ("location.hash = 'fragment'", "replaced#fragment"),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let url = format!("{fixture_url}{suffix}");
+ let response = send_cdp_command(
+ &mut page,
+ 10 + index as u64,
+ "Runtime.evaluate",
+ None,
+ json!({"expression": expression}),
+ )
+ .await;
+ assert!(
+ response_by_id(&response, 10 + index as u64)
+ .get("error")
+ .is_none()
+ );
+ recv_until_match(&mut browser, |message| {
+ message["method"] == "Target.targetInfoChanged"
+ && message["params"]["targetInfo"]["targetId"] == background_target
+ && message["params"]["targetInfo"]["url"] == url
+ })
+ .await;
+ timeout(Duration::from_secs(5), async {
+ loop {
+ let descriptors = fetch_server_json(addr, "/json/list").await;
+ if descriptors.as_array().unwrap().iter().any(|target| {
+ target["id"] == background_target
+ && target["url"] == url
+ && target["title"] == "Background navigation"
+ }) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .expect("HTTP discovery must follow background page metadata");
+ }
+ abort_test_cdp_server(server).await;
+ fixture_server.abort();
+}
+
#[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;
@@ -4116,3 +4588,180 @@ async fn cdp_ordering_navigator_configuration_waits_for_isolate_owner() {
assert_native_isolate_handler_waits_for_resume("Emulation.setHardwareConcurrencyOverride")
.await;
}
+
+async fn evaluate_window_name_probe(
+ page: &mut TestCdpSocket,
+ id: u64,
+ expression: &str,
+) -> serde_json::Value {
+ let messages = send_cdp_command(
+ page,
+ id,
+ "Runtime.evaluate",
+ None,
+ json!({"expression": expression, "returnByValue": true}),
+ )
+ .await;
+ let response = response_by_id(&messages, id);
+ assert!(response["error"].is_null(), "{response}");
+ assert!(
+ response["result"]["exceptionDetails"].is_null(),
+ "{response}"
+ );
+ response["result"]["result"]["value"].clone()
+}
+
+async fn navigate_dynamic_page_and_wait_for_load(page: &mut TestCdpSocket, id: u64, url: &str) {
+ send_cdp_command_without_wait(page, id, "Page.navigate", None, json!({"url": url})).await;
+ let mut responded = false;
+ let mut loaded = false;
+ recv_until_match(page, |message| {
+ responded |= message["id"] == id;
+ loaded |= message["method"] == "Page.loadEventFired";
+ responded && loaded
+ })
+ .await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn focus_change_does_not_wait_for_a_focused_busy_context() {
+ let entered = Arc::new(tokio::sync::Notify::new());
+ let witness = Arc::clone(&entered);
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new()
+ .route(
+ "/",
+ get(|| async { axum::response::Html("<title>Busy background</title>") }),
+ )
+ .route(
+ "/entered",
+ get(move || {
+ let witness = Arc::clone(&witness);
+ async move {
+ witness.notify_one();
+ "entered"
+ }
+ }),
+ ),
+ "unrelated-busy-context",
+ );
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ create_dynamic_target(&mut browser, 1).await;
+ let second_id = create_dynamic_target(&mut browser, 2).await;
+ let context = send_cdp_command(
+ &mut browser,
+ 3,
+ "Target.createBrowserContext",
+ None,
+ json!({}),
+ )
+ .await;
+ let context_id = response_by_id(&context, 3)["result"]["browserContextId"]
+ .as_str()
+ .unwrap();
+ let created = send_cdp_command(
+ &mut browser,
+ 4,
+ "Target.createTarget",
+ None,
+ json!({"url": "about:blank", "browserContextId": context_id}),
+ )
+ .await;
+ let busy_id = response_by_id(&created, 4)["result"]["targetId"]
+ .as_str()
+ .unwrap();
+ let mut busy = connect_dynamic_page(addr, busy_id).await;
+ send_cdp_command(&mut busy, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut busy, 2, &format!("http://{fixture_addr}/")).await;
+ assert_eq!(
+ evaluate_window_name_probe(
+ &mut busy,
+ 3,
+ "[document.hasFocus(), document.visibilityState]"
+ )
+ .await,
+ json!([true, "visible"])
+ );
+
+ send_cdp_command_without_wait(&mut busy, 4, "Runtime.evaluate", None, json!({
+ "expression": "const xhr = new XMLHttpRequest(); xhr.open('GET', '/entered', false); xhr.send(); const until = Date.now() + 5000; while (Date.now() < until) {} 'expired'",
+ "returnByValue": true,
+ })).await;
+ timeout(Duration::from_secs(5), entered.notified())
+ .await
+ .expect("busy script entered renderer");
+ let activation_started = std::time::Instant::now();
+ send_cdp_command_without_wait(
+ &mut browser,
+ 6,
+ "Target.activateTarget",
+ None,
+ json!({"targetId": second_id}),
+ )
+ .await;
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ let version_started = std::time::Instant::now();
+ send_cdp_command_without_wait(&mut browser, 7, "Browser.getVersion", None, json!({})).await;
+ let mut activation_elapsed = None;
+ let mut version_elapsed = None;
+ let responses = recv_until_match(&mut browser, |message| {
+ if message["id"] == 6 {
+ activation_elapsed = Some(activation_started.elapsed());
+ }
+ if message["id"] == 7 {
+ version_elapsed = Some(version_started.elapsed());
+ }
+ activation_elapsed.is_some() && version_elapsed.is_some()
+ })
+ .await;
+ let activation_elapsed = activation_elapsed.unwrap();
+ let version_elapsed = version_elapsed.unwrap();
+ let reversal_started = std::time::Instant::now();
+ let reversal = send_cdp_command(
+ &mut browser,
+ 8,
+ "Target.activateTarget",
+ None,
+ json!({"targetId": busy_id}),
+ )
+ .await;
+ let reversal_elapsed = reversal_started.elapsed();
+ eprintln!(
+ "focused_busy_context_latency: activate_ms={}, version_ms={}",
+ activation_elapsed.as_millis(),
+ version_elapsed.as_millis()
+ );
+ let expired = recv_until_id(&mut busy, 4).await;
+ assert_eq!(
+ response_by_id(&expired, 4)["result"]["result"]["value"],
+ "expired"
+ );
+ let final_activity = evaluate_window_name_probe(
+ &mut busy,
+ 5,
+ "[document.hasFocus(),document.visibilityState]",
+ )
+ .await;
+ abort_test_cdp_server(server).await;
+ assert!(
+ response_by_id(&reversal, 8)["error"].is_null(),
+ "{reversal:#?}"
+ );
+ assert_eq!(final_activity, json!([true, "visible"]));
+ for id in [6, 7] {
+ assert!(
+ response_by_id(&responses, id)["error"].is_null(),
+ "{responses:#?}"
+ );
+ }
+ assert!(
+ activation_elapsed < Duration::from_secs(1)
+ && version_elapsed < Duration::from_secs(1)
+ && reversal_elapsed < Duration::from_secs(1),
+ "a focused busy renderer must not block activation or Browser.getVersion: activate={activation_elapsed:?}, version={version_elapsed:?}"
+ );
+}
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rs
index d970b6d16..01512c305 100644
--- a/moli-protocol/src/conn.rs
+++ b/moli-protocol/src/conn.rs
@@ -45,7 +45,9 @@ mod cookie_policy_surface;
#[cfg(test)]
mod cookie_store_boundary;
mod dispatch;
+mod document_activity_work;
mod downloads;
+pub use document_activity_work::CompletedDocumentActivityUpdate;
mod fetch_support;
mod inspector_route;
mod navigation_error;
@@ -1189,6 +1191,8 @@ pub struct CdpConnection {
// Browser profile, permissions, download and global IO state.
pub window_bounds: BrowserWindowBounds,
+ pub(crate) browser_window_ids: HashMap<(String, u32), u32>,
+ pub(crate) browser_window_bounds: HashMap<u32, BrowserWindowBounds>,
pub download_behavior: BrowserDownloadBehavior,
pub permission_overrides: Vec<PermissionOverride>,
next_global_io_stream_id: u64,
@@ -1483,6 +1487,8 @@ impl CdpConnection {
dedicated_worker_pause_on_start_owner_sessions: HashSet::new(),
install_default_target_on_auto_attach: false,
window_bounds: BrowserWindowBounds::default(),
+ browser_window_ids: HashMap::new(),
+ browser_window_bounds: HashMap::new(),
download_behavior: BrowserDownloadBehavior::default(),
permission_overrides: Vec::new(),
next_bc_id: 0,
@@ -1522,6 +1528,13 @@ impl CdpConnection {
self.scheduler_hooks.set_background_event_sender(sender);
}
+ pub fn set_document_activity_completion_sender(
+ &mut self,
+ sender: tokio::sync::mpsc::UnboundedSender<CompletedDocumentActivityUpdate>,
+ ) {
+ self.scheduler_hooks.document_activity_completion_sender = Some(sender);
+ }
+
pub fn set_shared_target_id_allocator(&mut self, allocator: Arc<AtomicU64>) {
self.shared_target_id_allocator = Some(allocator);
}
diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rs
index 016b07df6..35f9c51e2 100644
--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs
+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs
@@ -1416,8 +1416,11 @@ impl CdpConnection {
if !is_background {
return None;
}
- self.close_page_target_for_target_close_async(target_id, out, reason)
- .await
+ let closed = self
+ .close_page_target_for_target_close_async(target_id, out, reason)
+ .await;
+ self.restore_browser_focus_after_removal_async().await;
+ closed
}
pub(crate) async fn close_active_page_target_for_target_close_async(
@@ -1426,11 +1429,23 @@ impl CdpConnection {
reason: &'static str,
) -> Option<ClosedPageTarget> {
let target_id = self.browser_context.as_ref()?.active_target_id_owned()?;
+ let next_target_id = self
+ .browser_context
+ .as_ref()?
+ .page_targets
+ .adjacent_target_id(&target_id)
+ .map(str::to_owned);
let closed = self
.close_page_target_for_target_close_async(&target_id, out, reason)
.await?;
- let selected_target_id = if let Some(browser_context) = self.browser_context.as_mut() {
- browser_context.select_last_background_target_async().await
+ let selected_target_id = if let Some(browser_context) = self.browser_context.as_mut()
+ && let Some(next_target_id) = next_target_id
+ {
+ browser_context
+ .select_page_target_async(&next_target_id)
+ .await
+ .expect("applying selected target visibility should succeed")
+ .then_some(next_target_id)
} else {
None
};
@@ -1448,7 +1463,7 @@ impl CdpConnection {
}),
);
}
-
+ self.restore_browser_focus_after_removal_async().await;
Some(closed)
}
@@ -1951,7 +1966,21 @@ impl CdpConnection {
if !self.target_page_protocol_attachment_identity_is_current(expected.attachment()) {
return false;
}
- self.runtime_session_owner_slot(expected.session_id())
+ // An implicit attachment may belong to an unattached background Page.
+ // Its frozen residence, not the currently selected Page for session=None,
+ // determines which renderer Document has authority over this output.
+ let residence = expected.attachment().page_owner();
+ let route = match residence.target_id() {
+ Some(target_id) => CdpSessionRoute::PageTarget {
+ browser_context_id: residence.browser_context_id().to_owned(),
+ target_id: target_id.to_owned(),
+ session_key: moli_page_types::DevToolsSessionKey::Primary,
+ },
+ None => CdpSessionRoute::BrowserContext {
+ browser_context_id: residence.browser_context_id().to_owned(),
+ },
+ };
+ self.runtime_session_owner_slot_for_owner(&CommandOwnerScope::for_route(route))
.ok()
.and_then(|slot| slot.page_slot().renderer_document_lifecycle_binding())
.map(crate::conn::CommittedRendererDocumentBinding::renderer_document_identity)
diff --git a/moli-protocol/src/conn/dispatch.rs b/moli-protocol/src/conn/dispatch.rs
index 527c1e1a1..612847363 100644
--- a/moli-protocol/src/conn/dispatch.rs
+++ b/moli-protocol/src/conn/dispatch.rs
@@ -515,7 +515,7 @@ impl CdpConnection {
Some(session_id),
);
};
- if !session_route.supports_cdp_domain(domain) {
+ if !session_route.supports_cdp_method(req.method()) {
return self.complete_with_output_plan(
command_context,
CommandOutputPlan::error(-32601, format!("'{}' wasn't found", req.method())),
diff --git a/moli-protocol/src/conn/dispatch_tests/command_dispatch.rs b/moli-protocol/src/conn/dispatch_tests/command_dispatch.rs
index 9609dbfad..b94614edb 100644
--- a/moli-protocol/src/conn/dispatch_tests/command_dispatch.rs
+++ b/moli-protocol/src/conn/dispatch_tests/command_dispatch.rs
@@ -101,6 +101,7 @@ fn command_dispatch_completes_console_log_and_inspector_owner_commands() {
#[test]
fn command_dispatch_completes_browser_sync_commands() {
let mut conn = CdpConnection::new();
+ conn.publish_default_browser_target();
for (id, method) in [
(20, "Browser.getVersion"),
(21, "Browser.getWindowForTarget"),
diff --git a/moli-protocol/src/conn/document_activity_work.rs b/moli-protocol/src/conn/document_activity_work.rs
new file mode 100644
index 000000000..7e52afda8
--- /dev/null
+++ b/moli-protocol/src/conn/document_activity_work.rs
@@ -0,0 +1,27 @@
+use moli_core::page::RendererCommandTurnOutput;
+
+use super::{CdpConnection, CdpRendererOwnerTurnOutcome, CdpTurnOutcome, CommandDispatchContext};
+
+/// A renderer acknowledgement whose concrete output is already in transport.
+/// Activity never installs a full historical PageState snapshot: another
+/// command or navigation may have completed before this acknowledgement arrives.
+pub struct CompletedDocumentActivityUpdate {
+ pub(super) completion: anyhow::Result<Box<RendererCommandTurnOutput>>,
+}
+
+impl CdpConnection {
+ pub fn complete_document_activity_update(
+ &mut self,
+ update: CompletedDocumentActivityUpdate,
+ ) -> CdpRendererOwnerTurnOutcome {
+ let mut context = CommandDispatchContext::default();
+ match update.completion {
+ Ok(output) => {
+ context.consume_renderer_command_turn_output(*output);
+ }
+ Err(error) => tracing::debug!(%error, "document activity owner update ended"),
+ }
+ CdpTurnOutcome::new_with_protocol_events(Vec::new(), self.take_scheduler_events())
+ .with_renderer_output_predecessor(context.take_renderer_output_predecessor())
+ }
+}
diff --git a/moli-protocol/src/conn/page_state/fetch_state.rs b/moli-protocol/src/conn/page_state/fetch_state.rs
index fc5b546b2..4e00c5ac7 100644
--- a/moli-protocol/src/conn/page_state/fetch_state.rs
+++ b/moli-protocol/src/conn/page_state/fetch_state.rs
@@ -59,7 +59,16 @@ impl BrowserContext {
self.page_targets.background_is_empty()
}
- pub(crate) fn insert_page_target_host(&mut self, mut host: PageTargetHost) -> bool {
+ pub(crate) fn insert_page_target_host(&mut self, host: PageTargetHost) -> bool {
+ let window_id = self.page_targets.default_window_id();
+ self.insert_page_target_host_in_window(host, window_id)
+ }
+
+ pub(crate) fn insert_page_target_host_in_window(
+ &mut self,
+ mut host: PageTargetHost,
+ window_id: u32,
+ ) -> bool {
if self.page_targets.is_empty() {
host.document_cookie_manager_surface =
self.default_document_cookie_manager_surface.clone();
@@ -69,7 +78,7 @@ impl BrowserContext {
let engine = self.new_page_navigation_engine(config);
host.install_navigation_engine(engine);
}
- self.page_targets.insert(host)
+ self.page_targets.insert(host, window_id)
}
#[cfg(test)]
diff --git a/moli-protocol/src/conn/page_state/page_targets.rs b/moli-protocol/src/conn/page_state/page_targets.rs
index b5a489e42..d6c57d902 100644
--- a/moli-protocol/src/conn/page_state/page_targets.rs
+++ b/moli-protocol/src/conn/page_state/page_targets.rs
@@ -29,6 +29,26 @@ impl BrowserContext {
url: String,
initial_empty_document_url: Option<String>,
creator: Option<TargetInitialEmptyDocumentCreator>,
+ ) {
+ let window_id = self.page_targets.default_window_id();
+ self.stage_background_target_in_window(
+ target_id,
+ session_id,
+ url,
+ initial_empty_document_url,
+ creator,
+ window_id,
+ );
+ }
+
+ pub(crate) fn stage_background_target_in_window(
+ &mut self,
+ target_id: String,
+ session_id: Option<String>,
+ url: String,
+ initial_empty_document_url: Option<String>,
+ creator: Option<TargetInitialEmptyDocumentCreator>,
+ window_id: u32,
) {
let session_storage_namespace =
self.deep_cloned_session_storage_namespace_for_creator(creator.as_ref());
@@ -40,6 +60,7 @@ impl BrowserContext {
creator,
None,
session_storage_namespace,
+ window_id,
);
}
@@ -53,6 +74,7 @@ impl BrowserContext {
session_storage_store: Option<SharedWebStorageStore>,
initial_empty_document_storage_key: Option<moli_storage_key::MoliStorageKey>,
) {
+ let window_id = self.page_targets.default_window_id();
let session_storage_namespace = session_storage_store
.map(TargetSessionStorageNamespace::from_store)
.or_else(|| self.deep_cloned_session_storage_namespace_for_creator(creator.as_ref()));
@@ -64,6 +86,7 @@ impl BrowserContext {
creator,
initial_empty_document_storage_key,
session_storage_namespace,
+ window_id,
);
}
@@ -86,6 +109,7 @@ impl BrowserContext {
creator: Option<TargetInitialEmptyDocumentCreator>,
initial_empty_document_storage_key: Option<moli_storage_key::MoliStorageKey>,
session_storage_namespace: Option<TargetSessionStorageNamespace>,
+ window_id: u32,
) {
let target_identity = background_target_identity_for_initial_url(&url, creator.as_ref());
let mut target = PageTargetHost::with_identity(target_id, session_id, target_identity);
@@ -99,10 +123,11 @@ impl BrowserContext {
if let Some(namespace) = session_storage_namespace {
target.replace_session_storage_namespace(namespace);
}
- let inserted = self.insert_page_target_host(target);
+ let inserted = self.insert_page_target_host_in_window(target, window_id);
debug_assert!(inserted, "staged page target id must be unique");
}
+ #[cfg(test)]
pub(crate) fn stage_foreground_target(
&mut self,
target_id: String,
@@ -110,21 +135,14 @@ impl BrowserContext {
url: String,
initial_empty_document_url: Option<String>,
) {
- let mut host = PageTargetHost::with_identity(
+ self.stage_background_target(
target_id.clone(),
session_id,
- TargetIdentityState::with_url(url.clone()),
- );
- host.owner_state.begin_initial_empty_document(
- target_id.clone(),
- initial_empty_document_url.unwrap_or(url),
- None,
+ url,
+ initial_empty_document_url,
None,
);
- let inserted = self.insert_page_target_host(host);
- debug_assert!(inserted, "new active page target id must be unique");
- let selected = self.page_targets.select(&target_id);
- debug_assert!(selected, "newly inserted page target must be selectable");
+ self.set_active_target_id(target_id);
}
pub(crate) fn reusable_window_open_target_name(target_name: &str) -> Option<String> {
@@ -570,24 +588,7 @@ impl BrowserContext {
.await
}
- pub(crate) async fn select_last_background_target_async(&mut self) -> Option<String> {
- let selected_target_id = self.last_selectable_background_target_id()?;
- self.select_background_target_async(selected_target_id)
- .await
- }
-
- pub(crate) fn last_selectable_background_target_id(&self) -> Option<String> {
- self.background_targets()
- .rev()
- .find(|target| target.has_loaded_page())
- .map(|target| target.target_id().to_owned())
- .or_else(|| {
- self.background_targets()
- .next_back()
- .map(|target| target.target_id().to_owned())
- })
- }
-
+ #[cfg(test)]
async fn select_background_target_async(&mut self, target_id: String) -> Option<String> {
self.select_page_target_async(&target_id)
.await
diff --git a/moli-protocol/src/conn/page_state/surfaces.rs b/moli-protocol/src/conn/page_state/surfaces.rs
index 7503c1f0b..ec285454f 100644
--- a/moli-protocol/src/conn/page_state/surfaces.rs
+++ b/moli-protocol/src/conn/page_state/surfaces.rs
@@ -13,6 +13,7 @@ struct SurfaceOverrideInputs {
navigator_queries: moli_page_types::NavigatorQueryOverrides,
focus_emulation_enabled: bool,
active_target_surface: bool,
+ window_is_focused: bool,
window_document_hidden: bool,
}
@@ -35,6 +36,7 @@ impl SurfaceOverrideInputs {
.effective_emulation_state
.focus_emulation_enabled,
active_target_surface: true,
+ window_is_focused: browser_context.window_is_focused,
window_document_hidden: browser_context
.active_page_target()
.owner_state
@@ -46,6 +48,7 @@ impl SurfaceOverrideInputs {
state: &PageTargetHost,
default_network_conditions: Option<EmulatedNetworkConditions>,
default_geolocation_override: Option<EmulatedGeolocationOverrideState>,
+ selected_tab: bool,
) -> Self {
Self {
network_conditions: state
@@ -60,8 +63,9 @@ impl SurfaceOverrideInputs {
max_touch_points: state.effective_emulation_state.max_touch_points,
navigator_queries: state.devtools_sessions.navigator_emulation.effective(),
focus_emulation_enabled: state.effective_emulation_state.focus_emulation_enabled,
- active_target_surface: false,
- window_document_hidden: false,
+ active_target_surface: selected_tab,
+ window_is_focused: false,
+ window_document_hidden: state.owner_state.window_document_hidden(),
}
}
@@ -116,7 +120,7 @@ impl SurfaceOverrideInputs {
}
fn document_is_visible(&self) -> bool {
- self.document_is_focused() && !self.window_document_hidden
+ (self.active_target_surface || self.focus_emulation_enabled) && !self.window_document_hidden
}
fn document_is_focused(&self) -> bool {
@@ -125,7 +129,8 @@ impl SurfaceOverrideInputs {
// report focused and visible by default; background targets
// stay unfocused/hidden unless CDP explicitly asks to simulate a
// focused and active page.
- (self.active_target_surface && !self.window_document_hidden) || self.focus_emulation_enabled
+ (self.active_target_surface && self.window_is_focused && !self.window_document_hidden)
+ || self.focus_emulation_enabled
}
}
@@ -143,6 +148,7 @@ impl BrowserContext {
self.default_geolocation_override
.clone()
.or_else(|| self.global_geolocation_override.clone()),
+ self.page_targets.is_selected_tab(target_id),
)
.navigator_overrides(),
)
@@ -168,6 +174,7 @@ impl BrowserContext {
self.default_geolocation_override
.clone()
.or_else(|| self.global_geolocation_override.clone()),
+ self.page_targets.is_selected_tab(target_id),
)
}
.document_activity(),
diff --git a/moli-protocol/src/conn/scheduler_hooks.rs b/moli-protocol/src/conn/scheduler_hooks.rs
index 7be1aeff0..59b0ada9f 100644
--- a/moli-protocol/src/conn/scheduler_hooks.rs
+++ b/moli-protocol/src/conn/scheduler_hooks.rs
@@ -4,6 +4,8 @@ use super::{BackgroundEventSender, RuntimeInspectorResponseReadySender};
#[derive(Default)]
pub(super) struct CdpSchedulerHooks {
+ pub(super) document_activity_completion_sender:
+ Option<tokio::sync::mpsc::UnboundedSender<super::CompletedDocumentActivityUpdate>>,
background_event_sender: Option<BackgroundEventSender>,
background_navigation_completion_sender: Option<
tokio::sync::mpsc::UnboundedSender<crate::domains::page::BackgroundNavigationCompletion>,
diff --git a/moli-protocol/src/conn/state/browser_context.rs b/moli-protocol/src/conn/state/browser_context.rs
index 18adbdd4a..a4e9f2e2b 100644
--- a/moli-protocol/src/conn/state/browser_context.rs
+++ b/moli-protocol/src/conn/state/browser_context.rs
@@ -41,6 +41,8 @@ pub struct BrowserContext {
pub id: String,
storage_partition: BrowserContextStoragePartition,
pub(crate) page_targets: PageTargetRegistry,
+ /// Browser focus is independent of which context is selected for routing.
+ pub(crate) window_is_focused: bool,
/// Policy retained while the context has no page target yet. The first
/// target inherits it; once targets exist, each target owns its surface.
pub(crate) default_document_cookie_manager_surface: BrowserContextCookieManagerSurface,
@@ -501,6 +503,7 @@ impl BrowserContext {
id,
storage_partition,
page_targets: PageTargetRegistry::default(),
+ window_is_focused: true,
default_document_cookie_manager_surface: BrowserContextCookieManagerSurface::default(),
target_opener_ids: HashMap::new(),
target_opener_frame_ids: HashMap::new(),
@@ -1630,10 +1633,6 @@ impl BrowserContext {
debug_assert!(selected, "registered page target must be selectable");
}
- pub(crate) fn rekey_active_target(&mut self, target_id: impl Into<String>) -> bool {
- self.page_targets.rekey_active(target_id.into())
- }
-
pub(crate) fn active_session_id(&self) -> Option<&str> {
self.page_targets.active()?.session_id()
}
diff --git a/moli-protocol/src/conn/state/page_target_host.rs b/moli-protocol/src/conn/state/page_target_host.rs
index d7810335a..ac66342ad 100644
--- a/moli-protocol/src/conn/state/page_target_host.rs
+++ b/moli-protocol/src/conn/state/page_target_host.rs
@@ -21,6 +21,7 @@ use crate::conn::cookie_manager_surface::BrowserContextCookieManagerSurface;
#[derive(Debug)]
pub struct PageTargetHost {
target_id: String,
+ pub(crate) window_id: u32,
navigation_engine: Option<NavigationEngine>,
pub(crate) target_identity: TargetIdentityState,
pub(crate) devtools_sessions: DevToolsSessionRegistry,
@@ -45,6 +46,7 @@ impl PageTargetHost {
pub(crate) fn empty(target_id: String) -> Self {
Self {
target_id,
+ window_id: 0,
navigation_engine: None,
target_identity: TargetIdentityState::about_blank(),
devtools_sessions: DevToolsSessionRegistry::default(),
@@ -240,6 +242,8 @@ impl PageTargetHost {
pub(crate) struct PageTargetRegistry {
active_target_id: Option<String>,
hosts: IndexMap<String, PageTargetHost>,
+ selected_tabs: HashMap<u32, String>,
+ next_window_id: u32,
}
impl PageTargetRegistry {
@@ -272,31 +276,102 @@ impl PageTargetRegistry {
self.hosts.get_mut(target_id)
}
- pub(crate) fn insert(&mut self, host: PageTargetHost) -> bool {
+ pub(crate) fn insert(&mut self, mut host: PageTargetHost, window_id: u32) -> bool {
let target_id = host.target_id().to_owned();
if self.hosts.contains_key(&target_id) {
return false;
}
+ host.window_id = window_id;
self.hosts.insert(target_id, host);
true
}
pub(crate) fn remove(&mut self, target_id: &str) -> Option<PageTargetHost> {
+ let window_id = self.get(target_id)?.window_id;
+ if self.is_selected_tab(target_id) {
+ let neighbor = self.adjacent_tab_id(target_id).map(str::to_owned);
+ self.selected_tabs.remove(&window_id);
+ if let Some(neighbor) = neighbor {
+ self.selected_tabs.insert(window_id, neighbor);
+ }
+ }
if self.active_target_id() == Some(target_id) {
self.active_target_id = None;
}
self.hosts.shift_remove(target_id)
}
+ /// Preserve tab-strip order when an active target closes: prefer its right
+ /// neighbor, then the left neighbor at the end of the strip. Compute this
+ /// before removal, while the closing target still identifies its position.
+ pub(crate) fn adjacent_target_id(&self, target_id: &str) -> Option<&str> {
+ self.adjacent_tab_id(target_id).or_else(|| {
+ self.hosts
+ .values()
+ .rev()
+ .find(|host| {
+ host.target_id() != target_id && self.is_selected_tab(host.target_id())
+ })
+ .map(PageTargetHost::target_id)
+ })
+ }
+
+ fn adjacent_tab_id(&self, target_id: &str) -> Option<&str> {
+ let index = self.hosts.get_index_of(target_id)?;
+ let window_id = self.get(target_id)?.window_id;
+ self.hosts
+ .values()
+ .skip(index + 1)
+ .find(|host| host.window_id == window_id)
+ .or_else(|| {
+ self.hosts
+ .values()
+ .take(index)
+ .rev()
+ .find(|host| host.window_id == window_id)
+ })
+ .map(PageTargetHost::target_id)
+ }
+
+ pub(crate) fn is_selected_tab(&self, target_id: &str) -> bool {
+ self.get(target_id).is_some_and(|host| {
+ self.selected_tabs
+ .get(&host.window_id)
+ .is_some_and(|selected| selected == target_id)
+ })
+ }
+
+ pub(crate) fn default_window_id(&mut self) -> u32 {
+ self.active()
+ .or_else(|| self.hosts.values().next())
+ .map(|host| host.window_id)
+ .unwrap_or_else(|| self.allocate_window_id())
+ }
+
+ pub(crate) fn allocate_window_id(&mut self) -> u32 {
+ let id = self.next_window_id;
+ self.next_window_id = id.checked_add(1).expect("window id space exhausted");
+ id
+ }
+
+ pub(crate) fn select_tab(&mut self, target_id: &str) -> bool {
+ let Some(host) = self.get(target_id) else {
+ return false;
+ };
+ self.selected_tabs
+ .insert(host.window_id, target_id.to_owned());
+ true
+ }
+
pub(crate) fn select(&mut self, target_id: &str) -> bool {
- if self.get(target_id).is_none() {
+ if !self.select_tab(target_id) {
return false;
}
self.active_target_id = Some(target_id.to_owned());
true
}
- pub(crate) fn rekey_active(&mut self, target_id: String) -> bool {
+ pub(crate) fn rekey_active(&mut self, target_id: String, window_id: u32) -> bool {
if self.hosts.contains_key(&target_id) {
return false;
}
@@ -308,7 +383,11 @@ impl PageTargetRegistry {
else {
return false;
};
+ self.selected_tabs.remove(&active.window_id);
+ active.window_id = window_id;
active.replace_target_id(target_id.clone());
+ self.selected_tabs
+ .insert(active.window_id, target_id.clone());
self.hosts.shift_insert(index, target_id.clone(), active);
self.active_target_id = Some(target_id);
true
@@ -344,3 +423,22 @@ impl PageTargetRegistry {
self.background().next().is_none()
}
}
+
+#[cfg(test)]
+mod window_tests {
+ use super::*;
+
+ #[test]
+ fn reopening_after_the_last_tab_closes_uses_a_new_window_identity() {
+ let mut targets = PageTargetRegistry::default();
+ let window_id = targets.default_window_id();
+ targets.insert(PageTargetHost::empty("first".into()), window_id);
+ targets.select("first");
+ let first_window = targets.remove("first").unwrap().window_id;
+ let window_id = targets.default_window_id();
+ targets.insert(PageTargetHost::empty("second".into()), window_id);
+ targets.select("second");
+ assert_ne!(targets.get("second").unwrap().window_id, first_window);
+ assert!(targets.is_selected_tab("second"));
+ }
+}
diff --git a/moli-protocol/src/conn/target/activation.rs b/moli-protocol/src/conn/target/activation.rs
index 6a72d417b..b41a32cf3 100644
--- a/moli-protocol/src/conn/target/activation.rs
+++ b/moli-protocol/src/conn/target/activation.rs
@@ -56,15 +56,116 @@ impl CompletedTargetActivation {
}
impl CdpConnection {
+ fn target_document_is_visible(&self, target_id: &str) -> bool {
+ self.browser_context
+ .iter()
+ .chain(self.inactive_browser_contexts.iter())
+ .find_map(|context| context.document_activity_for_target(target_id))
+ .is_some_and(|activity| activity.visible)
+ }
+ pub(crate) fn select_browser_focus_for_target(&mut self, target_id: &str) {
+ let Some(browser_context_id) = self
+ .target_session_route_for_target_id(target_id)
+ .and_then(|route| route.browser_context_id().map(str::to_owned))
+ else {
+ return;
+ };
+ for context in self
+ .browser_context
+ .iter_mut()
+ .chain(self.inactive_browser_contexts.iter_mut())
+ {
+ context.window_is_focused = context.id == browser_context_id;
+ }
+ }
+
+ pub(crate) async fn apply_browser_document_activity_async(&mut self) -> anyhow::Result<()> {
+ let completion_sender = self
+ .scheduler_hooks
+ .document_activity_completion_sender
+ .clone();
+ for context in self
+ .browser_context
+ .iter_mut()
+ .chain(self.inactive_browser_contexts.iter_mut())
+ {
+ let activities = context
+ .page_targets
+ .iter()
+ .filter(|target| !target.has_pending_javascript_dialog())
+ .map(|target| {
+ (
+ target.target_id().to_owned(),
+ context
+ .document_activity_for_target(target.target_id())
+ .unwrap(),
+ )
+ })
+ .collect::<Vec<_>>();
+ for (target_id, activity) in activities {
+ if let Some(page) = context
+ .page_target_mut(&target_id)
+ .and_then(|host| host.runtime_slot.loaded_page_mut())
+ && page.document_activity() != activity
+ {
+ if let Some(sender) = completion_sender.clone() {
+ let pending = page.start_set_document_activity(activity)?;
+ // The browser selection is complete. Each renderer
+ // consumes its own FIFO update independently of CDP.
+ tokio::task::spawn_local(async move {
+ let _ = sender.send(super::super::CompletedDocumentActivityUpdate {
+ completion: pending
+ .wait()
+ .await
+ .and_then(|completion| completion.into_unit_page_command_turn())
+ .map(Box::new),
+ });
+ });
+ } else {
+ // Protocol-only fixtures have no external completion
+ // driver and consume their owner turn inline.
+ page.set_document_activity_async(activity).await?;
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+
+ pub(crate) async fn restore_browser_focus_after_removal_async(&mut self) {
+ if !self
+ .browser_context
+ .iter()
+ .chain(self.inactive_browser_contexts.iter())
+ .any(|context| context.window_is_focused && context.active_target_id().is_some())
+ && let Some(target_id) = self
+ .browser_context
+ .iter()
+ .chain(self.inactive_browser_contexts.iter())
+ .find_map(BrowserContext::active_target_id_owned)
+ {
+ self.select_browser_focus_for_target(&target_id);
+ }
+ if let Err(error) = self.apply_browser_document_activity_async().await {
+ tracing::warn!(%error, "failed to update document activity after target removal");
+ }
+ }
+
/// Completes the renderer-surface half of a foreground transition that was
/// staged synchronously while creating a new target.
pub(crate) async fn complete_staged_target_activation_async(
&mut self,
transition: &TargetActivationTransition,
) -> CompletedTargetActivation {
+ if let Err(error) = self.apply_browser_document_activity_async().await {
+ tracing::warn!(%error, "failed to update document activity after target creation");
+ }
let Some(previous_target_id) = transition.deactivated_target_id() else {
return CompletedTargetActivation::new(Vec::new());
};
+ if self.target_document_is_visible(previous_target_id) {
+ return CompletedTargetActivation::new(Vec::new());
+ }
let protocol_events = self
.page_screencast_session_ids_for_target(previous_target_id)
.into_iter()
@@ -93,6 +194,8 @@ impl CdpConnection {
&mut self,
target_id: &str,
) -> anyhow::Result<Option<CompletedTargetActivation>> {
+ self.select_browser_focus_for_target(target_id);
+ let was_visible = self.target_document_is_visible(target_id);
let previous_active_target_id = self
.browser_context
.as_ref()
@@ -111,28 +214,36 @@ impl CdpConnection {
}
self.refresh_active_browser_context_loader_async().await;
self.notify_target_host_activated(target_id);
+ self.apply_browser_document_activity_async().await?;
let mut protocol_events = Vec::new();
if transition.changed_active_target() {
// Chromium's PageHandler reports RenderWidgetHost visibility only
// while that attachment has an active screencast. Hide the old
// surface before exposing the selected one.
- protocol_events.extend(hidden_screencast_sessions.into_iter().map(|session_id| {
- BackgroundProtocolEvent::page_screencast_visibility_changed(
- session_id.as_deref(),
- false,
- )
- }));
- protocol_events.extend(
- self.page_screencast_session_ids_for_target(target_id)
- .into_iter()
- .map(|session_id| {
- BackgroundProtocolEvent::page_screencast_visibility_changed(
- session_id.as_deref(),
- true,
- )
- }),
- );
+ if transition
+ .deactivated_target_id()
+ .is_some_and(|previous| !self.target_document_is_visible(previous))
+ {
+ protocol_events.extend(hidden_screencast_sessions.into_iter().map(|session_id| {
+ BackgroundProtocolEvent::page_screencast_visibility_changed(
+ session_id.as_deref(),
+ false,
+ )
+ }));
+ }
+ if !was_visible {
+ protocol_events.extend(
+ self.page_screencast_session_ids_for_target(target_id)
+ .into_iter()
+ .map(|session_id| {
+ BackgroundProtocolEvent::page_screencast_visibility_changed(
+ session_id.as_deref(),
+ true,
+ )
+ }),
+ );
+ }
}
Ok(Some(CompletedTargetActivation::new(protocol_events)))
}
diff --git a/moli-protocol/src/conn/target/route.rs b/moli-protocol/src/conn/target/route.rs
index 3c70bc756..1f6c1e27f 100644
--- a/moli-protocol/src/conn/target/route.rs
+++ b/moli-protocol/src/conn/target/route.rs
@@ -98,7 +98,8 @@ impl CdpSessionRoute {
/// 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 {
+ pub(crate) fn supports_cdp_method(&self, method: &str) -> bool {
+ let domain = method.split('.').next().unwrap_or_default();
match self {
Self::Browser => matches!(
domain,
@@ -112,7 +113,10 @@ impl CdpSessionRoute {
| "Tracing"
),
Self::BrowserContext { .. } | Self::PageTarget { .. } => true,
- Self::TabTarget { .. } => matches!(domain, "IO" | "Target" | "Tracing"),
+ Self::TabTarget { .. } => {
+ matches!(domain, "IO" | "Target" | "Tracing")
+ || method == "Runtime.runIfWaitingForDebugger"
+ }
Self::SharedWorkerTarget { .. }
| Self::DedicatedWorkerTarget { .. }
| Self::ServiceWorkerTarget { .. } => true,
diff --git a/moli-protocol/src/domains/browser.rs b/moli-protocol/src/domains/browser.rs
index 8d35a8936..504b5237f 100644
--- a/moli-protocol/src/domains/browser.rs
+++ b/moli-protocol/src/domains/browser.rs
@@ -158,7 +158,7 @@ pub(crate) fn try_start_browser_command_dispatch(
match action {
BrowserAction::GetVersion => BrowserCommandTaskStep::Complete(get_version(conn)),
BrowserAction::GetWindowForTarget => {
- BrowserCommandTaskStep::Complete(get_window_for_target(conn))
+ BrowserCommandTaskStep::Complete(get_window_for_target(conn, cmd))
}
BrowserAction::SetWindowBounds => {
BrowserCommandTaskStep::Complete(set_window_bounds(conn, cmd))
@@ -208,10 +208,51 @@ fn bounds_json(bounds: &BrowserWindowBounds) -> Value {
value
}
-fn get_window_for_target(conn: &CdpConnection) -> CommandOutputPlan {
+fn get_window_for_target(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> CommandOutputPlan {
+ #[derive(Default, Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct Params {
+ target_id: Option<String>,
+ }
+ let params: Params = match cmd.get_params() {
+ Ok(params) => params.unwrap_or_default(),
+ Err(_) => return CommandOutputPlan::error(-32602, "InvalidParams"),
+ };
+ let target_id = params
+ .target_id
+ .or_else(|| {
+ conn.target_owner_identity_for_session(cmd.session_id)
+ .and_then(|(_, id)| id)
+ })
+ .unwrap_or_else(|| conn.default_target_id().to_owned());
+ let page_target_id = conn
+ .primary_page_target_id_for_tab_target_id(&target_id)
+ .unwrap_or(&target_id);
+ let key = if conn.default_placeholder_is_logically_active(page_target_id) {
+ (conn.default_browser_context_id().to_owned(), 0)
+ } else if let Some((context, target)) = conn
+ .browser_context
+ .iter()
+ .chain(conn.inactive_browser_contexts.iter())
+ .find_map(|context| {
+ context
+ .page_target(page_target_id)
+ .map(|target| (context, target))
+ })
+ {
+ (context.id.clone(), target.window_id)
+ } else {
+ return CommandOutputPlan::error(-32000, "No browser window found");
+ };
+ let next_id = DEV_TOOLS_WINDOW_ID + conn.browser_window_ids.len() as u32;
+ let window_id = *conn.browser_window_ids.entry(key).or_insert(next_id);
+ let bounds = conn
+ .browser_window_bounds
+ .entry(window_id)
+ .or_insert_with(|| conn.window_bounds.clone());
CommandOutputPlan::result(json!({
- "windowId": DEV_TOOLS_WINDOW_ID,
- "bounds": bounds_json(&conn.window_bounds)
+ "windowId": window_id,
+ "bounds": bounds_json(bounds)
}))
}
@@ -273,9 +314,32 @@ fn set_window_bounds(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> CommandOutputPl
}
};
- if *params.window_id.inner() != i64::from(DEV_TOOLS_WINDOW_ID) {
+ let Ok(window_id) = u32::try_from(*params.window_id.inner()) else {
return CommandOutputPlan::error(-32602, "InvalidParams");
+ };
+ let window_is_live = conn
+ .browser_window_ids
+ .iter()
+ .any(|((context_id, local_id), id)| {
+ *id == window_id
+ && (conn
+ .browser_context_by_id(context_id)
+ .is_some_and(|context| {
+ context
+ .page_targets
+ .iter()
+ .any(|target| target.window_id == *local_id)
+ })
+ || (*local_id == 0
+ && context_id == conn.default_browser_context_id()
+ && conn.default_placeholder_is_logically_active(conn.default_target_id())))
+ });
+ if !window_is_live {
+ return CommandOutputPlan::error(-32000, "Browser window not found");
}
+ let Some(window_bounds) = conn.browser_window_bounds.get_mut(&window_id) else {
+ return CommandOutputPlan::error(-32602, "InvalidParams");
+ };
let left = match optional_i64_to_i32(params.bounds.left) {
Ok(left) => left,
@@ -301,12 +365,12 @@ fn set_window_bounds(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> CommandOutputPl
return CommandOutputPlan::error(-32602, "InvalidParams");
}
};
- conn.window_bounds.left = left;
- conn.window_bounds.top = top;
- conn.window_bounds.width = width;
- conn.window_bounds.height = height;
+ window_bounds.left = left;
+ window_bounds.top = top;
+ window_bounds.width = width;
+ window_bounds.height = height;
if let Some(window_state) = params.bounds.window_state {
- conn.window_bounds.window_state = window_state.as_ref().to_owned();
+ window_bounds.window_state = window_state.as_ref().to_owned();
}
CommandOutputPlan::success()
diff --git a/moli-protocol/src/domains/emulation/tests/native_navigator.rs b/moli-protocol/src/domains/emulation/tests/native_navigator.rs
index dc363d271..94e043384 100644
--- a/moli-protocol/src/domains/emulation/tests/native_navigator.rs
+++ b/moli-protocol/src/domains/emulation/tests/native_navigator.rs
@@ -321,7 +321,7 @@ async fn focus_override_dispatches_native_visibility_and_focus_events() {
.await;
assert_eq!(
evaluate(&mut ctx, "blurArrived.then(() => surfaceEvents.slice(2))").await,
- json!([["visibilitychange", true, true], ["blur", true, true]])
+ json!([["blur", true, true], ["visibilitychange", true, true]])
);
}
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index a0a88436b..2052d4025 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -644,6 +644,10 @@ async fn bring_session_route_to_front_async(
.and_then(|bc| bc.active_target_identity())
.is_some_and(|(active_target_id, _)| active_target_id == target_id);
if target_is_active {
+ conn.select_browser_focus_for_target(&target_id);
+ conn.apply_browser_document_activity_async()
+ .await
+ .map_err(|error| error.to_string())?;
return Ok(Vec::new());
}
diff --git a/moli-protocol/src/domains/page/navigation.rs b/moli-protocol/src/domains/page/navigation.rs
index 74add1f8f..5b5e96ca3 100644
--- a/moli-protocol/src/domains/page/navigation.rs
+++ b/moli-protocol/src/domains/page/navigation.rs
@@ -3543,6 +3543,9 @@ pub(crate) async fn emit_same_document_navigation_background_events_async(
);
continue;
}
+ crate::domains::target::emit_target_info_changed_for_owner_background_event(
+ conn, out, owner,
+ );
emit_same_document_navigation_background_event(
conn,
out,
diff --git a/moli-protocol/src/domains/page/producer_tests.rs b/moli-protocol/src/domains/page/producer_tests.rs
index 0889371dc..430cc00aa 100644
--- a/moli-protocol/src/domains/page/producer_tests.rs
+++ b/moli-protocol/src/domains/page/producer_tests.rs
@@ -214,6 +214,66 @@ fn protocol_messages_from_background_events(events: Vec<BackgroundProtocolEvent>
.collect()
}
+#[test]
+fn background_document_title_uses_its_frozen_page_residence() {
+ let mut conn = CdpConnection::default();
+ let mut bc = BrowserContext::new("BID-title-source".into());
+ bc.set_active_target_id("TID-background");
+ bc.attach_active_session("SID-background");
+ bc.stage_foreground_target(
+ "TID-foreground".into(),
+ Some("SID-foreground".into()),
+ "about:blank".into(),
+ None,
+ );
+ conn.install_browser_context_fixture_for_test(bc);
+ let background_document = renderer_document_identity_for_test(1, 1);
+ bind_renderer_document_for_test(
+ &mut conn,
+ "SID-background",
+ "TID-background",
+ background_document,
+ );
+ bind_renderer_document_for_test(
+ &mut conn,
+ "SID-foreground",
+ "TID-foreground",
+ renderer_document_identity_for_test(2, 2),
+ );
+ let owner = CommandOwnerScope::for_route(crate::conn::CdpSessionRoute::PageTarget {
+ browser_context_id: "BID-title-source".into(),
+ target_id: "TID-background".into(),
+ session_key: moli_page_types::DevToolsSessionKey::Primary,
+ });
+ let title = RendererDocumentTitleChanged {
+ source_document: background_document,
+ title: "background title".into(),
+ };
+ assert_eq!(
+ conn.apply_renderer_document_title_for_owner(&owner, &title),
+ Some(true)
+ );
+ assert_eq!(
+ conn.browser_context
+ .as_ref()
+ .unwrap()
+ .target_info("TID-background")
+ .unwrap()["title"],
+ json!("background title"),
+ );
+ bind_renderer_document_for_test(
+ &mut conn,
+ "SID-background",
+ "TID-background",
+ renderer_document_identity_for_test(3, 3),
+ );
+ assert_eq!(
+ conn.apply_renderer_document_title_for_owner(&owner, &title),
+ None,
+ "replacing the background Document still revokes its old title authority"
+ );
+}
+
#[test]
fn stale_document_title_cannot_overwrite_replacement_target_metadata() {
let mut conn = CdpConnection::default();
diff --git a/moli-protocol/src/domains/runtime/dispatcher/runtime_lifecycle.rs b/moli-protocol/src/domains/runtime/dispatcher/runtime_lifecycle.rs
index 7816c2295..dbcafc196 100644
--- a/moli-protocol/src/domains/runtime/dispatcher/runtime_lifecycle.rs
+++ b/moli-protocol/src/domains/runtime/dispatcher/runtime_lifecycle.rs
@@ -55,6 +55,23 @@ pub(super) fn start_runtime_run_if_waiting_for_debugger_command(
conn: &mut CdpConnection,
cmd: &Cmd<'_>,
) -> RuntimeCommandTaskStep {
+ if let Some(crate::conn::CdpSessionRoute::TabTarget { tab_target_id, .. }) =
+ conn.session_route(cmd.session_id)
+ {
+ // A Tab has a browser-side debugger barrier, but no V8 context. Resume
+ // only this attachment; never dispatch the command to an active Page.
+ let page_target_id = conn
+ .primary_page_target_id_for_tab_target_id(&tab_target_id)
+ .map(str::to_owned);
+ if conn.release_waiting_for_debugger_session(cmd.session_id)
+ && let Some(page_target_id) = page_target_id
+ {
+ crate::domains::target::schedule_initial_document_target_url_navigation_after_debugger_barrier_release_for_target(
+ conn, &page_target_id,
+ );
+ }
+ return RuntimeCommandTaskStep::Complete(CommandOutputPlan::success());
+ }
if !conn
.runtime_session_owner_slot(cmd.session_id)
.is_ok_and(|slot| slot.has_loaded_page())
diff --git a/moli-protocol/src/domains/target/activation.rs b/moli-protocol/src/domains/target/activation.rs
index 07082184e..16ca47428 100644
--- a/moli-protocol/src/domains/target/activation.rs
+++ b/moli-protocol/src/domains/target/activation.rs
@@ -165,6 +165,10 @@ pub(super) async fn execute_devtools_activate_target_command_async(
Vec::new()
};
+ conn.select_browser_focus_for_target(&target_id);
+ if let Err(error) = conn.apply_browser_document_activity_async().await {
+ tracing::warn!(%error, "failed to update document activity after activation");
+ }
restore_previously_active_browser_context(
conn,
previously_active_browser_context_id.as_deref(),
diff --git a/moli-protocol/src/domains/target/browser_context_disposal.rs b/moli-protocol/src/domains/target/browser_context_disposal.rs
index 6613ab58d..05de683cb 100644
--- a/moli-protocol/src/domains/target/browser_context_disposal.rs
+++ b/moli-protocol/src/domains/target/browser_context_disposal.rs
@@ -178,6 +178,7 @@ pub(super) async fn execute_browser_context_disposal_async(
if let Some(mut removed) = removed {
removed.close_all_pages_async().await;
}
+ conn.restore_browser_focus_after_removal_async().await;
conn.release_idle_navigation_engine_memory_after_target_close();
Ok(())
}
diff --git a/moli-protocol/src/domains/target/creation.rs b/moli-protocol/src/domains/target/creation.rs
index b96f71541..3acfd5e40 100644
--- a/moli-protocol/src/domains/target/creation.rs
+++ b/moli-protocol/src/domains/target/creation.rs
@@ -112,6 +112,7 @@ pub(super) struct CreateTargetParams {
pub(super) for_tab: Option<bool>,
pub(super) background: Option<bool>,
pub(super) focus: Option<bool>,
+ pub(super) new_window: Option<bool>,
}
fn default_blank() -> String {
@@ -142,6 +143,7 @@ pub(super) fn start_create_target_command(
for_tab: None,
background: None,
focus: None,
+ new_window: None,
},
Err(e) => {
return super::target_command_error(-32602, e);
@@ -152,6 +154,7 @@ pub(super) fn start_create_target_command(
} else {
CreateTargetResultHost::Page
};
+ let new_window = params.new_window.unwrap_or(false);
let command = match build_cdp_create_target_command(cmd, params) {
Ok(command) => command,
Err(message) => return super::target_command_error(-32602, message),
@@ -162,6 +165,7 @@ pub(super) fn start_create_target_command(
cmd.session_id,
command,
result_host,
+ new_window,
)
}
@@ -202,6 +206,7 @@ pub(super) fn start_devtools_create_target_command(
command_session_id,
command,
CreateTargetResultHost::Page,
+ false,
)
}
@@ -211,9 +216,10 @@ fn start_devtools_create_target_command_with_result_host(
command_session_id: Option<&str>,
command: DevToolsCreateTargetCommand,
result_host: CreateTargetResultHost,
+ new_window: bool,
) -> TargetCommandTaskStep {
let mut plan = CommandOutputPlan::default();
- let execution = execute_devtools_create_target_command(conn, command);
+ let execution = execute_devtools_create_target_command_in_window(conn, command, new_window);
let (created_target_id, creation_commit) = match execution {
Ok(execution) => {
let target_id = execution.result.target_id.clone();
@@ -278,6 +284,14 @@ fn start_devtools_create_target_command_with_result_host(
pub(super) fn execute_devtools_create_target_command(
conn: &mut CdpConnection,
command: DevToolsCreateTargetCommand,
+) -> Result<DevToolsCreateTargetExecution, DevToolsError> {
+ execute_devtools_create_target_command_in_window(conn, command, false)
+}
+
+fn execute_devtools_create_target_command_in_window(
+ conn: &mut CdpConnection,
+ command: DevToolsCreateTargetCommand,
+ new_window: bool,
) -> Result<DevToolsCreateTargetExecution, DevToolsError> {
let restore_browser_context_id = previously_active_browser_context_id(conn);
if let Err(error) = activate_browser_context_for_create_target(conn, &command) {
@@ -327,32 +341,19 @@ pub(super) fn execute_devtools_create_target_command(
None
};
let activating_created_target = has_active_target && command.activate;
- let activation = activating_created_target
- .then(|| TargetActivationTransition::new(target_id.clone(), previous_active_target_id));
+ let activation = command.activate.then(|| {
+ TargetActivationTransition::new(target_id.clone(), previous_active_target_id.clone())
+ });
let initial_empty_document_url = create_target_initial_empty_document_url(&command.url);
{
let bc = conn.browser_context.as_mut().unwrap();
- if creating_background_target {
- bc.stage_background_target(
- target_id.clone(),
- auto_attached_background_session_id.clone(),
- command.url.clone(),
- Some(initial_empty_document_url.clone()),
- None,
- );
- } else if activating_created_target {
- bc.stage_foreground_target(
- target_id.clone(),
- None,
- command.url.clone(),
- Some(initial_empty_document_url.clone()),
- );
+ let window_id = if new_window {
+ bc.page_targets.allocate_window_id()
} else {
- let claimed_default_placeholder =
- claims_default_placeholder && bc.rekey_active_target(target_id.clone());
- if !claimed_default_placeholder {
- bc.set_active_target_id(target_id.clone());
- }
+ bc.page_targets.default_window_id()
+ };
+ if claims_default_placeholder && bc.page_targets.rekey_active(target_id.clone(), window_id)
+ {
bc.set_target_url(command.url.clone());
bc.begin_active_target_initial_empty_document(initial_empty_document_url.clone());
bc.page_target_mut(&target_id)
@@ -360,6 +361,24 @@ pub(super) fn execute_devtools_create_target_command(
.owner_state
.target_crash_state
.clear();
+ } else {
+ bc.stage_background_target_in_window(
+ target_id.clone(),
+ auto_attached_background_session_id.clone(),
+ command.url.clone(),
+ Some(initial_empty_document_url.clone()),
+ None,
+ window_id,
+ );
+ if !creating_background_target {
+ bc.set_active_target_id(target_id.clone());
+ }
+ }
+ if new_window && creating_background_target {
+ // Select the first tab without changing browser focus for a
+ // background window.
+ let selected = bc.page_targets.select_tab(&target_id);
+ debug_assert!(selected, "new window target must be registered");
}
if command.url != initial_empty_document_url {
// Chromium gives Target.createTarget(url) one initial
@@ -370,6 +389,15 @@ pub(super) fn execute_devtools_create_target_command(
}
}
let tab_target_id = conn.register_top_level_page_target(&target_id);
+ if command.activate {
+ conn.select_browser_focus_for_target(&target_id);
+ } else if !has_active_target {
+ let another_window_exists = conn
+ .inactive_browser_contexts
+ .iter()
+ .any(|context| !context.page_targets.is_empty());
+ conn.browser_context.as_mut().unwrap().window_is_focused = !another_window_exists;
+ }
if !creating_background_target {
conn.notify_target_host_activated(&target_id);
}
diff --git a/moli-protocol/src/domains/target/popup.rs b/moli-protocol/src/domains/target/popup.rs
index d13082961..c8350cc11 100644
--- a/moli-protocol/src/domains/target/popup.rs
+++ b/moli-protocol/src/domains/target/popup.rs
@@ -644,6 +644,10 @@ async fn activate_popup_target_async(
.as_ref()
.is_some_and(|browser_context| browser_context.is_active_target(target_id))
{
+ conn.select_browser_focus_for_target(target_id);
+ conn.apply_browser_document_activity_async()
+ .await
+ .map_err(|error| error.to_string())?;
Ok(Vec::new())
} else {
match conn
diff --git a/moli-protocol/src/domains/target/protocol_neutral_tests.rs b/moli-protocol/src/domains/target/protocol_neutral_tests.rs
index c768a0b34..3b718f392 100644
--- a/moli-protocol/src/domains/target/protocol_neutral_tests.rs
+++ b/moli-protocol/src/domains/target/protocol_neutral_tests.rs
@@ -26,6 +26,7 @@ fn cdp_create_target_builds_protocol_neutral_target_command() {
for_tab: None,
background: None,
focus: None,
+ new_window: None,
},
)
.expect("valid target disposition");
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.rs
index 40af0524d..a41f6c3fd 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
@@ -1,5 +1,49 @@
use super::*;
+#[tokio::test(flavor = "multi_thread")]
+async fn closing_active_target_selects_adjacent_tab_in_creation_order() {
+ // Chromium TabStripModel::DetermineNewSelectedIndex prefers the next tab
+ // to the right, or the left neighbor when closing the last unrelated tab.
+ for (closing_index, selected_index) in [(0, 1), (1, 2), (2, 1)] {
+ let mut ctx = TestContext::new();
+ load_bc_with_target(&mut ctx, "BID-close-order", "TID-first");
+ let mut targets = vec!["TID-first".to_owned()];
+ for id in [10, 11] {
+ ctx.process_async(json!({
+ "id": id,
+ "method": "Target.createTarget",
+ "params": {
+ "browserContextId": "BID-close-order",
+ "url": format!("about:blank#{id}")
+ }
+ }))
+ .await;
+ targets.push(take_created_target_id(&mut ctx, id));
+ ctx.take_all();
+ }
+ ctx.process_async(json!({
+ "id": 12,
+ "method": "Target.activateTarget",
+ "params": {"targetId": targets[closing_index]}
+ }))
+ .await;
+ ctx.take_all();
+ ctx.process_async(json!({
+ "id": 13,
+ "method": "Target.closeTarget",
+ "params": {"targetId": targets[closing_index]}
+ }))
+ .await;
+ assert_eq!(take_response_by_id(&mut ctx, 13)["result"]["success"], true);
+ let context = ctx.conn.browser_context.as_ref().unwrap();
+ assert_eq!(
+ context.active_target_id(),
+ Some(targets[selected_index].as_str())
+ );
+ assert!(context.page_target(&targets[closing_index]).is_none());
+ }
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn activate_target_activates_auto_attached_background_session_into_page_runtime() {
let mut ctx = TestContext::new();
diff --git a/moli-protocol/src/domains/target/tests/tests_target_creation.rs b/moli-protocol/src/domains/target/tests/tests_target_creation.rs
index a7cb631dc..106028f39 100644
--- a/moli-protocol/src/domains/target/tests/tests_target_creation.rs
+++ b/moli-protocol/src/domains/target/tests/tests_target_creation.rs
@@ -3019,6 +3019,32 @@ async fn tab_session_auto_attach_catchall_attaches_child_page() {
ctx.conn.session_route(Some(page_session_id)),
Some(crate::conn::CdpSessionRoute::PageTarget { .. })
));
+ assert!(
+ ctx.conn
+ .target_has_waiting_for_debugger_session(&tab_target_id)
+ );
+ for id in [19_034, 19_035] {
+ ctx.process_async(json!({
+ "id": id, "sessionId": tab_session_id,
+ "method": "Runtime.runIfWaitingForDebugger"
+ }))
+ .await;
+ ctx.expect_result(id, json!({}), Some(&tab_session_id));
+ }
+ assert!(
+ !ctx.conn
+ .target_has_waiting_for_debugger_session(&tab_target_id)
+ );
+ ctx.process_async(json!({
+ "id": 19_036, "sessionId": tab_session_id, "method": "Runtime.enable"
+ }))
+ .await;
+ let unsupported = take_response_by_id(&mut ctx, 19_036);
+ assert_eq!(
+ unsupported["error"]["code"],
+ json!(-32601),
+ "the browser-side resume handler must not expose a Page Runtime on the Tab"
+ );
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/moli-renderer-v8/src/devtools/ingress/main.rs b/moli-renderer-v8/src/devtools/ingress/main.rs
index 445be50a9..1514c0366 100644
--- a/moli-renderer-v8/src/devtools/ingress/main.rs
+++ b/moli-renderer-v8/src/devtools/ingress/main.rs
@@ -781,6 +781,7 @@ mod tests {
navigation_redirect_chain: Vec::new(),
final_url: url,
document_title: String::new(),
+ document_activity: Default::default(),
status: 200,
headers: Vec::new(),
script_execution: Arc::new(ScriptExecutionReport::default()),
diff --git a/moli-renderer-v8/src/native_bridge/context_host/rendering_updates.rs b/moli-renderer-v8/src/native_bridge/context_host/rendering_updates.rs
index 69a1fcf23..6a64f88b9 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/rendering_updates.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/rendering_updates.rs
@@ -404,64 +404,85 @@ impl JsContextHost {
return dispatched;
}
}
- if change.previous_activity != current_activity {
- if change.previous_activity.visible != current_activity.visible
- && let Ok(document) = crate::host::event_target_value(
+ // Losing focus precedes hiding; showing precedes gaining focus.
+ // Install each intermediate state before its event so callbacks
+ // observe that transition, including callbacks in child Documents.
+ let previous = change.previous_activity;
+ let transitions = [
+ (previous.focused && !current_activity.focused).then_some((
+ "blur",
+ moli_page_types::DocumentActivity {
+ focused: false,
+ visible: previous.visible,
+ },
+ )),
+ (previous.visible != current_activity.visible).then_some((
+ "visibilitychange",
+ moli_page_types::DocumentActivity {
+ focused: previous.focused && current_activity.focused,
+ visible: current_activity.visible,
+ },
+ )),
+ (!previous.focused && current_activity.focused)
+ .then_some(("focus", current_activity)),
+ ];
+ for (event_type, activity) in transitions.into_iter().flatten() {
+ if !self.window_document_owner_is_current_for_dispatch_scope(
+ target.owner(),
+ target.dispatch_scope(),
+ ) {
+ return dispatched;
+ }
+ self.set_document_activity(activity);
+ let (event_target, event) = if event_type == "visibilitychange" {
+ let Ok(document) = crate::host::event_target_value(
context_scope,
host_ptr,
EventTargetHandle::Node(resolved.document_handle),
+ ) else {
+ continue;
+ };
+ (
+ EventTargetHandle::Node(resolved.document_handle),
+ crate::host::create_host_event(
+ context_scope,
+ event_type,
+ document,
+ document,
+ true,
+ false,
+ )
+ .ok(),
)
- && let Ok(event) = crate::host::create_host_event(
- context_scope,
- "visibilitychange",
- document,
- document,
- true,
- false,
+ } else {
+ (
+ window_target,
+ super::super::element::construct_focus_event(
+ context_scope,
+ event_type,
+ None,
+ false,
+ ),
)
- {
+ };
+ if let Some(event) = event {
dispatched |= self
.dispatch_public_event_best_effort(
context_scope,
host_ptr,
- EventTargetHandle::Node(resolved.document_handle),
+ event_target,
event,
- "document visibilitychange event",
+ "document activity event",
)
.is_ok();
}
- if !self.window_document_owner_is_current_for_dispatch_scope(
- target.owner(),
- target.dispatch_scope(),
- ) {
- return dispatched;
- }
- if change.previous_activity.focused != current_activity.focused {
- let event_type = if current_activity.focused {
- "focus"
- } else {
- "blur"
- };
- if let Some(event) = super::super::element::construct_focus_event(
- context_scope,
- event_type,
- None,
- false,
- ) {
- dispatched |= self
- .dispatch_public_event_best_effort(
- context_scope,
- host_ptr,
- window_target,
- event,
- "window focus state event",
- )
- .is_ok();
- }
- }
}
+
dispatched
})();
+ // A listener can retire its Document midway through the transition.
+ // The browser's requested final activity still belongs to the Page.
+ self.set_document_activity(current_activity);
target
.dispatch_scope()
.restore(context_scope, previous_scope);
diff --git a/moli-renderer-v8/src/runtime/page.rs b/moli-renderer-v8/src/runtime/page.rs
index a808982ae..24940a638 100644
--- a/moli-renderer-v8/src/runtime/page.rs
+++ b/moli-renderer-v8/src/runtime/page.rs
@@ -46,6 +46,7 @@ pub struct RendererDocumentOptions {
pub(crate) struct PageVmStateCapture {
pub(crate) final_url: Url,
pub(crate) document_title: String,
+ pub(crate) document_activity: moli_page_types::DocumentActivity,
pub(crate) report: Arc<ScriptExecutionReport>,
pub(crate) navigation_response: Option<PageVmNavigationResponse>,
pub(crate) idle_override: Option<crate::protocol_types::EmulatedIdleOverride>,
diff --git a/moli-renderer-v8/src/runtime/page_state.rs b/moli-renderer-v8/src/runtime/page_state.rs
index 2c79e63a9..1f8d8750d 100644
--- a/moli-renderer-v8/src/runtime/page_state.rs
+++ b/moli-renderer-v8/src/runtime/page_state.rs
@@ -16,6 +16,7 @@ pub struct RendererPageState {
pub navigation_redirect_chain: Vec<crate::protocol_types::NavigationRedirect>,
pub final_url: Url,
pub document_title: String,
+ pub document_activity: moli_page_types::DocumentActivity,
pub status: u16,
pub headers: Vec<(String, Vec<u8>)>,
pub script_execution: Arc<ScriptExecutionReport>,
@@ -53,6 +54,7 @@ impl RendererPageState {
navigation_redirect_chain,
final_url: state_capture.final_url,
document_title: state_capture.document_title,
+ document_activity: state_capture.document_activity,
status,
headers,
script_execution: state_capture.report,
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index 941f86ca7..42fdb7721 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -6147,6 +6147,7 @@ impl RendererPageTable {
navigation_redirect_chain: Vec::new(),
final_url,
document_title,
+ document_activity: Default::default(),
status,
headers: Vec::new(),
script_execution: Arc::new(ScriptExecutionReport::default()),
diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs
index d54b1e395..4cf290100 100644
--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs
@@ -4010,6 +4010,7 @@ impl PageVm {
Ok(PageVmStateCapture {
final_url,
document_title,
+ document_activity: self.document_settings.document_activity,
report,
navigation_response: self.navigation_response.clone(),
idle_override: self.document_settings.idle_override,
diff --git a/moli-renderer-v8/src/script_vm/tests/rendering_update.rs b/moli-renderer-v8/src/script_vm/tests/rendering_update.rs
index 6755f70c9..1dda6964e 100644
--- a/moli-renderer-v8/src/script_vm/tests/rendering_update.rs
+++ b/moli-renderer-v8/src/script_vm/tests/rendering_update.rs
@@ -553,3 +553,74 @@ async fn environment_media_and_visibility_changes_reach_existing_child_documents
"dark:true|hidden:true"
);
}
+
+#[tokio::test(flavor = "current_thread")]
+async fn activity_events_observe_each_focus_and_visibility_transition() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ let mut vm = new_storage_page_task_executor_test_vm("https://activity-events.test/");
+ vm.eval(r#"
+ globalThis.events=[];
+ const record=event=>events.push([event.type,document.visibilityState,document.hasFocus()].join(':'));
+ addEventListener('focus',record);addEventListener('blur',record);
+ document.addEventListener('visibilitychange',record);
+ 'ready'
+ "#).unwrap();
+ vm.set_document_activity(moli_page_types::DocumentActivity::new(false, false))
+ .unwrap();
+ assert!(
+ vm.run_one_rendering_update_executor_turn(&loader)
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ vm.eval("events.join('|')").unwrap(),
+ "blur:visible:false|visibilitychange:hidden:false"
+ );
+ vm.set_document_activity(moli_page_types::DocumentActivity::new(true, true))
+ .unwrap();
+ assert!(
+ vm.run_one_rendering_update_executor_turn(&loader)
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ vm.eval("events.join('|')").unwrap(),
+ "blur:visible:false|visibilitychange:hidden:false|visibilitychange:visible:false|focus:visible:true"
+ );
+ assert_eq!(
+ vm.eval("[document.visibilityState,document.hasFocus()].join(':')")
+ .unwrap(),
+ "visible:true"
+ );
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn activity_blur_document_replacement_skips_old_visibility_and_keeps_final_state() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ let mut vm = new_storage_page_task_executor_test_vm("https://activity-replacement.test/");
+ vm.eval(
+ r#"
+ globalThis.events=[];
+ addEventListener('blur',()=>{
+ events.push('blur:'+document.visibilityState);
+ document.open();document.write('<p>replacement</p>');document.close();
+ });
+ document.addEventListener('visibilitychange',()=>events.push('retired'));
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ vm.set_document_activity(moli_page_types::DocumentActivity::new(false, false))
+ .unwrap();
+ assert!(
+ vm.run_one_rendering_update_executor_turn(&loader)
+ .await
+ .unwrap()
+ );
+ assert_eq!(vm.eval("events.join('|')").unwrap(), "blur:visible");
+ assert_eq!(
+ vm.eval("[document.visibilityState,document.hasFocus()].join(':')")
+ .unwrap(),
+ "hidden:false"
+ );
+}