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(idle): align deadlines with the DOM clock
ldm02fc3c71030c8
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/idle_callbacks.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/idle_callbacks.rsindex d8570dff3..f2631c527 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/idle_callbacks.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/idle_callbacks.rs@@ -1,5 +1,38 @@use super::*;+#[tokio::test]+async fn idle_deadline_remaining_time_uses_dom_clock_resolution() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ let mut vm = new_storage_test_vm("https://idle-deadline-resolution.test/");++ vm.eval(+ r#"+globalThis.__idleDeadlineResolution = null;+requestIdleCallback(deadline => {+ deadline.__moliIdleDeadlineTimeOrigin = Number.POSITIVE_INFINITY;+ const remaining = Array.from({ length: 16 }, () => deadline.timeRemaining());+ globalThis.__idleDeadlineResolution = {+ positive: remaining.some(value => value > 0),+ bounded: remaining.every(value => value >= 0 && value <= 50),+ sameResolutionAsPerformance: remaining.every(value =>+ Math.abs(value * 10 - Math.round(value * 10)) < 1e-7),+ nonincreasing: remaining.every((value, index) =>+ index === 0 || value <= remaining[index - 1])+ };+});+"#,+ )+ .expect("idle deadline resolution probe should schedule");+ vm.advance_timers_until_deadline_for_test(&loader)+ .await+ .expect("idle deadline resolution probe should drain");+ assert_eq!(+ vm.eval("JSON.stringify(__idleDeadlineResolution)")+ .expect("idle deadline resolution facts should evaluate"),+ r#"{"positive":true,"bounded":true,"sameResolutionAsPerformance":true,"nonincreasing":true}"#+ );+}+#[tokio::test]async fn idle_callback_timeout_is_a_deadline_not_a_dispatch_delay() {let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");diff --git a/moli-renderer-v8/src/window_host.rs b/moli-renderer-v8/src/window_host.rsindex 1cadae126..5bd0856e2 100644--- a/moli-renderer-v8/src/window_host.rs+++ b/moli-renderer-v8/src/window_host.rs@@ -2,6 +2,7 @@ use super::{context_bootstrap::CHILD_BROWSING_CONTEXT_HANDLE_SLOT as WINDOW_CHILD_CONTEXT_HANDLE_SLOT,context_bootstrap::DOCUMENT_SELECTION_CHANGE_LISTENER_SLOT,context_bootstrap::PERFORMANCE_TIME_ORIGIN_SLOT,+ context_bootstrap::current_performance_time_origin,context_bootstrap::dom_time_since_origin_millis,context_bootstrap::event_initialized,context_bootstrap::event_is_dispatching,@@ -62,6 +63,7 @@ const WINDOW_PENDING_ANIMATION_FRAME_TIMESTAMP_SLOT: &str =const IDLE_CALLBACK_BUDGET_MS: f64 = 50.0;const IDLE_DEADLINE_DID_TIMEOUT_SLOT: &str = "__moliIdleDeadlineDidTimeout";const IDLE_DEADLINE_MS_SLOT: &str = "__moliIdleDeadlineMs";+const IDLE_DEADLINE_TIME_ORIGIN_SLOT: &str = "__moliIdleDeadlineTimeOrigin";const IDLE_OPPORTUNITY_DELAY_MS: u32 = 1;const WINDOW_REQUEST_ANIMATION_FRAME_DELAY_MS: u32 = 16;pub(crate) const TOP_WINDOW_MESSAGE_ENDPOINT_SLOT: &str = "__moliTopWindowMessageEndpoint";@@ -87,6 +89,8 @@ struct WindowDocumentEventInitDeclaration {struct IdleDeadlineDeclaration {#[webapi(slot = IDLE_DEADLINE_MS_SLOT)]deadline_ms: f64,+ #[webapi(slot = IDLE_DEADLINE_TIME_ORIGIN_SLOT)]+ time_origin_ms: f64,#[webapi(slot = IDLE_DEADLINE_DID_TIMEOUT_SLOT)]did_timeout: bool,}@@ -1867,7 +1871,8 @@ pub(crate) fn build_window_idle_deadline<'s>(} else {now_ms + IDLE_CALLBACK_BUDGET_MS};- IdleDeadlineDeclaration::new(deadline_ms, did_timeout)+ let time_origin_ms = current_performance_time_origin(scope);+ IdleDeadlineDeclaration::new(deadline_ms, time_origin_ms, did_timeout).bind(scope).ok()}@@ -1915,9 +1920,20 @@ fn window_idle_deadline_time_remaining_callback<'s>(return;};let now_ms = current_time_ms();+ let time_origin_ms = get_private_value(scope, deadline, IDLE_DEADLINE_TIME_ORIGIN_SLOT)+ .and_then(|value| value.number_value(scope))+ .unwrap_or(0.0);let remaining_ms = get_private_value(scope, deadline, IDLE_DEADLINE_MS_SLOT).and_then(|value| value.number_value(scope))- .map_or(0.0, |deadline_ms| (deadline_ms - now_ms).max(0.0));+ .map_or(0.0, |deadline_ms| {+ // Use the captured origin even if timeRemaining is borrowed from+ // another realm. Both timestamps must match performance.now()'s+ // relative clock and precision rather than the raw wall clock.+ moli_time::coarsened_dom_time_remaining_millis(+ (deadline_ms - time_origin_ms).max(0.0),+ (now_ms - time_origin_ms).max(0.0),+ )+ });rv.set(v8::Number::new(scope, remaining_ms).into());}diff --git a/moli-time/src/lib.rs b/moli-time/src/lib.rsindex 5c302cd75..b5cafac5f 100644--- a/moli-time/src/lib.rs+++ b/moli-time/src/lib.rs@@ -39,12 +39,22 @@ pub fn monotonic_timestamp_micros() -> u64 {.unwrap_or(u64::MAX)}+// High Resolution Time requires the default, non-isolated clock to expose+// no finer than 100 microseconds. Cross-origin-isolated realms may opt into+// a finer clock later.+const DOM_TIME_TICKS_PER_MILLISECOND: f64 = 10.0;+pub fn coarsened_dom_time_millis(millis: f64) -> f64 {- // High Resolution Time requires the default, non-isolated clock to expose- // no finer than 100 microseconds. Keep the shared clock on that safe- // default; cross-origin-isolated realms may opt into a finer clock later.- const TEN_TICKS_PER_MILLISECOND: f64 = 10.0;- (millis * TEN_TICKS_PER_MILLISECOND).floor() / TEN_TICKS_PER_MILLISECOND+ (millis * DOM_TIME_TICKS_PER_MILLISECOND).floor() / DOM_TIME_TICKS_PER_MILLISECOND+}++/// Remaining time between two timestamps on the same relative DOM timeline.+/// Subtract in ticks so floating-point cancellation cannot expose sub-tick+/// residuals or change the precision of the remaining duration.+pub fn coarsened_dom_time_remaining_millis(deadline_millis: f64, now_millis: f64) -> f64 {+ let deadline_ticks = (deadline_millis * DOM_TIME_TICKS_PER_MILLISECOND).floor();+ let now_ticks = (now_millis * DOM_TIME_TICKS_PER_MILLISECOND).floor();+ (deadline_ticks - now_ticks).max(0.0) / DOM_TIME_TICKS_PER_MILLISECOND}pub fn dom_time_since_origin_millis(time_origin: f64) -> f64 {@@ -117,6 +127,25 @@ mod tests {);}+ #[test]+ fn remaining_dom_time_uses_the_same_clock_buckets_as_performance_now() {+ let first =+ coarsened_dom_time_millis(24.381) + coarsened_dom_time_remaining_millis(74.331, 24.381);+ let next =+ coarsened_dom_time_millis(24.393) + coarsened_dom_time_remaining_millis(74.352, 24.393);+ assert_eq!(first, 74.3);+ assert_eq!(next, first);+ assert_eq!(coarsened_dom_time_remaining_millis(74.331, 24.414), 49.9);+ }++ #[test]+ fn remaining_dom_time_preserves_resolution_and_clamps_expired_deadlines() {+ assert_eq!(coarsened_dom_time_remaining_millis(1.3, 1.2), 0.1);+ assert_eq!(coarsened_dom_time_remaining_millis(1.31, 1.29), 0.1);+ assert_eq!(coarsened_dom_time_remaining_millis(1.39, 1.399), 0.0);+ assert_eq!(coarsened_dom_time_remaining_millis(1.3, 1.4), 0.0);+ }+#[test]fn shared_monotonic_seconds_and_micros_use_the_same_epoch() {let seconds = monotonic_timestamp_seconds();