Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(renderer): retire actions with document lifecycle
ldm0d4e03f24dea4
diff --git a/moli-action-window/src/window.rs b/moli-action-window/src/window.rsindex 6b656a818..5f622afbf 100644--- a/moli-action-window/src/window.rs+++ b/moli-action-window/src/window.rs@@ -168,16 +168,32 @@ impl<S: PartialEq, O> PendingWindow<S, O> {self.actions = normalized;}- fn remove_scope(&mut self, scope: &S) -> usize {- let before = self.retained_action_count;- self.actions.retain(|action| action.scope() != scope);+ fn remove_scope(&mut self, scope: &S) -> Vec<ActionSequence> {+ let mut removed_sequences = Vec::new();+ self.actions.retain(|action| {+ if action.scope() != scope {+ return true;+ }+ match action {+ PlannedAction::Scroll { run, .. } => {+ removed_sequences.extend(run.steps().iter().map(|step| step.sequence()))+ }+ PlannedAction::Click { click, .. } => {+ removed_sequences.push(click.sequence());+ }+ PlannedAction::Ordered { action, .. } => {+ removed_sequences.push(action.sequence());+ }+ }+ false+ });self.retained_action_count = self.actions.iter().map(PlannedAction::retained_action_count).sum();self.normalize_scroll_runs();- before - self.retained_action_count+ removed_sequences}fn into_batch(self, released_at: Instant, cause: ActionBatchCause) -> ActionBatch<S, O> {@@ -329,8 +345,17 @@ impl<S: PartialEq, O> ActionWindow<S, O> {/// If no actions remain, the old deadline is canceled and the queue/// returns to idle.pub fn cancel_scope(&mut self, scope: &S) -> usize {+ self.cancel_scope_sequences(scope).len()+ }++ /// Cancels all pending actions for a scope and returns the retained+ /// sequences that were removed, in their execution order.+ ///+ /// Hosts with renderer-specific sidecars can use these identities to+ /// retire the matching payloads atomically with the semantic actions.+ pub fn cancel_scope_sequences(&mut self, scope: &S) -> Vec<ActionSequence> {let Some(window) = self.open.as_mut() else {- return 0;+ return Vec::new();};let removed = window.remove_scope(scope);if window.actions.is_empty() {diff --git a/moli-action-window/tests/public_api.rs b/moli-action-window/tests/public_api.rsindex db212a935..3d545c13d 100644--- a/moli-action-window/tests/public_api.rs+++ b/moli-action-window/tests/public_api.rs@@ -170,6 +170,60 @@ fn canceling_unknown_scope_is_a_noop_and_preserves_deadline() {assert_eq!(window.pending_planned_action_count(), 1);}+#[test]+fn scope_cancellation_reports_retained_sequences_for_host_sidecar_cleanup() {+ let base = Instant::now();+ let mut window = ActionWindow::<&str, &str>::default();+ let first_scroll = window.push(+ "retired",+ WindowAction::Scroll(ScrollAction::pixels(Point::default(), 0.0, 10.0)),+ base,+ );+ let kept_scroll = window.push(+ "current",+ WindowAction::Scroll(ScrollAction::pixels(Point::default(), 0.0, 20.0)),+ base + Duration::from_millis(10),+ );+ let replaced_click = window.push(+ "retired",+ WindowAction::Click(ClickAction::new(Point::default(), MouseButton::Left, 1)),+ base + Duration::from_millis(20),+ );+ let retained_click = window.push(+ "retired",+ WindowAction::Click(ClickAction::new(Point::default(), MouseButton::Left, 2)),+ base + Duration::from_millis(30),+ );+ let ordered = window.push(+ "retired",+ WindowAction::Ordered("renderer-sidecar"),+ base + Duration::from_millis(40),+ );+ let original_deadline = window.next_deadline();++ assert_eq!(+ window.cancel_scope_sequences(&"retired"),+ vec![+ first_scroll.sequence(),+ retained_click.sequence(),+ ordered.sequence(),+ ]+ );+ assert_ne!(replaced_click.sequence(), retained_click.sequence());+ assert_eq!(window.next_deadline(), original_deadline);+ assert_eq!(window.pending_admitted_action_count(), 5);+ assert_eq!(window.pending_retained_action_count(), 1);++ let batch = window+ .flush(ActionBarrier::Explicit, base + Duration::from_millis(50))+ .expect("the other scope should remain pending");+ let PlannedAction::Scroll { scope, run } = &batch.actions()[0] else {+ panic!("the surviving action should be a scroll run");+ };+ assert_eq!(*scope, "current");+ assert_eq!(run.steps()[0].sequence(), kept_scroll.sequence());+}+#[test]fn click_replacement_reports_public_compaction_without_rotation() {let base = Instant::now();diff --git a/moli-renderer-v8/src/runtime/page_vm/document_lifecycle_turn.rs b/moli-renderer-v8/src/runtime/page_vm/document_lifecycle_turn.rsindex 555bb5cb0..0fe9f4eb8 100644--- a/moli-renderer-v8/src/runtime/page_vm/document_lifecycle_turn.rs+++ b/moli-renderer-v8/src/runtime/page_vm/document_lifecycle_turn.rs@@ -132,6 +132,7 @@ impl PageVm {replacement.to == self.document_lifecycle.identity(),"Document replacement admission targets a non-current identity");+ self.cancel_page_actions_for_document(replacement.from)?;}let ready_admission =diff --git a/moli-renderer-v8/src/runtime/page_vm/page_action_window.rs b/moli-renderer-v8/src/runtime/page_vm/page_action_window.rsindex aad5dd404..a7a6ca048 100644--- a/moli-renderer-v8/src/runtime/page_vm/page_action_window.rs+++ b/moli-renderer-v8/src/runtime/page_vm/page_action_window.rs@@ -9,7 +9,8 @@ use moli_action_window::{use crate::{page_task_queue::RendererPageReadyDescriptor,runtime::{- RendererDocumentToken, RendererInputDispatchOutcome, RendererPointerEventProperties,+ RendererDocumentLifecycleIdentity, RendererInputDispatchOutcome,+ RendererPointerEventProperties,},};@@ -29,7 +30,7 @@ struct QueuedWheelEvent {}pub(super) struct RendererPageActionWindow {- window: ActionWindow<RendererDocumentToken>,+ window: ActionWindow<RendererDocumentLifecycleIdentity>,wheel_events: HashMap<ActionSequence, QueuedWheelEvent>,}@@ -73,7 +74,7 @@ impl PageVm {self.apply_page_action_batch(batch)?;}- let scope = self.document_lifecycle.identity().document;+ let scope = self.document_lifecycle.identity();let admission = self.page_action_window.window.push(scope,WindowAction::Scroll(ScrollAction {@@ -127,10 +128,41 @@ impl PageVm {Ok(true)}- fn apply_page_action_batch(&mut self, batch: ActionBatch<RendererDocumentToken>) -> Result<()> {+ pub(super) fn cancel_page_actions_for_document(+ &mut self,+ document: RendererDocumentLifecycleIdentity,+ ) -> Result<usize> {+ let sequences = self+ .page_action_window+ .window+ .cancel_scope_sequences(&document);+ for sequence in &sequences {+ anyhow::ensure!(+ self.page_action_window+ .wheel_events+ .remove(sequence)+ .is_some(),+ "action-window cancellation lost wheel payload {}",+ sequence.get()+ );+ }+ if !sequences.is_empty() {+ tracing::debug!(+ ?document,+ canceled_action_count = sequences.len(),+ "canceled renderer actions for a retired Document"+ );+ }+ Ok(sequences.len())+ }++ fn apply_page_action_batch(+ &mut self,+ batch: ActionBatch<RendererDocumentLifecycleIdentity>,+ ) -> Result<()> {let batch_id = batch.id().get();let cause = batch.cause();- let current_document = self.document_lifecycle.identity().document;+ let current_document = self.document_lifecycle.identity();let mut events = Vec::with_capacity(batch.retained_action_count());for action in batch.into_actions() {match action {@@ -147,7 +179,7 @@ impl PageVm {)})?;if scope == current_document {- events.push(event);+ events.push((scope, event));}}}@@ -165,7 +197,12 @@ impl PageVm {self.vm_mut().begin_batched_mouse_event_dispatch();let mut first_error = None;- for event in events {+ let mut skipped_after_document_replacement = 0_usize;+ for (document, event) in events {+ if self.document_lifecycle.identity() != document {+ skipped_after_document_replacement += 1;+ continue;+ }let result = self.vm_mut().dispatch_mouse_event_at_point_with_pointer_and_modifiers_without_checkpoint(@@ -186,10 +223,18 @@ impl PageVm {first_error = Some(error);}}+ if skipped_after_document_replacement != 0 {+ tracing::debug!(+ batch_id,+ skipped_action_count = skipped_after_document_replacement,+ "discarded remaining renderer actions after an in-batch Document replacement"+ );+ }let dispatch_result = first_error.map_or(Ok(()), Err);+ let commit_scroll_effects = self.document_lifecycle.identity() == current_document;let result = self.vm_mut()- .finish_batched_mouse_event_dispatch(dispatch_result);+ .finish_batched_mouse_event_dispatch(dispatch_result, commit_scroll_effects);tracing::debug!(batch_id, ?cause, "applied renderer action batch");result}@@ -206,4 +251,14 @@ impl PageVm {};self.apply_page_action_batch(batch)}++ #[cfg(test)]+ pub(super) fn pending_page_action_counts_for_test(&self) -> (usize, usize) {+ (+ self.page_action_window+ .window+ .pending_retained_action_count(),+ self.page_action_window.wheel_events.len(),+ )+ }}diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/lifecycle.rs b/moli-renderer-v8/src/runtime/page_vm/tests/lifecycle.rsindex 1a384221f..2a9ff9bab 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/lifecycle.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/lifecycle.rs@@ -52,6 +52,103 @@ fn stale_domcontentloaded_barrier_preserves_current_document_frontend_bindings());}+#[tokio::test]+async fn action_window_is_preserved_for_same_document_history_and_canceled_on_document_open() {+ run_page_vm_async_test(async move {+ let page_vm = test_page_vm();+ let local_executor = page_vm.local_executor.clone();++ local_executor+ .run(async move {+ let mut page_vm = page_vm;+ let initial_document = page_vm.document_lifecycle.identity();+ let outcome = page_vm.queue_wheel_event(+ 10.0,+ 10.0,+ -1,+ Some(0),+ 0,+ 0.0,+ 25.0,+ crate::RendererPointerEventProperties::default(),+ 0,+ )?;+ assert!(outcome.handled);+ let original_deadline = page_vm+ .next_action_window_deadline()+ .expect("the first wheel should open an action window");+ assert_eq!(page_vm.pending_page_action_counts_for_test(), (1, 1));++ let same_document_snapshot =+ page_vm.document_replacement_lifecycle_action_snapshot();+ assert_eq!(+ page_vm+ .vm_mut()+ .eval("history.pushState({}, '', '#same-document'); location.hash")?,+ "#same-document"+ );+ let mut pending_document_lifecycle_turn = None;+ assert!(+ page_vm+ .reconcile_document_replacement_lifecycle_after_owner_action(+ same_document_snapshot,+ &mut pending_document_lifecycle_turn,+ )+ .await?+ .is_none()+ );+ assert_eq!(page_vm.document_lifecycle.identity(), initial_document);+ assert_eq!(+ page_vm.next_action_window_deadline(),+ Some(original_deadline),+ "same-Document history must retain the existing action window"+ );+ assert_eq!(page_vm.pending_page_action_counts_for_test(), (1, 1));++ let replacement_snapshot = page_vm.document_replacement_lifecycle_action_snapshot();+ assert_eq!(+ page_vm.vm_mut().eval("document.open(); 'opened'")?,+ "opened"+ );+ let replacement_document = page_vm.document_lifecycle.identity();+ assert_eq!(+ replacement_document.document, initial_document.document,+ "document.open keeps the cross-document token generation"+ );+ assert_ne!(+ replacement_document.epoch, initial_document.epoch,+ "document.open must still create a new exact Document lifecycle"+ );+ assert_eq!(+ page_vm.pending_page_action_counts_for_test(),+ (1, 1),+ "cancellation belongs to the owner lifecycle reconciliation boundary"+ );++ assert!(+ page_vm+ .reconcile_document_replacement_lifecycle_after_owner_action(+ replacement_snapshot,+ &mut pending_document_lifecycle_turn,+ )+ .await?+ .is_none(),+ "an open replacement stream should not yet install lifecycle work"+ );+ assert_eq!(page_vm.next_action_window_deadline(), None);+ assert_eq!(+ page_vm.pending_page_action_counts_for_test(),+ (0, 0),+ "retiring the exact Document must remove semantic actions and host payloads"+ );+ Ok::<_, anyhow::Error>(())+ })+ .await+ })+ .await+ .expect("action-window exact Document lifecycle test should run");+}+fn replacement_collision_dynamic_import_owner_action(target: ChildDocumentModuleFetchTarget,) -> crate::frame_owner_model::FrameDocumentDynamicImportTerminalPreparedAction {diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rsindex 4691772a3..2d0e260f2 100644--- a/moli-renderer-v8/src/runtime/tests.rs+++ b/moli-renderer-v8/src/runtime/tests.rs@@ -12662,6 +12662,64 @@ addEventListener("wheel", event => {.expect("capture barrier page should close");}+#[tokio::test(flavor = "multi_thread")]+async fn wheel_batch_stops_when_an_event_replaces_the_exact_document() {+ let runtime = initialize_layout_test_runtime();+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default())+ .expect("default resource request client");+ let url = url::Url::parse("https://example.test/action-window-document-open").unwrap();+ let mut page = create_test_html_page(+ &runtime,+ &loader,+ url,+ r#"<!doctype html>+<style>html, body { margin: 0; } body { height: 1200px; }</style>+<script>+globalThis.__lmRetiredDocumentWheelDeltas = [];+globalThis.__lmReplacementDocumentWheelDeltas = [];+document.addEventListener("wheel", event => {+ __lmRetiredDocumentWheelDeltas.push(event.deltaY);+ document.open();+ document.write("<!doctype html><body style='height:1200px'>replacement</body>");+ document.close();+ document.addEventListener("wheel", replacementEvent => {+ __lmReplacementDocumentWheelDeltas.push(replacementEvent.deltaY);+ }, { capture: true });+}, { capture: true, once: true });+</script>"#,+ )+ .await;++ for delta_y in [10.0, 20.0, 30.0] {+ assert!(+ dispatch_wheel_for_action_window_test(&page, delta_y)+ .await+ .handled+ );+ }++ let (state, _) = page+ .run_async_command(RendererPageCommand::EvaluateExpression {+ expression: r#"JSON.stringify({+ retired: __lmRetiredDocumentWheelDeltas,+ replacement: __lmReplacementDocumentWheelDeltas+})"#+ .to_owned(),+ await_promise: false,+ })+ .await+ .expect("the explicit read barrier should apply the pending wheel batch");+ assert_eq!(+ renderer_json_value(state),+ Some(serde_json::json!(r#"{"retired":[10],"replacement":[]}"#)),+ "actions admitted for the retired lifecycle must not continue in its document.open replacement"+ );++ page.close_async()+ .await+ .expect("document replacement action-window page should close");+}+#[tokio::test(flavor = "multi_thread")]async fn owner_scheduler_runs_post_parse_autofocus_after_domcontentloaded_without_a_command() {let runtime = JsRuntime::initialize();diff --git a/moli-renderer-v8/src/script_vm/input_dispatch.rs b/moli-renderer-v8/src/script_vm/input_dispatch.rsindex 9bc5a9e35..fbe70cce5 100644--- a/moli-renderer-v8/src/script_vm/input_dispatch.rs+++ b/moli-renderer-v8/src/script_vm/input_dispatch.rs@@ -386,12 +386,13 @@ impl ScriptVm {pub(crate) fn finish_batched_mouse_event_dispatch(&mut self,dispatch_result: Result<()>,+ commit_scroll_observable_effects: bool,) -> Result<()> {let effects = self._context_host.borrow_mut().finish_scroll_observable_effect_batch();- let effects_result = match effects {+ let effects_result = match effects.filter(|_| commit_scroll_observable_effects) {Some(effects) => self.with_default_context_scope(|scope, runtime_ptr| {crate::native_bridge::element::apply_scroll_observable_effects(scope,