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(input): dispatch InputEvent metadata for text edits
ldm0f0a31d85ed4c
diff --git a/moli-protocol/src/domains/input/tests/keyboard_events.rs b/moli-protocol/src/domains/input/tests/keyboard_events.rsindex 482274bc0..d34c4b89c 100644--- a/moli-protocol/src/domains/input/tests/keyboard_events.rs+++ b/moli-protocol/src/domains/input/tests/keyboard_events.rs@@ -11,6 +11,7 @@ async fn keyboard_fixture(control: &str) -> TestContext {let html = r#"<html><body>CONTROL<input id='other'><script>window.__events = [];window.__keypresses = [];+ window.__inputEvents = [];window.__cancel = '';window.__moveFocus = false;for (const type of ['keydown', 'keypress', 'beforeinput', 'input', 'keyup']) {@@ -21,6 +22,14 @@ async fn keyboard_fixture(control: &str) -> TestContext {keyCode: event.keyCode, charCode: event.charCode,which: event.which, trusted: event.isTrusted});}+ if (type === 'beforeinput' || type === 'input') {+ __inputEvents.push({type, inputEvent: event instanceof InputEvent,+ data: event.data, inputType: event.inputType,+ isComposing: event.isComposing, trusted: event.isTrusted,+ bubbles: event.bubbles, composed: event.composed,+ cancelable: event.cancelable,+ value: event.target.value ?? event.target.textContent});+ }if (type === __cancel) event.preventDefault();if (type === 'keydown' && __moveFocus)document.getElementById('other').focus();@@ -56,6 +65,166 @@ async fn events(ctx: &mut TestContext) -> serde_json::Value {.expect("event log must be JSON")}+async fn assert_input_events(+ ctx: &mut TestContext,+ input_type: &str,+ before_data: Option<&str>,+ input_data: Option<&str>,+ before_value: &str,+ after_value: &str,+ canceled: bool,+) {+ let event = |event_type: &str, data: Option<&str>, value: &str| {+ json!({"type": event_type, "inputEvent": true, "data": data,+ "inputType": input_type, "isComposing": false, "trusted": true,+ "bubbles": true, "composed": true, "cancelable": event_type == "beforeinput",+ "value": value})+ };+ let mut expected = vec![event("beforeinput", before_data, before_value)];+ if !canceled {+ expected.push(event("input", input_data, after_value));+ }+ let actual: serde_json::Value =+ serde_json::from_str(&evaluate_string(ctx, "JSON.stringify(__inputEvents)").await)+ .expect("input event log must be JSON");+ assert_eq!(actual, json!(expected));+ assert_eq!(field_value(ctx).await, after_value);+}++#[tokio::test(flavor = "multi_thread")]+async fn cdp_text_editing_dispatches_input_events_with_text_and_cancellation() {+ for control in CONTROLS {+ for route in ["keyDown", "char", "insertText"] {+ for text in ["a", "πz"] {+ for canceled in [false, true] {+ let mut ctx = keyboard_fixture(control).await;+ if canceled {+ assert!(evaluate_bool(&mut ctx, "(__cancel = 'beforeinput') !== ''").await);+ }+ if route == "insertText" {+ ctx.process_async(json!({"id": 902, "method": "Input.insertText",+ "params": {"text": text}}))+ .await;+ ctx.expect_result(902, json!({}), None);+ } else {+ dispatch(&mut ctx, route, text, "", text).await;+ }+ assert_input_events(+ &mut ctx,+ "insertText",+ Some(text),+ Some(text),+ "",+ if canceled { "" } else { text },+ canceled,+ )+ .await;+ }+ }+ }+ }+}++#[tokio::test(flavor = "multi_thread")]+async fn cdp_text_editing_deletion_input_events_report_direction_and_null_data() {+ for control in CONTROLS {+ for (key, input_type) in [+ ("Backspace", "deleteContentBackward"),+ ("Delete", "deleteContentForward"),+ ] {+ for canceled in [false, true] {+ let mut ctx = keyboard_fixture(control).await;+ assert!(+ evaluate_bool(+ &mut ctx,+ r#"(() => {+ const field = document.getElementById('field');+ if ('value' in field) {+ field.value = 'abc'; field.setSelectionRange(1, 2);+ } else {+ field.textContent = 'abc';+ const range = document.createRange();+ range.setStart(field.firstChild, 1); range.setEnd(field.firstChild, 2);+ const selection = getSelection();+ selection.removeAllRanges(); selection.addRange(range);+ }+ return true;+ })()"#+ )+ .await+ );+ if canceled {+ assert!(evaluate_bool(&mut ctx, "(__cancel = 'beforeinput') !== ''").await);+ }+ dispatch(&mut ctx, "rawKeyDown", key, key, "").await;+ assert_input_events(+ &mut ctx,+ input_type,+ None,+ None,+ "abc",+ if canceled { "abc" } else { "ac" },+ canceled,+ )+ .await;+ }+ }+ }+}++#[tokio::test(flavor = "multi_thread")]+async fn cdp_textarea_enter_input_events_report_line_break_and_null_data() {+ for (route, key) in [("keyDown", "Enter"), ("char", "")] {+ for canceled in [false, true] {+ let mut ctx = keyboard_fixture(CONTROLS[1]).await;+ if canceled {+ assert!(evaluate_bool(&mut ctx, "(__cancel = 'beforeinput') !== ''").await);+ }+ dispatch(&mut ctx, route, key, "", "\r").await;+ assert_input_events(+ &mut ctx,+ "insertLineBreak",+ None,+ None,+ "",+ if canceled { "" } else { "\n" },+ canceled,+ )+ .await;+ }+ }+}++#[tokio::test(flavor = "multi_thread")]+async fn cdp_text_editing_input_data_reflects_maxlength_and_single_line_normalization() {+ for control in &CONTROLS[..2] {+ for (text, inserted) in [("abc", "ab"), ("πX", "π"), ("a\rb", "a ")] {+ if *control == CONTROLS[1] && text.contains('\r') {+ continue;+ }+ let mut ctx = keyboard_fixture(control).await;+ assert!(+ evaluate_bool(+ &mut ctx,+ "(document.getElementById('field').maxLength = 2) === 2"+ )+ .await+ );+ dispatch(&mut ctx, "char", "", "", text).await;+ assert_input_events(+ &mut ctx,+ "insertText",+ Some(text),+ Some(inserted),+ "",+ inserted,+ false,+ )+ .await;+ }+ }+}+#[tokio::test(flavor = "multi_thread")]async fn cdp_keyboard_event_types_preserve_character_dispatch_and_editing_order() {for control in CONTROLS {diff --git a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs b/moli-renderer-v8/src/native_bridge/document/lifecycle.rsindex 90c206d0c..7e4f77c32 100644--- a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs+++ b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs@@ -7,7 +7,7 @@ use super::{JsContextHost, detached_native_handle_for_runtime, is_html_document, throw_dom_exception,};use crate::native_bridge::element::{- contenteditable_editing_host, dispatch_text_control_event, is_text_control,+ TextEditInputType, contenteditable_editing_host, dispatch_text_control_event, is_text_control,queue_text_control_document_selection_change_event, replace_contenteditable_selection,replace_text_control_selection, text_control_value,};@@ -480,12 +480,24 @@ fn exec_command_insert_text(return false;};if is_text_control(unsafe { &*runtime_ptr }, active) {- return replace_text_control_selection(scope, runtime_ptr, active, replacement);+ return replace_text_control_selection(+ scope,+ runtime_ptr,+ active,+ replacement,+ TextEditInputType::InsertText,+ );}let Some(editing_host) = contenteditable_editing_host(unsafe { &*runtime_ptr }, active) else {return false;};- replace_contenteditable_selection(scope, runtime_ptr, editing_host, replacement)+ replace_contenteditable_selection(+ scope,+ runtime_ptr,+ editing_host,+ replacement,+ TextEditInputType::InsertText,+ )}pub(in crate::native_bridge) fn node_document_query_command_supported_callback<'s>(diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rsindex 07c93d79c..fc865fc9f 100644--- a/moli-renderer-v8/src/native_bridge/element.rs+++ b/moli-renderer-v8/src/native_bridge/element.rs@@ -199,8 +199,8 @@ use event_handlers::{pub(in crate::native_bridge::element) use events::construct_event;pub(crate) use events::construct_focus_event;pub(crate) use events::{- NodePublicEventDispatchOutcome, TouchEventPoint, construct_beforeinput_event,- construct_command_event, construct_drag_event, construct_interest_event,+ NodePublicEventDispatchOutcome, TextEditInputType, TouchEventPoint, construct_command_event,+ construct_drag_event, construct_input_event, construct_interest_event,construct_keyboard_event, construct_mouse_event_with_detail_and_modifiers,construct_mouse_event_with_modifiers, construct_mouse_event_with_related_target_and_modifiers,construct_pointer_event, construct_pointer_event_with_modifiers,diff --git a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rsindex eaf257562..8818d2181 100644--- a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs+++ b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs@@ -23,12 +23,12 @@ use crate::{use super::super::super::JsContextHost;use super::super::forms::{FormAssociatedResetCallbackTiming, reset_form_default_action};use super::super::{- NodePublicEventDispatchOutcome, cache_input_files_from_selected_files,+ NodePublicEventDispatchOutcome, TextEditInputType, cache_input_files_from_selected_files,construct_click_event_with_detail_and_modifiers, construct_command_event,- construct_simple_event, contenteditable_editing_host, dispatch_popover_toggle_events,- dispatch_public_event, element_attribute, element_has_attribute, form_associated_form_owner,- is_disabled_form_control, is_focusable, is_valid_submit_button,- label_activation_control_handle, observable_bounding_client_rect,+ construct_input_event, construct_simple_event, contenteditable_editing_host,+ dispatch_popover_toggle_events, dispatch_public_event, element_attribute,+ element_has_attribute, form_associated_form_owner, is_disabled_form_control, is_focusable,+ is_valid_submit_button, label_activation_control_handle, observable_bounding_client_rect,perform_popover_invoker_default_action, perform_summary_click_default_action,replace_text_control_selection, resolve_url_like_attribute,resolved_reflected_element_attribute_handle, scroll_node_into_view_at_start,@@ -215,7 +215,13 @@ fn perform_text_drop_default_action(if text.is_empty() {return false;}- replace_text_control_selection(scope, runtime_ptr, handle, &text)+ replace_text_control_selection(+ scope,+ runtime_ptr,+ handle,+ &text,+ TextEditInputType::InsertFromDrop,+ )}fn slice_chars(value: &str, start: usize, end: usize) -> String {@@ -536,15 +542,20 @@ pub(crate) fn replace_contenteditable_selection(runtime_ptr: *mut JsContextHost,handle: DomHandle,replacement_text: &str,+ input_type: TextEditInputType,) -> bool {let Some(target) = node_wrapper_from_handle(scope, handle) else {return false;};- let Some(before_input) = construct_simple_event(scope, "beforeinput", true, true, true) else {+ let Some(before_input) = construct_input_event(+ scope,+ "beforeinput",+ input_type,+ input_type.data(replacement_text),+ ) else {return false;};- let _ = dispatch_public_event(scope, runtime_ptr, handle, before_input);- if event_default_prevented(scope, before_input) {+ if !dispatch_public_event(scope, runtime_ptr, handle, before_input).allows_default() {return false;}let inserted = if let Some(selection) = window_selection(scope) {@@ -570,7 +581,12 @@ pub(crate) fn replace_contenteditable_selection(if !inserted {return false;}- if let Some(event) = construct_simple_event(scope, "input", true, false, true) {+ if let Some(event) = construct_input_event(+ scope,+ "input",+ input_type,+ input_type.data(replacement_text),+ ) {let _ = dispatch_public_event(scope, runtime_ptr, handle, event);}truediff --git a/moli-renderer-v8/src/native_bridge/element/events.rs b/moli-renderer-v8/src/native_bridge/element/events.rsindex 67742edd5..823d5cd91 100644--- a/moli-renderer-v8/src/native_bridge/element/events.rs+++ b/moli-renderer-v8/src/native_bridge/element/events.rs@@ -5,8 +5,8 @@ mod dispatch;pub(crate) use self::constructors::construct_focus_event;pub(crate) use self::constructors::{- TouchEventPoint, construct_beforeinput_event, construct_command_event, construct_drag_event,- construct_interest_event, construct_keyboard_event,+ TextEditInputType, TouchEventPoint, construct_command_event, construct_drag_event,+ construct_input_event, construct_interest_event, construct_keyboard_event,construct_mouse_event_with_detail_and_modifiers, construct_mouse_event_with_modifiers,construct_mouse_event_with_related_target_and_modifiers, construct_pointer_event,construct_pointer_event_with_modifiers, construct_pointer_event_with_related_target,diff --git a/moli-renderer-v8/src/native_bridge/element/events/constructors.rs b/moli-renderer-v8/src/native_bridge/element/events/constructors.rsindex 25bdc3e8f..ed89fe9fe 100644--- a/moli-renderer-v8/src/native_bridge/element/events/constructors.rs+++ b/moli-renderer-v8/src/native_bridge/element/events/constructors.rs@@ -131,6 +131,37 @@ struct InputEventInitDeclaration<'scope> {cancelable: bool,composed: bool,input_type: v8::Local<'scope, v8::String>,+ data: v8::Local<'scope, v8::Value>,+}++#[derive(Clone, Copy)]+pub(crate) enum TextEditInputType {+ InsertText,+ InsertLineBreak,+ InsertFromDrop,+ DeleteContentBackward,+ DeleteContentForward,+}++impl TextEditInputType {+ fn as_str(self) -> &'static str {+ match self {+ Self::InsertText => "insertText",+ Self::InsertLineBreak => "insertLineBreak",+ Self::InsertFromDrop => "insertFromDrop",+ Self::DeleteContentBackward => "deleteContentBackward",+ Self::DeleteContentForward => "deleteContentForward",+ }+ }++ pub(crate) fn data(self, text: &str) -> Option<&str> {+ match self {+ Self::InsertText | Self::InsertFromDrop => Some(text),+ Self::InsertLineBreak | Self::DeleteContentBackward | Self::DeleteContentForward => {+ None+ }+ }+ }}fn keyboard_event_legacy_codes(event_type: &str, key: &str, code: &str) -> (u32, u32, u32) {@@ -761,15 +792,22 @@ pub(crate) fn construct_focus_event<'s>(construct_event(scope, "FocusEvent", event_type, init)}-pub(crate) fn construct_beforeinput_event<'s>(+pub(crate) fn construct_input_event<'s>(scope: &mut v8::PinScope<'s, '_>,- input_type: &str,+ event_type: &str,+ input_type: TextEditInputType,+ data: Option<&str>,) -> Option<v8::Local<'s, v8::Object>> {- let input_type = v8_string(scope, input_type)?;- let init = InputEventInitDeclaration::new(true, true, true, input_type)- .bind(scope)- .ok()?;- construct_event(scope, "InputEvent", "beforeinput", init)+ let input_type = v8_string(scope, input_type.as_str())?;+ let data = match data {+ Some(text) => v8_string(scope, text)?.into(),+ None => v8::null(scope).into(),+ };+ let init =+ InputEventInitDeclaration::new(true, event_type == "beforeinput", true, input_type, data)+ .bind(scope)+ .ok()?;+ construct_event(scope, "InputEvent", event_type, init)}pub(crate) fn construct_simple_event<'s>(diff --git a/moli-renderer-v8/src/native_bridge/element/forms/text_control/selection.rs b/moli-renderer-v8/src/native_bridge/element/forms/text_control/selection.rsindex 968abfbaf..d6cbceafb 100644--- a/moli-renderer-v8/src/native_bridge/element/forms/text_control/selection.rs+++ b/moli-renderer-v8/src/native_bridge/element/forms/text_control/selection.rs@@ -1,12 +1,11 @@-use super::events::{- dispatch_text_control_event, queue_text_control_select_event,- queue_text_control_selection_change_event,-};+use super::events::{queue_text_control_select_event, queue_text_control_selection_change_event};use super::value::{- clamp_text_control_offset, is_text_control, supports_variable_length_selection,+ clamp_text_control_offset, is_text_control, normalize_textarea_api_value,+ supports_variable_length_selection,};use super::*;use crate::dom::forms::parse_non_negative_length_attribute;+use crate::native_bridge::element::{TextEditInputType, construct_input_event};use crate::util::{utf16_replace_units_range_lossy, utf16_units, v8str};use crate::webidl;@@ -70,15 +69,6 @@ fn text_control_selection_idl_owner(runtime: &JsContextHost, handle: DomHandle).unwrap_or("HTMLInputElement")}-fn event_default_prevented(- scope: &mut v8::PinScope<'_, '_>,- event: v8::Local<'_, v8::Object>,-) -> bool {- event- .get(scope, v8str(scope, "defaultPrevented").into())- .is_some_and(|value| value.boolean_value(scope))-}-pub(crate) fn text_control_set_selection_range_internal(scope: &mut v8::PinScope<'_, '_>,runtime_ptr: *mut JsContextHost,@@ -125,16 +115,21 @@ pub(crate) fn replace_text_control_selection(runtime_ptr: *mut JsContextHost,handle: DomHandle,replacement_text: &str,+ input_type: TextEditInputType,) -> bool {if !is_text_control(unsafe { &*runtime_ptr }, handle) {return false;}- let Some(before_input) = construct_simple_event(scope, "beforeinput", true, true, true) else {+ let Some(before_input) = construct_input_event(+ scope,+ "beforeinput",+ input_type,+ input_type.data(replacement_text),+ ) else {return false;};- let _ = dispatch_public_event(scope, runtime_ptr, handle, before_input);- if event_default_prevented(scope, before_input) {+ if !dispatch_public_event(scope, runtime_ptr, handle, before_input).allows_default() {return false;}@@ -187,7 +182,14 @@ pub(crate) fn replace_text_control_selection(let selection_changed =text_control_set_selection_range_internal(scope, runtime_ptr, handle, caret, caret);if changed || selection_changed {- dispatch_text_control_event(scope, runtime_ptr, handle, "input");+ // beforeinput describes the request; input describes the text actually+ // inserted after single-line normalization and maxlength truncation.+ let inserted_text = String::from_utf16_lossy(&replacement_units);+ if let Some(event) =+ construct_input_event(scope, "input", input_type, input_type.data(&inserted_text))+ {+ let _ = dispatch_public_event(scope, runtime_ptr, handle, event);+ }}changed || selection_changed}@@ -206,7 +208,7 @@ fn text_control_user_edit_replacement_units(let replacement_text = if element.is_html_input() {normalize_single_line_text_insertion(replacement_text)} else {- replacement_text.to_owned()+ normalize_textarea_api_value(replacement_text)};let mut replacement_units = utf16_units(&replacement_text);diff --git a/moli-renderer-v8/src/script_vm/input_dispatch.rs b/moli-renderer-v8/src/script_vm/input_dispatch.rsindex 8472629c6..43fed60b7 100644--- a/moli-renderer-v8/src/script_vm/input_dispatch.rs+++ b/moli-renderer-v8/src/script_vm/input_dispatch.rs@@ -17,10 +17,10 @@ use crate::dom::{native::{Node, SelectedFile},};use crate::native_bridge::element::{- TouchEventPoint, activate_default_submit_button_via_keyboard,+ TextEditInputType, TouchEventPoint, activate_default_submit_button_via_keyboard,activate_handle_after_pointer_release, activate_handle_via_click,activate_handle_via_click_with_detail_and_modifiers, cache_input_files_from_selected_files,- construct_beforeinput_event, construct_drag_event, construct_keyboard_event,+ construct_drag_event, construct_input_event, construct_keyboard_event,construct_mouse_event_with_detail_and_modifiers, construct_mouse_event_with_modifiers,construct_mouse_event_with_related_target_and_modifiers, construct_pointer_event,construct_pointer_event_with_modifiers, construct_pointer_event_with_related_target,@@ -1852,7 +1852,13 @@ impl ScriptVm {let result = self.with_default_context_scope(|scope, runtime_ptr| {if is_text_control(unsafe { &*runtime_ptr }, handle) {- let _ = replace_text_control_selection(scope, runtime_ptr, handle, text);+ let _ = replace_text_control_selection(+ scope,+ runtime_ptr,+ handle,+ text,+ TextEditInputType::InsertText,+ );return Ok(true);}let runtime = unsafe { &*runtime_ptr };@@ -1864,6 +1870,7 @@ impl ScriptVm {runtime_ptr,editing_host,text,+ TextEditInputType::InsertText,))});self.finish_input_command_checkpoint(result)@@ -1975,13 +1982,18 @@ impl ScriptVm {runtime_ptr,handle,"\n",+ TextEditInputType::InsertLineBreak,)));}if input_blocks_implicit_submission(runtime, handle) && is_character_phase {// Enter's editing default action must remain cancelable before// activating a default submit button (and firing its click).- let Some(before_input) = construct_beforeinput_event(scope, "insertLineBreak")- else {+ let Some(before_input) = construct_input_event(+ scope,+ "beforeinput",+ TextEditInputType::InsertLineBreak,+ None,+ ) else {return Ok(input_dispatch_outcome(false));};if !dispatch_public_event(scope, runtime_ptr, handle, before_input)@@ -2016,20 +2028,12 @@ impl ScriptVm {return Ok(input_dispatch_outcome(true));}if target.is_text_control {- if target.is_textarea && text.contains('\r') {- let normalized_text = text.replace("\r\n", "\n").replace('\r', "\n");- return Ok(input_dispatch_outcome(replace_text_control_selection(- scope,- runtime_ptr,- handle,- &normalized_text,- )));- }return Ok(input_dispatch_outcome(replace_text_control_selection(scope,runtime_ptr,handle,text,+ TextEditInputType::InsertText,)));}if let Some(editing_host) = contenteditable_editing_host(runtime, handle) {@@ -2038,6 +2042,7 @@ impl ScriptVm {runtime_ptr,editing_host,text,+ TextEditInputType::InsertText,)));}return Ok(input_dispatch_outcome(true));@@ -2197,6 +2202,11 @@ impl ScriptVm {runtime_ptr,handle,"",+ if key_lower == "backspace" {+ TextEditInputType::DeleteContentBackward+ } else {+ TextEditInputType::DeleteContentForward+ },)));}@@ -2230,6 +2240,11 @@ impl ScriptVm {runtime_ptr,editing_host,"",+ if key_lower == "backspace" {+ TextEditInputType::DeleteContentBackward+ } else {+ TextEditInputType::DeleteContentForward+ },)));}