Stealth browser automation for AI agents over MCP and the Chrome DevTools Protocol: navigation, network hooks, DOM extraction, and pixel-accurate UI cloning.
Python ai-agent-toolsai-toolsanthropicanti-bot-bypassautomation-toolsbrowser-automationchrome-devtoolsclaude-mcpcloudflare-bypassdeveloper-toolsfastmcpmcp-servermodel-context-protocolnetwork-interceptionnodriverpythonstealth-browserundetectable-browserweb-automationweb-scraping
feat(element-interaction): add press_key tool (trusted CDP key events)
JosueM11092d0541f94488
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f912c3d..3a2e93b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,17 @@ All notable changes to this project will be documented in this file.The format is based on Keep a Changelog and adheres to Semantic Versioning where practical.+## [Unreleased]+### Added+- **`press_key()` tool** - Presses real keys through CDP `Input.dispatchKeyEvent`, producing trusted `keydown`/`keypress`/`keyup` events. Supports named keys (Enter, Tab, Escape, arrows, Backspace, Delete, Home, End, PageUp, PageDown, Space, F1-F12), single printable characters, modifier combinations (Shift, Control/Ctrl, Alt, Meta/Cmd), optional focus selector, repeat count, and inter-press delay.+- **Tests** - `tests/test_press_key.py` covers the key-to-CDP mapping, the modifier bitmask, and the dispatch sequence. A browser-backed test asserting `isTrusted` runs when `STEALTH_BROWSER_TESTS=1` is set.++### Changed+- `element-interaction` section now exposes 13 tools; full surface is 98 tools, minimal surface is 21.++### Notes+- `type_text(parse_newlines=True)` fakes Enter by writing `\n` into the input value and dispatching an untrusted JavaScript `KeyboardEvent`. React-select and typeahead widgets (Greenhouse, Ashby, Lever, Workday) ignore untrusted events and drop the value on blur. Use `press_key()` for those fields.+## [0.2.5] - 2026-02-10### Fixed- **MCP JSON-RPC Protocol Corruption** - All debug `print()` calls redirected from stdout to stderr, fixing tool hangs after `spawn_browser` and `navigate` (#8)diff --git a/README.md b/README.mdindex 2adeed7..eda516f 100644--- a/README.md+++ b/README.md@@ -122,13 +122,13 @@ Use promo code `RAPID10` for **10% off**.## Features- **Anti-bot resistance** - Has passed Cloudflare and Queue-It style challenges in testing; results vary by site, region, browser version, and detector version.-- **97 tools across 11 sections** - From basic navigation to advanced CDP function execution.-- **Modular loading** - Run the full 97-tool surface or a minimal 20-tool core; disable sections you do not need.+- **98 tools across 11 sections** - From basic navigation to advanced CDP function execution.+- **Modular loading** - Run the full 98-tool surface or a minimal 21-tool core; disable sections you do not need.- **Pixel-accurate element cloning** - Extract complete elements with CSS, DOM structure, events, animations, and assets via CDP.- **Network inspection** - Inspect requests, responses, headers, payloads, and captured bodies through your AI agent.- **Dynamic hook system** - Restricted Python hooks can intercept, block, redirect, fulfill, or modify request/response flows.- **CDP execution** - Run JavaScript, direct CDP commands, and pre-document scripts through trusted local MCP clients.-- **Instant text input** - Paste large content via CDP or type with human-like keystrokes and newline support.+- **Instant text input** - Paste large content via CDP, type with human-like keystrokes, or press real keys with trusted CDP key events.- **Cross-platform** - Windows, macOS, Linux, Docker, and CI environments with automatic browser/platform detection.- **Browser support** - Chrome, Chromium, and Microsoft Edge with automatic executable discovery.- **Clean MCP integration** - Works through standard MCP clients without custom brokers.@@ -250,14 +250,14 @@ Treat the MCP client or agent as the security principal. The recommended deploym## Modular Architecture-Choose exactly what functionality you need. Run the full 97-tool suite or strip it down to the 20-tool core.+Choose exactly what functionality you need. Run the full 98-tool suite or strip it down to the 21-tool core.| Mode | Tools | Use Case ||------|-------|----------|-| **Full** (default) | 97 | Complete browser automation and debugging |-| **Minimal** (`--minimal`) | 20 | Core browser automation and interaction |+| **Full** (default) | 98 | Complete browser automation and debugging |+| **Minimal** (`--minimal`) | 21 | Core browser automation and interaction || **Custom** (`--disable-*`) | Your choice | Disable specific sections |-| **Xpool safe** (`--xpool-safe`) | 83 | Disable CDP function tools that trigger `Runtime.enable` |+| **Xpool safe** (`--xpool-safe`) | 84 | Disable CDP function tools that trigger `Runtime.enable` |```bashpython src/server.py --minimal@@ -274,7 +274,7 @@ Use `--debug` or set `STEALTH_BROWSER_DEBUG=1` to enable verbose server diagnost| Section | Tools | Description ||---------|-------|-------------|| `browser-management` | 8 | Core browser operations |-| `element-interaction` | 12 | Page interaction and manipulation |+| `element-interaction` | 13 | Page interaction and manipulation || `element-extraction` | 9 | Element cloning and extraction || `file-extraction` | 9 | File-based extraction tools || `network-debugging` | 10 | Network monitoring and capture |@@ -371,7 +371,7 @@ client = Client(</details><details>-<summary><strong>Element Interaction (12)</strong></summary>+<summary><strong>Element Interaction (13)</strong></summary>| Tool | Description ||------|-------------|@@ -379,6 +379,7 @@ client = Client(| `click_element()` | Click an element || `type_text()` | Human-like typing with newline support || `paste_text()` | Instant text paste via CDP |+| `press_key()` | Press a real key with trusted CDP key events (Enter, Tab, arrows, modifiers) || `file_upload()` | Upload allowlisted local files to file inputs || `select_option()` | Select dropdown options || `get_element_state()` | Inspect element state |@@ -554,8 +555,8 @@ Detection results are point-in-time and depend on site policy, region, browser v| Network debugging | Full request/response inspection through AI tools | Basic || API reverse engineering | Payload inspection through chat | Manual tools only || Dynamic hook system | Restricted Python hooks for real-time interception | Not available |-| Modular architecture | 11 sections, 20-97 tools | Fixed tool surface |-| Total tools | 97 customizable tools | About 20 |+| Modular architecture | 11 sections, 21-98 tools | Fixed tool surface |+| Total tools | 98 customizable tools | About 20 |---diff --git a/skills/stealth-browser-mcp/SKILL.md b/skills/stealth-browser-mcp/SKILL.mdindex e8ff887..9df7d88 100644--- a/skills/stealth-browser-mcp/SKILL.md+++ b/skills/stealth-browser-mcp/SKILL.md@@ -18,6 +18,7 @@ description: Use this skill when operating stealth-browser-mcp from an AI agent- Use `--minimal` when an agent only needs browser spawning, navigation, screenshots, page content, and basic interaction.- Use full mode for CDP execution, network debugging, cookie/storage work, dynamic hooks, and advanced element extraction.+- Use `press_key` when a widget needs a real key event, such as Enter or arrow keys in a react-select or typeahead field. Those widgets ignore the synthetic events produced by `type_text(parse_newlines=True)` and discard the value on blur.- Use `execute_script` for normal page JavaScript.- Use `execute_cdp_command` only when a CDP primitive is required or when page JavaScript cannot access the needed browser state.- Use network tools after navigation starts: `list_network_requests`, `search_network_requests`, `get_request_details`, `get_response_details`, and `get_response_content`.diff --git a/src/dom_handler.py b/src/dom_handler.pyindex bb83d93..a98742a 100644--- a/src/dom_handler.py+++ b/src/dom_handler.py@@ -13,6 +13,147 @@ from models import ElementInfo, ElementAction+MODIFIER_ALT = 1+MODIFIER_CONTROL = 2+MODIFIER_META = 4+MODIFIER_SHIFT = 8++MODIFIER_ALIASES: Dict[str, tuple] = {+ "alt": ("Alt", MODIFIER_ALT),+ "option": ("Alt", MODIFIER_ALT),+ "control": ("Control", MODIFIER_CONTROL),+ "ctrl": ("Control", MODIFIER_CONTROL),+ "meta": ("Meta", MODIFIER_META),+ "cmd": ("Meta", MODIFIER_META),+ "command": ("Meta", MODIFIER_META),+ "shift": ("Shift", MODIFIER_SHIFT),+}++NAMED_KEYS: Dict[str, tuple] = {+ "enter": ("Enter", "Enter", 13, "\r"),+ "tab": ("Tab", "Tab", 9, None),+ "escape": ("Escape", "Escape", 27, None),+ "arrowdown": ("ArrowDown", "ArrowDown", 40, None),+ "arrowup": ("ArrowUp", "ArrowUp", 38, None),+ "arrowleft": ("ArrowLeft", "ArrowLeft", 37, None),+ "arrowright": ("ArrowRight", "ArrowRight", 39, None),+ "backspace": ("Backspace", "Backspace", 8, None),+ "delete": ("Delete", "Delete", 46, None),+ "home": ("Home", "Home", 36, None),+ "end": ("End", "End", 35, None),+ "pageup": ("PageUp", "PageUp", 33, None),+ "pagedown": ("PageDown", "PageDown", 34, None),+ "space": (" ", "Space", 32, " "),+}++NAMED_KEYS.update({+ f"f{n}": (f"F{n}", f"F{n}", 111 + n, None) for n in range(1, 13)+})++PRINTABLE_KEY_CODES: Dict[str, tuple] = {+ " ": ("Space", 32),+ "-": ("Minus", 189), "_": ("Minus", 189),+ "=": ("Equal", 187), "+": ("Equal", 187),+ "[": ("BracketLeft", 219), "{": ("BracketLeft", 219),+ "]": ("BracketRight", 221), "}": ("BracketRight", 221),+ "\\": ("Backslash", 220), "|": ("Backslash", 220),+ ";": ("Semicolon", 186), ":": ("Semicolon", 186),+ "'": ("Quote", 222), '"': ("Quote", 222),+ ",": ("Comma", 188), "<": ("Comma", 188),+ ".": ("Period", 190), ">": ("Period", 190),+ "/": ("Slash", 191), "?": ("Slash", 191),+ "`": ("Backquote", 192), "~": ("Backquote", 192),+ "!": ("Digit1", 49), "@": ("Digit2", 50), "#": ("Digit3", 51),+ "$": ("Digit4", 52), "%": ("Digit5", 53), "^": ("Digit6", 54),+ "&": ("Digit7", 55), "*": ("Digit8", 56), "(": ("Digit9", 57),+ ")": ("Digit0", 48),+}+++def supported_key_names() -> List[str]:+ """List the named keys accepted by press_key, for error messages."""+ named = [+ "Enter", "Tab", "Escape", "ArrowDown", "ArrowUp", "ArrowLeft", "ArrowRight",+ "Backspace", "Delete", "Home", "End", "PageUp", "PageDown", "Space",+ ]+ return named + [f"F{n}" for n in range(1, 13)]+++def resolve_key_descriptor(key: str) -> Dict[str, Any]:+ """+ Map a DOM KeyboardEvent.key name or single printable character to CDP key fields.++ Args:+ key (str): Named key (Enter, ArrowDown, F5, ...) or a single printable character.++ Returns:+ Dict[str, Any]: { key, code, virtual_key_code, text } for Input.dispatchKeyEvent.+ """+ if not isinstance(key, str) or key == "":+ raise Exception(+ "Invalid key: key must be a non-empty string. "+ f"Supported named keys: {', '.join(supported_key_names())}. "+ "Any single printable character is also accepted."+ )++ if len(key) == 1 and key != " ":+ code, virtual_key_code = PRINTABLE_KEY_CODES.get(key, ("", 0))+ if not code:+ if key.isalpha() and key.upper() in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":+ code = f"Key{key.upper()}"+ virtual_key_code = ord(key.upper())+ elif key.isdigit():+ code = f"Digit{key}"+ virtual_key_code = ord(key)+ return {"key": key, "code": code, "virtual_key_code": virtual_key_code, "text": key}++ lookup = "space" if key == " " else key.strip().lower()+ named = NAMED_KEYS.get(lookup)+ if named is None:+ raise Exception(+ f"Unsupported key: {key!r}. "+ f"Supported named keys: {', '.join(supported_key_names())}. "+ "Any single printable character is also accepted."+ )++ dom_key, code, virtual_key_code, text = named+ return {"key": dom_key, "code": code, "virtual_key_code": virtual_key_code, "text": text}+++def resolve_modifiers(modifiers: Optional[List[str]]) -> tuple:+ """+ Combine modifier names into the CDP modifiers bitmask.++ Args:+ modifiers (Optional[List[str]]): Any of Shift, Control/Ctrl, Alt, Meta/Cmd.++ Returns:+ tuple: (bitmask int, canonical modifier names list).+ """+ if not modifiers:+ return 0, []++ if isinstance(modifiers, str):+ modifiers = [modifiers]++ mask = 0+ canonical: List[str] = []+ for modifier in modifiers:+ entry = MODIFIER_ALIASES.get(str(modifier).strip().lower())+ if entry is None:+ raise Exception(+ f"Unsupported modifier: {modifier!r}. "+ "Supported modifiers: Shift, Control (Ctrl), Alt, Meta (Cmd)."+ )+ name, bit = entry+ mask |= bit+ if name not in canonical:+ canonical.append(name)++ return mask, canonical+++class DOMHandler:"""Handles DOM queries and element interactions."""@@ -358,6 +499,85 @@ class DOMHandler:except Exception as e:raise Exception(f"Failed to paste text: {str(e)}")+ @staticmethod+ async def press_key(+ tab: Tab,+ key: str,+ modifiers: Optional[List[str]] = None,+ selector: Optional[str] = None,+ count: int = 1,+ delay_ms: int = 50+ ) -> Dict[str, Any]:+ """+ Press a real key using trusted CDP Input.dispatchKeyEvent events.++ Unlike synthetic JavaScript KeyboardEvents, these events are trusted by the+ page, so React-select, typeahead and other widgets that gate on+ `event.isTrusted` react to them.++ Args:+ tab (Tab): The browser tab object.+ key (str): DOM KeyboardEvent.key name (Enter, Tab, ArrowDown, F5, ...) or a single printable character.+ modifiers (Optional[List[str]]): Modifier keys to hold: Shift, Control/Ctrl, Alt, Meta/Cmd.+ selector (Optional[str]): CSS selector to focus before pressing. Presses on the active element when omitted.+ count (int): Number of times to press the key.+ delay_ms (int): Delay between presses in milliseconds.++ Returns:+ Dict[str, Any]: { success: True, key: str, count: int, modifiers: [str, ...] }+ """+ from nodriver import cdp++ try:+ if count < 1:+ raise Exception(f"Invalid count: {count}. Must be 1 or greater.")++ descriptor = resolve_key_descriptor(key)+ modifier_mask, canonical_modifiers = resolve_modifiers(modifiers)++ if selector:+ element = await tab.select(selector)+ if not element:+ raise Exception(f"Element not found: {selector}")+ await element.focus()+ await asyncio.sleep(0.1)++ text = descriptor["text"]+ if modifier_mask & ~MODIFIER_SHIFT:+ text = None++ for index in range(count):+ await tab.send(cdp.input_.dispatch_key_event(+ "keyDown",+ modifiers=modifier_mask,+ key=descriptor["key"],+ code=descriptor["code"],+ windows_virtual_key_code=descriptor["virtual_key_code"],+ native_virtual_key_code=descriptor["virtual_key_code"],+ text=text,+ unmodified_text=text+ ))+ await tab.send(cdp.input_.dispatch_key_event(+ "keyUp",+ modifiers=modifier_mask,+ key=descriptor["key"],+ code=descriptor["code"],+ windows_virtual_key_code=descriptor["virtual_key_code"],+ native_virtual_key_code=descriptor["virtual_key_code"]+ ))+ if index < count - 1:+ await asyncio.sleep(delay_ms / 1000)++ return {+ "success": True,+ "key": descriptor["key"],+ "count": count,+ "modifiers": canonical_modifiers+ }++ except Exception as e:+ raise Exception(f"Failed to press key: {str(e)}")+@staticmethodasync def file_upload(tab: Tab,diff --git a/src/server.py b/src/server.pyindex dd51e90..b5ad386 100644--- a/src/server.py+++ b/src/server.py@@ -516,6 +516,45 @@ async def paste_text(raise Exception(f"Instance not found: {instance_id}")return await dom_handler.paste_text(tab, selector, text, clear_first)+@section_tool("element-interaction")+async def press_key(+ instance_id: str,+ key: str,+ modifiers: Optional[List[str]] = None,+ selector: Optional[str] = None,+ count: int = 1,+ delay_ms: int = 50+) -> Dict[str, Any]:+ """+ Press a real key using trusted CDP key events.++ Sends Input.dispatchKeyEvent keyDown/keyUp pairs, so the page sees trusted+ events. Use this instead of type_text(parse_newlines=True) for React-select,+ typeahead and combobox widgets, which discard values set by synthetic+ JavaScript KeyboardEvents.++ Args:+ instance_id (str): Browser instance ID.+ key (str): DOM KeyboardEvent.key name (Enter, Tab, Escape, ArrowDown, ArrowUp, ArrowLeft, ArrowRight, Backspace, Delete, Home, End, PageUp, PageDown, Space, F1-F12) or a single printable character.+ modifiers (Optional[List[str]]): Modifier keys to hold: Shift, Control (Ctrl), Alt, Meta (Cmd).+ selector (Optional[str]): CSS selector to focus before pressing. Presses on the focused element when omitted.+ count (int): Number of times to press the key.+ delay_ms (int): Delay between presses in milliseconds.++ Returns:+ Dict[str, Any]: { success: True, key: str, count: int, modifiers: [str, ...] }+ """+ if isinstance(count, str):+ count = int(count)+ if isinstance(delay_ms, str):+ delay_ms = int(delay_ms)+ if isinstance(modifiers, str):+ modifiers = [modifiers]+ tab = await browser_manager.get_tab(instance_id)+ if not tab:+ raise Exception(f"Instance not found: {instance_id}")+ return await dom_handler.press_key(tab, key, modifiers, selector, count, delay_ms)+@section_tool("element-interaction")async def file_upload(instance_id: str,diff --git a/tests/test_press_key.py b/tests/test_press_key.pynew file mode 100644index 0000000..400bbdb--- /dev/null+++ b/tests/test_press_key.py@@ -0,0 +1,243 @@+import asyncio+import json+import os+import sys+import unittest+from pathlib import Path+from urllib.parse import quote++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "src"))++from dom_handler import (+ MODIFIER_ALT,+ MODIFIER_CONTROL,+ MODIFIER_META,+ MODIFIER_SHIFT,+ DOMHandler,+ resolve_key_descriptor,+ resolve_modifiers,+)++RUN_BROWSER_TESTS = os.getenv("STEALTH_BROWSER_TESTS", "").strip().lower() in {+ "1", "true", "yes", "on"+}++HEADLESS_USER_AGENT = (+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"+)++RECORDER_PAGE = """<!doctype html>+<html><body><input id="target">+<script>+window.__events = [];+const input = document.getElementById('target');+for (const type of ['keydown', 'keypress', 'keyup']) {+ input.addEventListener(type, (e) => {+ window.__events.push({ type: e.type, key: e.key, isTrusted: e.isTrusted,+ shiftKey: e.shiftKey });+ });+}+</script>+</body></html>"""+++class KeyDescriptorTests(unittest.TestCase):+ def test_named_keys_map_to_cdp_fields(self):+ self.assertEqual(+ resolve_key_descriptor("Enter"),+ {"key": "Enter", "code": "Enter", "virtual_key_code": 13, "text": "\r"},+ )+ self.assertEqual(+ resolve_key_descriptor("ArrowDown"),+ {"key": "ArrowDown", "code": "ArrowDown", "virtual_key_code": 40, "text": None},+ )+ self.assertEqual(+ resolve_key_descriptor("Tab"),+ {"key": "Tab", "code": "Tab", "virtual_key_code": 9, "text": None},+ )+ self.assertEqual(+ resolve_key_descriptor("F12"),+ {"key": "F12", "code": "F12", "virtual_key_code": 123, "text": None},+ )++ def test_named_key_lookup_is_case_insensitive(self):+ self.assertEqual(resolve_key_descriptor("enter"), resolve_key_descriptor("Enter"))+ self.assertEqual(resolve_key_descriptor("pagedown")["code"], "PageDown")++ def test_space_accepts_both_spellings(self):+ expected = {"key": " ", "code": "Space", "virtual_key_code": 32, "text": " "}+ self.assertEqual(resolve_key_descriptor("Space"), expected)+ self.assertEqual(resolve_key_descriptor(" "), expected)++ def test_printable_characters_carry_text(self):+ self.assertEqual(+ resolve_key_descriptor("a"),+ {"key": "a", "code": "KeyA", "virtual_key_code": 65, "text": "a"},+ )+ self.assertEqual(+ resolve_key_descriptor("A"),+ {"key": "A", "code": "KeyA", "virtual_key_code": 65, "text": "A"},+ )+ self.assertEqual(+ resolve_key_descriptor("7"),+ {"key": "7", "code": "Digit7", "virtual_key_code": 55, "text": "7"},+ )+ self.assertEqual(+ resolve_key_descriptor("?"),+ {"key": "?", "code": "Slash", "virtual_key_code": 191, "text": "?"},+ )++ def test_unknown_key_lists_supported_keys(self):+ with self.assertRaises(Exception) as ctx:+ resolve_key_descriptor("Frobnicate")+ message = str(ctx.exception)+ self.assertIn("Unsupported key", message)+ self.assertIn("Enter", message)+ self.assertIn("PageDown", message)+ self.assertIn("F12", message)++ def test_empty_key_is_rejected(self):+ with self.assertRaises(Exception):+ resolve_key_descriptor("")+++class ModifierMaskTests(unittest.TestCase):+ def test_bit_values(self):+ self.assertEqual((MODIFIER_ALT, MODIFIER_CONTROL, MODIFIER_META, MODIFIER_SHIFT), (1, 2, 4, 8))++ def test_no_modifiers(self):+ self.assertEqual(resolve_modifiers(None), (0, []))+ self.assertEqual(resolve_modifiers([]), (0, []))++ def test_aliases_normalize(self):+ self.assertEqual(resolve_modifiers(["Ctrl"]), (2, ["Control"]))+ self.assertEqual(resolve_modifiers(["cmd"]), (4, ["Meta"]))+ self.assertEqual(resolve_modifiers(["ALT"]), (1, ["Alt"]))++ def test_combined_mask(self):+ mask, names = resolve_modifiers(["Shift", "Control", "Alt", "Meta"])+ self.assertEqual(mask, 15)+ self.assertEqual(names, ["Shift", "Control", "Alt", "Meta"])++ def test_duplicate_aliases_collapse(self):+ self.assertEqual(resolve_modifiers(["Ctrl", "Control"]), (2, ["Control"]))++ def test_unknown_modifier_is_rejected(self):+ with self.assertRaises(Exception) as ctx:+ resolve_modifiers(["Hyper"])+ self.assertIn("Unsupported modifier", str(ctx.exception))+++class RecordingTab:+ """Minimal Tab stand-in that records dispatched CDP key events."""++ def __init__(self):+ self.events = []++ async def send(self, command):+ payload = next(command)+ assert payload["method"] == "Input.dispatchKeyEvent", payload["method"]+ self.events.append(payload["params"])+ try:+ command.send(None)+ except StopIteration:+ pass+ return None+++class PressKeyDispatchTests(unittest.IsolatedAsyncioTestCase):+ async def test_enter_sends_keydown_and_keyup_with_text(self):+ tab = RecordingTab()+ result = await DOMHandler.press_key(tab, "Enter")++ self.assertEqual(result, {"success": True, "key": "Enter", "count": 1, "modifiers": []})+ self.assertEqual([e["type"] for e in tab.events], ["keyDown", "keyUp"])+ key_down = tab.events[0]+ self.assertEqual(key_down["key"], "Enter")+ self.assertEqual(key_down["code"], "Enter")+ self.assertEqual(key_down["windowsVirtualKeyCode"], 13)+ self.assertEqual(key_down["text"], "\r")++ async def test_count_repeats_press_pairs(self):+ tab = RecordingTab()+ result = await DOMHandler.press_key(tab, "ArrowDown", count=3, delay_ms=0)++ self.assertEqual(result["count"], 3)+ self.assertEqual(len(tab.events), 6)+ self.assertEqual([e["type"] for e in tab.events[:2]], ["keyDown", "keyUp"])+ self.assertNotIn("text", tab.events[0])++ async def test_shift_modifier_keeps_text(self):+ tab = RecordingTab()+ result = await DOMHandler.press_key(tab, "Tab", modifiers=["Shift"])++ self.assertEqual(result["modifiers"], ["Shift"])+ self.assertEqual(tab.events[0]["modifiers"], 8)+ self.assertEqual(tab.events[1]["modifiers"], 8)++ async def test_non_shift_modifier_suppresses_text(self):+ tab = RecordingTab()+ await DOMHandler.press_key(tab, "a", modifiers=["Ctrl"])++ self.assertEqual(tab.events[0]["modifiers"], 2)+ self.assertNotIn("text", tab.events[0])++ async def test_invalid_count_is_rejected(self):+ tab = RecordingTab()+ with self.assertRaises(Exception) as ctx:+ await DOMHandler.press_key(tab, "Enter", count=0)+ self.assertIn("Invalid count", str(ctx.exception))+ self.assertEqual(tab.events, [])+++ RUN_BROWSER_TESTS,+ "Set STEALTH_BROWSER_TESTS=1 to run tests that launch a real browser.",+)+class PressKeyBrowserTests(unittest.IsolatedAsyncioTestCase):+ async def test_dispatched_events_are_trusted(self):+ from browser_manager import BrowserManager+ from models import BrowserOptions++ manager = BrowserManager()+ instance = await manager.spawn_browser(+ BrowserOptions(headless=True, user_agent=HEADLESS_USER_AGENT)+ )+ try:+ await manager.navigate(+ instance.instance_id,+ "data:text/html," + quote(RECORDER_PAGE),+ )+ tab = await manager.get_tab(instance.instance_id)+ self.assertIsNotNone(tab)++ await DOMHandler.press_key(tab, "Enter", selector="#target")+ await DOMHandler.press_key(tab, "ArrowDown")+ await DOMHandler.press_key(tab, "Tab", modifiers=["Shift"])++ recorded = await DOMHandler.execute_script(+ tab, "JSON.stringify(window.__events)"+ )+ events = json.loads(recorded if isinstance(recorded, str) else recorded["result"])++ self.assertTrue(all(e["isTrusted"] for e in events), events)++ enter_events = [e for e in events if e["key"] == "Enter"]+ self.assertEqual(+ [e["type"] for e in enter_events], ["keydown", "keypress", "keyup"]+ )++ arrow_events = [e for e in events if e["key"] == "ArrowDown"]+ self.assertEqual([e["type"] for e in arrow_events], ["keydown", "keyup"])++ tab_events = [e for e in events if e["key"] == "Tab"]+ self.assertEqual([e["type"] for e in tab_events], ["keydown", "keyup"])+ self.assertTrue(all(e["shiftKey"] for e in tab_events), tab_events)+ finally:+ await manager.close_instance(instance.instance_id)+++if __name__ == "__main__":+ unittest.main()