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): derive options and retire native abort observation by owner
ldm0c7bcf304f0fb
diff --git a/moli-renderer-v8/src/abort_signal_route.rs b/moli-renderer-v8/src/abort_signal_route.rsindex dfe903988..db72d4890 100644--- a/moli-renderer-v8/src/abort_signal_route.rs+++ b/moli-renderer-v8/src/abort_signal_route.rs@@ -27,6 +27,22 @@ pub(crate) struct ResolvedAbortSignal<'s> {owner: AbortSignalOwner,}+impl<'s> webidl::WebIdlConverter<'s> for ResolvedAbortSignal<'s> {+ type Options = ();++ fn convert(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+ context: webidl::Context,+ _: &(),+ ) -> Result<Self, webidl::WebIdlError> {+ v8::Local::<v8::Object>::try_from(value)+ .ok()+ .and_then(|signal| Self::resolve(scope, signal))+ .ok_or_else(|| webidl::WebIdlError::cannot_convert(context, "AbortSignal"))+ }+}+impl<'s> ResolvedAbortSignal<'s> {pub(crate) fn resolve(scope: &mut v8::PinScope<'s, '_>,diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rsindex cf59d977b..370297033 100644--- a/moli-renderer-v8/src/context_bootstrap.rs+++ b/moli-renderer-v8/src/context_bootstrap.rs@@ -42,7 +42,9 @@ pub(crate) use history_runtime::state::bind_isolated_window_history_owner;mod idle_detection;mod image_data;mod javascript_url;-pub(crate) use self::idle_detection::apply_idle_override_to_current_context;+pub(crate) use self::idle_detection::{+ apply_idle_override_to_current_context, retire_idle_detectors_in_current_context,+};mod indexed_db;#[cfg(test)]pub(crate) use exposed_interfaces::{diff --git a/moli-renderer-v8/src/context_bootstrap/idle_detection.rs b/moli-renderer-v8/src/context_bootstrap/idle_detection.rsindex 5d82941fb..9663a5742 100644--- a/moli-renderer-v8/src/context_bootstrap/idle_detection.rs+++ b/moli-renderer-v8/src/context_bootstrap/idle_detection.rs@@ -7,8 +7,8 @@ use crate::web_api_interfaces;use crate::{context_bootstrap::events::mark_event_trusted,util::{- array_push_value, context_host_ptr_from_global_bridge, get_private_value,- set_private_value, throw_type_error, v8_string, v8str,+ context_host_ptr_from_global_bridge, get_private_value, set_private_value,+ throw_type_error, v8_string, v8str,},webidl,};@@ -17,6 +17,8 @@ use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};const IDLE_DETECTOR_STARTED_SLOT: &str = "__lmIdleDetectorStarted";const IDLE_DETECTOR_USER_ACTIVE_SLOT: &str = "__lmIdleDetectorUserActive";const IDLE_DETECTOR_SCREEN_UNLOCKED_SLOT: &str = "__lmIdleDetectorScreenUnlocked";+const IDLE_DETECTOR_ABORT_SIGNAL_SLOT: &str = "__lmIdleDetectorAbortSignal";+const IDLE_DETECTOR_ABORT_ALGORITHM_SLOT: &str = "__lmIdleDetectorAbortAlgorithm";const IDLE_DETECTOR_REGISTRY_SLOT: &str = "__lmIdleDetectorRegistry";const MINIMUM_IDLE_THRESHOLD_MS: u32 = 60_000;const ACTUAL_IDLE_STATE: crate::protocol_types::EmulatedIdleOverride =@@ -39,6 +41,12 @@ struct IdleDetectorObjectDeclaration {#[webapi(slot = SIMPLE_EVENT_TARGET_LISTENERS_SLOT, init = "null_object")]event_listeners: (),++ #[webapi(slot = IDLE_DETECTOR_ABORT_SIGNAL_SLOT, init = "null")]+ abort_signal: (),++ #[webapi(slot = IDLE_DETECTOR_ABORT_ALGORITHM_SLOT, init = "null")]+ abort_algorithm: (),}#[derive(WebApiFunctionTemplate)]@@ -69,7 +77,8 @@ struct IdleDetectorPrototypeDeclaration {)]screen_state: (),- #[webapi(method, length = 0, callback = idle_detector_start_callback)]+ #[webapi(method, length = 0, callback = idle_detector_start_callback,+ returns_promise, receiver = web_api_interfaces::IdleDetector::is_instance)]start: (),}@@ -128,12 +137,40 @@ fn idle_detector_receiver<'s>(None}+fn idle_detector_owner_context<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ detector: v8::Local<'s, v8::Object>,+) -> Option<v8::Local<'s, v8::Context>> {+ let context = detector.get_creation_context(scope)?;+ if crate::util::page_context_is_detached_document(context)+ || crate::util::page_context_is_disconnected(context)+ {+ return None;+ }+ let host_ptr = crate::util::context_host_ptr_from_context_slot(context)?;+ let host = unsafe { &*host_ptr };+ // DOM removal revokes execution authority before the deferred Context+ // cleanup runs. Public state and start must observe that revocation now.+ host.window_execution_context_identity_for_v8_context(scope, context)+ .filter(|identity| {+ host.window_execution_context_identity_is_current(*identity)+ && match identity.dispatch_scope() {+ crate::native_bridge::OwnerDispatchScope::Child(handle) => {+ host.child_browsing_context_is_live(handle)+ }+ _ => true,+ }+ })+ .map(|_| context)+}+fn idle_detector_started<'s>(scope: &mut v8::PinScope<'s, '_>,detector: v8::Local<'s, v8::Object>,) -> bool {get_private_value(scope, detector, IDLE_DETECTOR_STARTED_SLOT).is_some_and(|value| value.boolean_value(scope))+ && idle_detector_owner_context(scope, detector).is_some()}fn idle_detector_user_state_getter<'s>(@@ -170,20 +207,67 @@ fn idle_detector_screen_state_getter<'s>(rv.set(v8str(scope, if unlocked { "unlocked" } else { "locked" }).into());}+#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "IdleDetector.start")]+struct IdleDetectorStartArgs<'s> {+ #[webidl(dictionary)]+ options: IdleOptions<'s>,+}++#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "IdleOptions")]+struct IdleOptions<'s> {+ #[webidl(converter = "raw")]+ signal: Option<crate::abort_signal_route::ResolvedAbortSignal<'s>>,+ #[webidl(default = MINIMUM_IDLE_THRESHOLD_MS, converter = "enforce_range_unsigned_long")]+ threshold: u32,+}+fn idle_detector_start_callback<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'s, v8::Value>,) {+ let Some(parsed) = webidl::parse_args::<IdleDetectorStartArgs>(scope, &args) else {+ return;+ };+ let options = parsed.options;+ let detector = args.this();let Some(resolver) = v8::PromiseResolver::new(scope) else {rv.set_undefined();return;};rv.set(resolver.get_promise(scope).into());- let Some(detector) = idle_detector_receiver(scope, args.this()) else {+ let Some(owner_context) = idle_detector_owner_context(scope, detector) else {+ reject_dom_exception(+ scope,+ resolver,+ "InvalidStateError",+ "Execution context is detached.",+ );+ return;+ };+ let Some(host_ptr) = crate::util::context_host_ptr_from_context_slot(owner_context) else {+ reject_dom_exception(+ scope,+ resolver,+ "InvalidStateError",+ "Execution context is detached.",+ );return;};+ // Copy native state before registering an algorithm, which mutably borrows+ // the signal's host. No host borrow crosses the registration or callbacks.+ let (permission_granted, state) = {+ let host = unsafe { &*host_ptr };+ let state = if context_is_top_level_window(scope, host, owner_context) {+ host.idle_override().unwrap_or(ACTUAL_IDLE_STATE)+ } else {+ ACTUAL_IDLE_STATE+ };+ (host.permission_state("idle-detection") == "granted", state)+ };if idle_detector_started(scope, detector) {reject_dom_exception(scope,@@ -193,87 +277,167 @@ fn idle_detector_start_callback<'s>();return;}- if let Err(message) = validate_idle_options(scope, args.get(0)) {- reject_type_error(scope, resolver, &message);+ if options.threshold < MINIMUM_IDLE_THRESHOLD_MS {+ reject_type_error(scope, resolver, "Minimum threshold is 1 minute.");+ return;+ }+ let signal = options.signal;+ if let Some(signal) = signal+ && signal.is_aborted(scope)+ {+ let reason = signal+ .reason(scope)+ .unwrap_or_else(|| crate::native_bridge::abort::abort_error_value(scope));+ let _ = resolver.reject(scope, reason);return;}- let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {+ if !permission_granted {reject_dom_exception(scope,resolver,- "InvalidStateError",- "Execution context is detached.",+ "NotAllowedError",+ "Idle detection permission denied",);return;+ }++ let algorithm = if let Some(signal) = signal {+ let algorithm = {+ let owner_scope = &mut v8::ContextScope::new(scope, owner_context);+ v8::Function::builder(idle_detector_abort_callback)+ .data(detector.into())+ .build(owner_scope)+ };+ let Some(algorithm) = algorithm else {+ return;+ };+ if !signal.register_algorithm(scope, algorithm) {+ reject_dom_exception(+ scope,+ resolver,+ "InvalidStateError",+ "AbortSignal execution context is detached.",+ );+ return;+ }+ Some((signal, algorithm))+ } else {+ None};- let host = unsafe { &*host_ptr };- if host.permission_state("idle-detection") != "granted" {+ let owner_global = owner_context.global(scope);+ if !register_idle_detector(scope, owner_global, detector) {+ if let Some((signal, algorithm)) = algorithm {+ signal.unregister_algorithm(scope, algorithm);+ }reject_dom_exception(scope,resolver,- "NotAllowedError",- "Idle detection permission denied",+ "InvalidStateError",+ "Idle detector observation could not be registered.",);return;}-+ if let Some((signal, algorithm)) = algorithm {+ set_private_value(+ scope,+ detector,+ IDLE_DETECTOR_ABORT_SIGNAL_SLOT,+ signal.value().into(),+ );+ set_private_value(+ scope,+ detector,+ IDLE_DETECTOR_ABORT_ALGORITHM_SLOT,+ algorithm.into(),+ );+ }set_private_value(scope,detector,IDLE_DETECTOR_STARTED_SLOT,v8::Boolean::new(scope, true).into(),);- register_idle_detector(scope, detector);- let state = if current_context_is_top_level_window(scope, host) {- host.idle_override().unwrap_or(ACTUAL_IDLE_STATE)- } else {- ACTUAL_IDLE_STATE- };let _ = resolver.resolve(scope, v8::undefined(scope).into());update_idle_detector(scope, detector, state, true);}-fn current_context_is_top_level_window(+fn context_is_top_level_window(scope: &mut v8::PinScope<'_, '_>,host: &crate::native_bridge::JsContextHost,+ context: v8::Local<'_, v8::Context>,) -> bool {- let current_global = scope.get_current_context().global(scope);+ let current_global = context.global(scope);host.page_default_context(scope).is_some_and(|context| context.global(scope).strict_equals(current_global.into()))}-fn validate_idle_options<'s>(+fn clear_idle_abort_registration<'s>(scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,-) -> Result<(), String> {- let options =- webidl::dictionary_value(value, webidl::Context::argument("IdleDetector.start", 1))- .map_err(|error| error.to_string())?;- let Some(options) = options else {- return Ok(());- };- let threshold = webidl::property_result(+ detector: v8::Local<'s, v8::Object>,+) {+ let signal = get_private_value(scope, detector, IDLE_DETECTOR_ABORT_SIGNAL_SLOT)+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok());+ let algorithm = get_private_value(scope, detector, IDLE_DETECTOR_ABORT_ALGORITHM_SLOT)+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok());+ set_private_value(scope,- options,- "threshold",- webidl::Context::member("IdleOptions", "threshold"),- )- .map_err(|error| error.to_string())?;- let Some(threshold) = threshold.filter(|value| !value.is_undefined()) else {- return Ok(());+ detector,+ IDLE_DETECTOR_ABORT_SIGNAL_SLOT,+ v8::null(scope).into(),+ );+ set_private_value(+ scope,+ detector,+ IDLE_DETECTOR_ABORT_ALGORITHM_SLOT,+ v8::null(scope).into(),+ );+ if let (Some(signal), Some(algorithm)) = (signal, algorithm)+ && let Some(source_context) = signal.get_creation_context(scope)+ {+ // The observing realm can retire while the signal's realm remains+ // live. Remove only this registration from the source owner's store.+ let source_scope = &mut v8::ContextScope::new(scope, source_context);+ if let Some(signal) =+ crate::abort_signal_route::ResolvedAbortSignal::resolve(source_scope, signal)+ {+ signal.unregister_algorithm(source_scope, algorithm);+ }+ }+}++fn idle_detector_abort_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ _rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Ok(detector) = v8::Local::<v8::Object>::try_from(args.data()) else {+ return;};- let threshold = webidl::convert::<webidl::EnforceRangeUnsignedLong>(+ set_private_value(scope,- threshold,- webidl::Context::member("IdleOptions", "threshold"),- )- .map_err(|error| error.to_string())?- .0;- if threshold < MINIMUM_IDLE_THRESHOLD_MS {- return Err("Minimum threshold is 1 minute.".to_owned());+ detector,+ IDLE_DETECTOR_STARTED_SLOT,+ v8::Boolean::new(scope, false).into(),+ );+ clear_idle_abort_registration(scope, detector);+ // Stop observing and release the registry's strong reference. The signal+ // owner drains this one-shot abort algorithm; realm teardown owns the rest.+ let global = scope.get_current_context().global(scope);+ if let Some(registry) = get_private_value(scope, global, IDLE_DETECTOR_REGISTRY_SLOT)+ .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())+ {+ let mut retained = Vec::new();+ for index in 0..registry.length() {+ if let Some(value) = registry.get_index(scope, index)+ && !value.strict_equals(detector.into())+ {+ retained.push(value);+ }+ }+ let retained = v8::Array::new_with_elements(scope, &retained);+ set_private_value(scope, global, IDLE_DETECTOR_REGISTRY_SLOT, retained.into());}- Ok(())}fn idle_detector_request_permission_callback<'s>(@@ -297,9 +461,9 @@ fn idle_detector_request_permission_callback<'s>(fn register_idle_detector<'s>(scope: &mut v8::PinScope<'s, '_>,+ global: v8::Local<'s, v8::Object>,detector: v8::Local<'s, v8::Object>,-) {- let global = scope.get_current_context().global(scope);+) -> bool {let registry = get_private_value(scope, global, IDLE_DETECTOR_REGISTRY_SLOT).and_then(|value| v8::Local::<v8::Array>::try_from(value).ok()).unwrap_or_else(|| {@@ -307,7 +471,40 @@ fn register_idle_detector<'s>(set_private_value(scope, global, IDLE_DETECTOR_REGISTRY_SLOT, registry.into());registry});- array_push_value(scope, registry, detector.into());+ let Some(index) = v8::Integer::new_from_unsigned(scope, registry.length()).to_string(scope)+ else {+ return false;+ };+ registry.create_data_property(scope, index.into(), detector.into()) == Some(true)+}++pub(crate) fn retire_idle_detectors_in_current_context(scope: &mut v8::PinScope<'_, '_>) {+ let global = scope.get_current_context().global(scope);+ let Some(registry) = get_private_value(scope, global, IDLE_DETECTOR_REGISTRY_SLOT)+ .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())+ else {+ return;+ };+ for index in 0..registry.length() {+ if let Some(detector) = registry+ .get_index(scope, index)+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ {+ set_private_value(+ scope,+ detector,+ IDLE_DETECTOR_STARTED_SLOT,+ v8::Boolean::new(scope, false).into(),+ );+ clear_idle_abort_registration(scope, detector);+ }+ }+ set_private_value(+ scope,+ global,+ IDLE_DETECTOR_REGISTRY_SLOT,+ v8::Array::new(scope, 0).into(),+ );}pub(crate) fn apply_idle_override_to_current_context(diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rsindex 950aebcc5..31dd2bce0 100644--- a/moli-renderer-v8/src/native_bridge/identity.rs+++ b/moli-renderer-v8/src/native_bridge/identity.rs@@ -553,6 +553,7 @@ pub(crate) fn clear_context_wrapper_cache_for_teardown() {let context = scope.get_current_context();let _ = crate::context_bootstrap::retain_window_document_in_retired_realm(scope);+ crate::context_bootstrap::retire_idle_detectors_in_current_context(scope);crate::util::detach_document_page_context(context);if let Some(host) = crate::util::context_host_ptr_from_context_slot(context) {unsafe { &mut *host }diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/idle_detection.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/idle_detection.rsindex ed75ef640..2ee9899a6 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/idle_detection.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/idle_detection.rs@@ -9,6 +9,60 @@ fn idle_permission_override() -> crate::protocol_types::PermissionOverrideRegist}}+fn assert_idle_fixture(vm: &mut StandaloneScriptVmHarness, source: &str) {+ vm.eval(&format!(+ "globalThis.idleFixtureResult='pending'; ({}).then(value=>idleFixtureResult=value,error=>idleFixtureResult=String(error.stack||error));",+ source,+ ))+ .unwrap();+ vm.eval("0").unwrap();+ assert_eq!(vm.eval("String(idleFixtureResult)").unwrap(), "true");+}++#[test]+fn idle_options_convert_before_state_permission_and_abort_algorithms() {+ let mut vm = new_storage_test_vm("https://idle-options.test/");+ assert_idle_fixture(+ &mut vm,+ include_str!("../../../../tests/fixtures/idle-options-dictionary.js"),+ );+}++#[test]+fn idle_abort_stops_observation_and_preserves_other_registered_detectors() {+ let mut vm = new_storage_test_vm("https://idle-abort.test/");+ vm.set_permission_overrides(&[idle_permission_override()]);+ assert_idle_fixture(+ &mut vm,+ include_str!("../../../../tests/fixtures/idle-abort-runtime.js"),+ );+ vm.set_idle_override_and_sync_surface(Some(crate::protocol_types::EmulatedIdleOverride {+ is_user_active: false,+ is_screen_unlocked: false,+ }))+ .unwrap();+ assert_eq!(+ vm.eval("JSON.stringify([idleStopped.userState,idleStopped.screenState,idleActive.userState,idleActive.screenState,idleStoppedChanges,idleActiveChanges])").unwrap(),+ r#"[null,null,"idle","locked",0,1]"#+ );+ vm.eval("idleActiveController.abort()").unwrap();+ vm.set_idle_override_and_sync_surface(None).unwrap();+ assert_eq!(+ vm.eval("JSON.stringify([idleStopped.userState,idleActive.userState,idleStoppedChanges,idleActiveChanges])").unwrap(),+ "[null,null,0,1]"+ );+}++#[test]+fn idle_observer_and_signal_algorithm_retire_with_the_detector_realm() {+ let mut vm = new_storage_html_test_vm("https://idle-realm.test/");+ vm.set_permission_overrides(&[idle_permission_override()]);+ assert_idle_fixture(+ &mut vm,+ include_str!("../../../../tests/fixtures/idle-realm-lifetime.js"),+ );+}+#[test]fn idle_detector_observes_devtools_override_and_clear() {let mut vm = new_storage_test_vm("https://idle-detector.test/");diff --git a/moli-renderer-v8/tests/fixtures/idle-abort-runtime.js b/moli-renderer-v8/tests/fixtures/idle-abort-runtime.jsnew file mode 100644index 000000000..9fdd872af--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/idle-abort-runtime.js@@ -0,0 +1,38 @@+(async () => {+ const assert = (ok, label) => { if (!ok) throw Error(label); };+ const stopped = new IdleDetector(), controller = new AbortController();+ controller.signal.addEventListener = () => { throw Error('author addEventListener'); };+ let indexedSets = 0, promise;+ const previous = Object.getOwnPropertyDescriptor(Array.prototype, '0');+ Object.defineProperty(Array.prototype, '0', {configurable: true, set() { indexedSets++; throw Error('author index setter'); }});+ try { promise = stopped.start({signal: controller.signal}); }+ finally { if (previous) Object.defineProperty(Array.prototype, '0', previous); else delete Array.prototype[0]; }+ await promise;+ assert(indexedSets === 0, 'observer registry does not execute author indexed setters');+ assert(stopped.userState === 'active' && stopped.screenState === 'unlocked', 'initial idle state');+ const active = new IdleDetector(), activeController = new AbortController();+ await active.start({signal: activeController.signal});+ let error;+ await active.start().catch(caught => { error = caught; });+ assert(error && error.name === 'InvalidStateError', 'single active observation');+ const sentinel = {};+ error = undefined;+ await active.start({get threshold() { throw sentinel; }}).catch(caught => { error = caught; });+ assert(error === sentinel, 'argument conversion precedes started state check');+ controller.abort(sentinel);+ assert(stopped.userState === null && stopped.screenState === null && active.userState === 'active', 'abort only stops its detector');+ const restartedController = new AbortController();+ await stopped.start({signal: restartedController.signal});+ controller.abort();+ assert(stopped.userState === 'active', 'old aborted signal does not stop a new observation');+ restartedController.abort();+ assert(stopped.userState === null && stopped.screenState === null, 'abort resets public state after restart');+ globalThis.idleStopped = stopped;+ globalThis.idleActive = active;+ globalThis.idleActiveController = activeController;+ globalThis.idleStoppedChanges = 0;+ globalThis.idleActiveChanges = 0;+ stopped.addEventListener('change', () => idleStoppedChanges++);+ active.addEventListener('change', () => idleActiveChanges++);+ return true;+})()diff --git a/moli-renderer-v8/tests/fixtures/idle-options-dictionary.js b/moli-renderer-v8/tests/fixtures/idle-options-dictionary.jsnew file mode 100644index 000000000..caf83c354--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/idle-options-dictionary.js@@ -0,0 +1,46 @@+(async () => {+ const assert = (ok, label) => { if (!ok) throw Error(label); };+ const rejection = async (detector, options) => {+ let promise;+ try { promise = detector.start(options); } catch (error) { throw Error('start threw synchronously'); }+ assert(promise instanceof Promise, 'start Promise');+ let rejected = false, error;+ await promise.then(() => {}, caught => { rejected = true; error = caught; });+ assert(rejected, 'start must reject');+ return error;+ };+ const members = ['signal','threshold'];+ for (const stop of members) for (const sentinel of [undefined, null, false, 0, 'sentinel', {}]) {+ const trace = [], options = {};+ for (const key of members) Object.defineProperty(options, key, {get() {+ trace.push(key); if (key === stop) throw sentinel;+ }});+ const detector = new IdleDetector();+ const error = await rejection(detector, options);+ assert(Object.is(error, sentinel) && trace.join() === members.slice(0, members.indexOf(stop) + 1).join(), stop + ' original rejection and short circuit');+ assert(detector.userState === null && detector.screenState === null, 'failed conversion does not start observation');+ }+ for (const signal of [null, {}, new Proxy(new AbortController().signal, {})]) {+ let late = 0;+ const error = await rejection(new IdleDetector(), {signal, get threshold() { late++; }});+ assert(error instanceof TypeError && late === 0, 'native signal conversion before threshold');+ }+ for (const threshold of [-1, Infinity, NaN, 1n, Symbol('threshold'), 59999]) {+ assert(await rejection(new IdleDetector(), {threshold}) instanceof TypeError, 'threshold range and algorithm minimum');+ }+ for (const options of [1, true, 'options', 1n, Symbol('options')]) {+ assert(await rejection(new IdleDetector(), options) instanceof TypeError, 'primitive dictionary');+ }+ const reason = {}, controller = new AbortController(); controller.abort(reason);+ const detector = new IdleDetector();+ assert(await rejection(detector, {signal: controller.signal}) === reason, 'abort reason before permission check');+ const conversionError = {};+ assert(await rejection(detector, {signal: controller.signal, get threshold() { throw conversionError; }}) === conversionError,+ 'complete dictionary conversion before abort algorithm');+ let reads = 0, promise;+ try { promise = IdleDetector.prototype.start.call({}, {get signal() { reads++; }}); } catch (error) { throw Error('receiver failure threw synchronously'); }+ let error;+ await promise.catch(caught => { error = caught; });+ assert(error instanceof TypeError && reads === 0, 'receiver checked before options in rejected Promise');+ return true;+})()diff --git a/moli-renderer-v8/tests/fixtures/idle-realm-lifetime.js b/moli-renderer-v8/tests/fixtures/idle-realm-lifetime.jsnew file mode 100644index 000000000..c695dfaab--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/idle-realm-lifetime.js@@ -0,0 +1,22 @@+(async () => {+ const assert = (ok, label) => { if (!ok) throw Error(label); };+ const frame = document.createElement('iframe'); document.body.appendChild(frame);+ const controller = new AbortController();+ const childDetector = new frame.contentWindow.IdleDetector();+ const rootDetector = new IdleDetector();+ await IdleDetector.prototype.start.call(childDetector, {signal: controller.signal});+ await rootDetector.start({signal: controller.signal});+ assert(childDetector.userState === 'active' && rootDetector.userState === 'active', 'both realms observe');+ frame.remove(); await Promise.resolve();+ assert(childDetector.userState === null && childDetector.screenState === null && rootDetector.userState === 'active', 'teardown stops only the retired owner');+ const marker = {}, aborted = new AbortController(); aborted.abort(marker);+ for (const [options, expected] of [[{threshold: 59999}, 'InvalidStateError'], [{signal: aborted.signal}, 'InvalidStateError'],+ [{get signal() { throw marker; }}, marker], [{threshold: Infinity}, 'TypeError']]) {+ let error;+ await IdleDetector.prototype.start.call(childDetector, options).catch(caught => { error = caught; });+ assert(expected === marker ? error === marker : error && error.name === expected, 'retired owner validation priority');+ }+ controller.abort();+ assert(childDetector.userState === null && rootDetector.userState === null, 'source signal keeps the other realm algorithm after observing realm teardown');+ return true;+})()