Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(input): preserve CDP keypress and raw keydown semantics

ldm066563c6399c3
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.md
index 6ea75681f..a642d5084 100644
--- a/moli-cdp-smoke/README.md
+++ b/moli-cdp-smoke/README.md
@@ -145,6 +145,12 @@ workers can partition that selected list with the one-based
The current suite is a strong core smoke gate, not a complete Playwright compatibility suite.
+The `dom-input` keypress contract was calibrated on 2026-09-08 against
+headed Debian Chromium 145.0.7632.116 through CDP. It checks the full trusted
+`keydown -> keypress -> beforeinput -> input -> keyup` sequence for Playwright
+typing, cancellation at keypress, the distinct `rawKeyDown` and `char` paths,
+and the absence of keyboard events for `Input.insertText`.
+
The default `webgl-viewport` group was calibrated on 2026-09-07 against
Debian `/usr/bin/chromium` 145.0.7632.116. It uses the same fixture as the
renderer tests to check WebGL1/2 on HTML and
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py b/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py
index 7c8cef521..44dac5002 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py
@@ -192,6 +192,7 @@ async def run_dom_input_group(state: SmokeState) -> None:
await run_playwright_expect_matcher_workflows(state)
await run_locator_composition_workflows(state)
await run_keyboard_editing_workflows(state)
+ await run_keypress_dispatch_workflow(state)
await run_cdp_control_key_name_workflow(state)
await run_cdp_input_navigation_replacement_workflows(state)
await run_mouse_event_workflows(state)
@@ -974,6 +975,80 @@ async def run_keyboard_editing_workflows(state: SmokeState) -> None:
state.record("playwright_keyboard_editing_workflows")
+async def run_keypress_dispatch_workflow(state: SmokeState) -> None:
+ page = await state.context.new_page()
+ session = None
+ try:
+ await page.set_content("""
+ <input id="field">
+ <script>
+ window.__keyEvents = [];
+ window.__cancelAt = false;
+ for (const type of ['keydown', 'keypress', 'beforeinput', 'input', 'keyup']) {
+ document.getElementById('field').addEventListener(type, event => {
+ __keyEvents.push({type, trusted: event.isTrusted});
+ if (__cancelAt && type === 'keypress' && event.key === '@')
+ event.preventDefault();
+ });
+ }
+ </script>
+ """)
+ session = await state.context.new_cdp_session(page)
+ full_sequence = ["keydown", "keypress", "beforeinput", "input", "keyup"]
+
+ async def reset(cancel_at: bool = False) -> None:
+ await page.evaluate("""cancelAt => {
+ const field = document.getElementById('field');
+ field.value = '';
+ field.focus();
+ window.__keyEvents = [];
+ window.__cancelAt = cancelAt;
+ }""", cancel_at)
+
+ async def check(value: str, event_types: list[str], label: str) -> None:
+ assert_equal(
+ await page.evaluate("""() => ({
+ value: document.getElementById('field').value,
+ events: __keyEvents,
+ })"""),
+ {"value": value, "events": [{"type": kind, "trusted": True} for kind in event_types]},
+ label,
+ )
+
+ await reset()
+ await page.keyboard.type("a@A")
+ await check("a@A", full_sequence * 3, "Playwright type emits a trusted keypress for every character")
+
+ await reset(cancel_at=True)
+ await page.keyboard.type("a@A")
+ await check(
+ "aA", full_sequence + ["keydown", "keypress", "keyup"] + full_sequence,
+ "canceling keypress prevents only that character's input",
+ )
+
+ for kind, value, event_types in [
+ ("rawKeyDown", "", ["keydown", "keyup"]),
+ ("char", "a", ["keypress", "beforeinput", "input", "keyup"]),
+ ]:
+ await reset()
+ await session.send("Input.dispatchKeyEvent", {
+ "type": kind, "key": "a", "code": "KeyA", "text": "a", "windowsVirtualKeyCode": 65,
+ })
+ await session.send("Input.dispatchKeyEvent", {
+ "type": "keyUp", "key": "a", "code": "KeyA", "windowsVirtualKeyCode": 65,
+ })
+ await check(value, event_types, f"CDP {kind} preserves its character-event semantics")
+
+ await reset()
+ await session.send("Input.insertText", {"text": "a"})
+ await check("a", ["beforeinput", "input"], "insertText does not synthesize keyboard events")
+ state.record("playwright_and_cdp_keypress_dispatch")
+ finally:
+ if session is not None:
+ await session.detach()
+ await page.close()
+
+
async def run_cdp_control_key_name_workflow(state: SmokeState) -> None:
page = await state.context.new_page()
session = None
diff --git a/moli-protocol/src/domains/input/key.rs b/moli-protocol/src/domains/input/key.rs
index 5dc827bfb..00552a38b 100644
--- a/moli-protocol/src/domains/input/key.rs
+++ b/moli-protocol/src/domains/input/key.rs
@@ -48,17 +48,17 @@ pub(super) fn parse_dispatch_key_event(
return Err("InvalidParams");
};
- let cdp_event_type = params.r#type.clone();
- let event_type = match cdp_event_type {
- KeyEventType::KeyDown | KeyEventType::RawKeyDown => DevToolsKeyEventType::KeyDown,
- KeyEventType::KeyUp => DevToolsKeyEventType::KeyUp,
- KeyEventType::Char => DevToolsKeyEventType::KeyPress,
+ // keyDown combines a DOM keydown with a character phase; rawKeyDown
+ // dispatches only keydown, even when the client supplies text.
+ let (event_type, should_insert_text) = match params.r#type {
+ KeyEventType::KeyDown => (
+ DevToolsKeyEventType::KeyDown,
+ params.text.as_deref().is_some_and(|text| !text.is_empty()),
+ ),
+ KeyEventType::RawKeyDown => (DevToolsKeyEventType::KeyDown, false),
+ KeyEventType::KeyUp => (DevToolsKeyEventType::KeyUp, false),
+ KeyEventType::Char => (DevToolsKeyEventType::KeyPress, true),
};
- let should_insert_text = cdp_event_type == KeyEventType::Char
- || matches!(
- cdp_event_type,
- KeyEventType::KeyDown | KeyEventType::RawKeyDown
- ) && params.text.as_deref().is_some_and(|text| !text.is_empty());
Ok(ParsedDispatchKeyEvent {
event_type,
diff --git a/moli-protocol/src/domains/input/tests.rs b/moli-protocol/src/domains/input/tests.rs
index 328d84308..3de7b7aec 100644
--- a/moli-protocol/src/domains/input/tests.rs
+++ b/moli-protocol/src/domains/input/tests.rs
@@ -3,6 +3,8 @@ use crate::conn::{BrowserContext, CdpCommandTaskStep, CommandDispatchContext};
use crate::testing::{TestContext, wait_until_frame_stopped_loading};
use moli_core::LayoutPolicy;
+mod keyboard_events;
+
const INPUT_HIT_X: u32 = 20;
const INPUT_HIT_Y: u32 = 20;
diff --git a/moli-protocol/src/domains/input/tests/keyboard_events.rs b/moli-protocol/src/domains/input/tests/keyboard_events.rs
new file mode 100644
index 000000000..06033c61f
--- /dev/null
+++ b/moli-protocol/src/domains/input/tests/keyboard_events.rs
@@ -0,0 +1,195 @@
+use super::*;
+
+const CONTROLS: [&str; 3] = [
+ "<input id='field'>",
+ "<textarea id='field'></textarea>",
+ "<div id='field' contenteditable='true'></div>",
+];
+
+async fn keyboard_fixture(control: &str) -> TestContext {
+ let mut ctx = TestContext::new();
+ let html = r#"<html><body>CONTROL<input id='other'><script>
+ window.__events = [];
+ window.__keypresses = [];
+ window.__cancel = '';
+ window.__moveFocus = false;
+ for (const type of ['keydown', 'keypress', 'beforeinput', 'input', 'keyup']) {
+ document.addEventListener(type, event => {
+ __events.push(event.type + ':' + event.target.id);
+ if (type === 'keypress') {
+ __keypresses.push({key: event.key, code: event.code,
+ keyCode: event.keyCode, charCode: event.charCode,
+ which: event.which, trusted: event.isTrusted});
+ }
+ if (type === __cancel) event.preventDefault();
+ if (type === 'keydown' && __moveFocus)
+ document.getElementById('other').focus();
+ });
+ }
+ document.getElementById('field').focus();
+ </script></body></html>"#
+ .replace("CONTROL", control);
+ with_loaded_document(&mut ctx, &html).await;
+ ctx
+}
+
+async fn dispatch(ctx: &mut TestContext, event_type: &str, key: &str, code: &str, text: &str) {
+ ctx.process_async(json!({
+ "id": 901,
+ "method": "Input.dispatchKeyEvent",
+ "params": {"type": event_type, "key": key, "code": code, "text": text}
+ }))
+ .await;
+ ctx.expect_result(901, json!({}), None);
+}
+
+async fn field_value(ctx: &mut TestContext) -> String {
+ evaluate_string(
+ ctx,
+ "document.getElementById('field').value ?? document.getElementById('field').textContent",
+ )
+ .await
+}
+
+async fn events(ctx: &mut TestContext) -> serde_json::Value {
+ serde_json::from_str(&evaluate_string(ctx, "JSON.stringify(__events)").await)
+ .expect("event log must be JSON")
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn cdp_keyboard_event_types_preserve_character_dispatch_and_editing_order() {
+ for control in CONTROLS {
+ for (event_type, text, expected_value, expected_events) in [
+ (
+ "keyDown",
+ "a",
+ "a",
+ vec!["keydown", "keypress", "beforeinput", "input", "keyup"],
+ ),
+ ("rawKeyDown", "a", "", vec!["keydown", "keyup"]),
+ (
+ "char",
+ "a",
+ "a",
+ vec!["keypress", "beforeinput", "input", "keyup"],
+ ),
+ ("keyDown", "", "", vec!["keydown", "keyup"]),
+ ] {
+ let mut ctx = keyboard_fixture(control).await;
+ dispatch(&mut ctx, event_type, "a", "KeyA", text).await;
+ dispatch(&mut ctx, "keyUp", "a", "KeyA", "").await;
+ assert_eq!(
+ field_value(&mut ctx).await,
+ expected_value,
+ "{control}: {event_type}"
+ );
+ assert_eq!(
+ events(&mut ctx).await,
+ json!(
+ expected_events
+ .iter()
+ .map(|event| format!("{event}:field"))
+ .collect::<Vec<_>>()
+ ),
+ "{control}: {event_type}"
+ );
+ }
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn cdp_combined_keydown_honors_each_cancellation_boundary() {
+ for control in CONTROLS {
+ for (cancel, expected) in [
+ ("keydown", vec!["keydown", "keyup"]),
+ ("keypress", vec!["keydown", "keypress", "keyup"]),
+ (
+ "beforeinput",
+ vec!["keydown", "keypress", "beforeinput", "keyup"],
+ ),
+ ] {
+ let mut ctx = keyboard_fixture(control).await;
+ assert!(
+ evaluate_bool(&mut ctx, &format!("(__cancel = '{cancel}') === '{cancel}'")).await
+ );
+ dispatch(&mut ctx, "keyDown", "a", "KeyA", "a").await;
+ dispatch(&mut ctx, "keyUp", "a", "KeyA", "").await;
+ assert_eq!(
+ field_value(&mut ctx).await,
+ "",
+ "{control}: cancel {cancel}"
+ );
+ assert_eq!(
+ events(&mut ctx).await,
+ json!(
+ expected
+ .iter()
+ .map(|event| format!("{event}:field"))
+ .collect::<Vec<_>>()
+ ),
+ "{control}: cancel {cancel}"
+ );
+ }
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn cdp_combined_keydown_delivers_trusted_keypresses_for_typed_characters() {
+ let mut ctx = keyboard_fixture(CONTROLS[0]).await;
+ for (key, code) in [("a", "KeyA"), ("@", "Digit2"), ("A", "KeyA")] {
+ dispatch(&mut ctx, "keyDown", key, code, key).await;
+ dispatch(&mut ctx, "keyUp", key, code, "").await;
+ }
+ assert_eq!(field_value(&mut ctx).await, "a@A");
+ let observed: serde_json::Value =
+ serde_json::from_str(&evaluate_string(&mut ctx, "JSON.stringify(__keypresses)").await)
+ .expect("keypress log must be JSON");
+ assert_eq!(
+ observed,
+ json!([
+ {"key":"a", "code":"KeyA", "keyCode":97, "charCode":97, "which":97, "trusted":true},
+ {"key":"@", "code":"Digit2", "keyCode":64, "charCode":64, "which":64, "trusted":true},
+ {"key":"A", "code":"KeyA", "keyCode":65, "charCode":65, "which":65, "trusted":true}
+ ])
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn cdp_combined_keydown_refetches_focus_before_keypress() {
+ let mut ctx = keyboard_fixture(CONTROLS[0]).await;
+ assert!(evaluate_bool(&mut ctx, "__moveFocus = true").await);
+ dispatch(&mut ctx, "keyDown", "a", "KeyA", "a").await;
+ dispatch(&mut ctx, "keyUp", "a", "KeyA", "").await;
+ assert_eq!(field_value(&mut ctx).await, "");
+ assert_eq!(
+ evaluate_string(&mut ctx, "document.getElementById('other').value").await,
+ "a"
+ );
+ assert_eq!(
+ events(&mut ctx).await,
+ json!([
+ "keydown:field",
+ "keypress:other",
+ "beforeinput:other",
+ "input:other",
+ "keyup:other"
+ ])
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn cdp_insert_text_does_not_manufacture_keyboard_events() {
+ for control in CONTROLS {
+ let mut ctx = keyboard_fixture(control).await;
+ ctx.process_async(json!({
+ "id": 902, "method": "Input.insertText", "params": {"text": "a"}
+ }))
+ .await;
+ ctx.expect_result(902, json!({}), None);
+ assert_eq!(field_value(&mut ctx).await, "a");
+ assert_eq!(
+ events(&mut ctx).await,
+ json!(["beforeinput:field", "input:field"])
+ );
+ }
+}
diff --git a/moli-renderer-v8/src/script_vm/input_dispatch.rs b/moli-renderer-v8/src/script_vm/input_dispatch.rs
index 848c708a3..d638d12b3 100644
--- a/moli-renderer-v8/src/script_vm/input_dispatch.rs
+++ b/moli-renderer-v8/src/script_vm/input_dispatch.rs
@@ -1831,6 +1831,40 @@ impl ScriptVm {
return Ok(input_dispatch_outcome(false));
}
+ // Combined keydown/text input includes a cancelable keypress before
+ // editing. Keep both events in this input turn; an explicit char
+ // command already dispatched keypress and must not emit it twice.
+ let handle = if event_name == "keydown" && should_insert_text && !text.is_empty() {
+ // Like Blink's KeyboardEventManager, resolve focus again after
+ // keydown listeners before targeting the character event.
+ let runtime = unsafe { &*runtime_ptr };
+ let Some(handle) = runtime
+ .active_element_handle()
+ .or_else(|| runtime.document_focus_fallback_handle())
+ else {
+ return Ok(input_dispatch_outcome(false));
+ };
+ let Some(keypress) = construct_keyboard_event(
+ scope,
+ "keypress",
+ key,
+ code,
+ alt,
+ ctrl,
+ meta,
+ shift,
+ auto_repeat,
+ ) else {
+ return Ok(input_dispatch_outcome(false));
+ };
+ if !dispatch_public_event(scope, runtime_ptr, handle, keypress).allows_default() {
+ return Ok(input_dispatch_outcome(false));
+ }
+ handle
+ } else {
+ handle
+ };
+
let runtime = unsafe { &mut *runtime_ptr };
let target = key_target_info(runtime, handle);