Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

Feat: browser visual pixel mode (#3767)

Puzhen Zhang400c01ba07a9
diff --git a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.py b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.py
index f07902222..75ca35b93 100644
--- a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.py
+++ b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.py
@@ -36,6 +36,215 @@ from camel.utils.tool_result import ToolResult
from .config_loader import ConfigLoader
from .ws_wrapper import WebSocketBrowserWrapper, high_level_action
+
+def _add_rulers_to_image(
+ image_bytes: bytes, tick_interval: int = 100
+) -> bytes:
+ r"""Add rulers with tick marks to an image (like a real measuring ruler).
+
+ Adds horizontal ruler at the top and vertical ruler on the left side,
+ with multi-level tick marks like a real ruler:
+ - Every 100 pixels: longest tick + number label
+ - Every 50 pixels: long tick (no label)
+ - Every 10 pixels: medium tick
+ - Every 5 pixels: short tick
+
+ Args:
+ image_bytes: The original image as bytes.
+ tick_interval: Major interval for number labels (default: 100).
+
+ Returns:
+ The modified image with rulers as bytes.
+ """
+ from io import BytesIO
+
+ from PIL import Image, ImageDraw, ImageFont
+
+ # Load the original image
+ original = Image.open(BytesIO(image_bytes))
+ orig_width, orig_height = original.size
+
+ # Ruler dimensions
+ ruler_thickness = 30 # Increased for better visibility
+ font_size = 9
+
+ # Create new image with space for rulers
+ new_width = orig_width + ruler_thickness
+ new_height = orig_height + ruler_thickness
+ new_image = Image.new('RGB', (new_width, new_height), 'white')
+
+ # Paste original image offset by ruler thickness
+ new_image.paste(original, (ruler_thickness, ruler_thickness))
+
+ draw = ImageDraw.Draw(new_image)
+
+ # Try to load a font, fall back to default if not available
+ font: ImageFont.FreeTypeFont | ImageFont.ImageFont
+ try:
+ font = ImageFont.truetype(
+ "/System/Library/Fonts/Helvetica.ttc", font_size
+ )
+ except (IOError, OSError):
+ try:
+ font = ImageFont.truetype("arial.ttf", font_size)
+ except (IOError, OSError):
+ font = ImageFont.load_default()
+
+ # Colors
+ ruler_bg_color = (245, 245, 245) # Light gray background
+ tick_color = (80, 80, 80) # Dark gray for ticks
+ minor_tick_color = (160, 160, 160) # Lighter gray for minor ticks
+ text_color = (40, 40, 40) # Darker gray for text
+
+ # Draw horizontal ruler background (top)
+ draw.rectangle(
+ [ruler_thickness, 0, new_width, ruler_thickness], fill=ruler_bg_color
+ )
+
+ # Draw vertical ruler background (left)
+ draw.rectangle(
+ [0, ruler_thickness, ruler_thickness, new_height], fill=ruler_bg_color
+ )
+
+ # Draw corner square
+ draw.rectangle(
+ [0, 0, ruler_thickness, ruler_thickness], fill=ruler_bg_color
+ )
+
+ # Tick heights for different intervals (from ruler bottom)
+ tick_100 = 18 # Every 100px - longest, with number
+ tick_50 = 14 # Every 50px - long
+ tick_10 = 10 # Every 10px - medium
+ tick_5 = 6 # Every 5px - short
+
+ # Draw horizontal tick marks and labels (top ruler)
+ for x in range(0, orig_width + 1):
+ tick_x = x + ruler_thickness
+
+ if x % tick_interval == 0:
+ # Major tick (every 100px) - longest with label
+ draw.line(
+ [
+ (tick_x, ruler_thickness - tick_100),
+ (tick_x, ruler_thickness),
+ ],
+ fill=tick_color,
+ width=1,
+ )
+ # Draw number label
+ label = str(x)
+ bbox = draw.textbbox((0, 0), label, font=font)
+ text_width = bbox[2] - bbox[0]
+ draw.text(
+ (tick_x - text_width // 2, 1),
+ label,
+ fill=text_color,
+ font=font,
+ )
+ elif x % 50 == 0:
+ # Half tick (every 50px) - long, no label
+ draw.line(
+ [
+ (tick_x, ruler_thickness - tick_50),
+ (tick_x, ruler_thickness),
+ ],
+ fill=tick_color,
+ width=1,
+ )
+ elif x % 10 == 0:
+ # Medium tick (every 10px)
+ draw.line(
+ [
+ (tick_x, ruler_thickness - tick_10),
+ (tick_x, ruler_thickness),
+ ],
+ fill=tick_color,
+ width=1,
+ )
+ elif x % 5 == 0:
+ # Small tick (every 5px)
+ draw.line(
+ [
+ (tick_x, ruler_thickness - tick_5),
+ (tick_x, ruler_thickness),
+ ],
+ fill=minor_tick_color,
+ width=1,
+ )
+
+ # Draw vertical tick marks and labels (left ruler)
+ for y in range(0, orig_height + 1):
+ tick_y = y + ruler_thickness
+
+ if y % tick_interval == 0:
+ # Major tick (every 100px) - longest with label
+ draw.line(
+ [
+ (ruler_thickness - tick_100, tick_y),
+ (ruler_thickness, tick_y),
+ ],
+ fill=tick_color,
+ width=1,
+ )
+ # Draw number label
+ label = str(y)
+ bbox = draw.textbbox((0, 0), label, font=font)
+ text_height = bbox[3] - bbox[1]
+ draw.text(
+ (2, tick_y - text_height // 2),
+ label,
+ fill=text_color,
+ font=font,
+ )
+ elif y % 50 == 0:
+ # Half tick (every 50px) - long, no label
+ draw.line(
+ [
+ (ruler_thickness - tick_50, tick_y),
+ (ruler_thickness, tick_y),
+ ],
+ fill=tick_color,
+ width=1,
+ )
+ elif y % 10 == 0:
+ # Medium tick (every 10px)
+ draw.line(
+ [
+ (ruler_thickness - tick_10, tick_y),
+ (ruler_thickness, tick_y),
+ ],
+ fill=tick_color,
+ width=1,
+ )
+ elif y % 5 == 0:
+ # Small tick (every 5px)
+ draw.line(
+ [
+ (ruler_thickness - tick_5, tick_y),
+ (ruler_thickness, tick_y),
+ ],
+ fill=minor_tick_color,
+ width=1,
+ )
+
+ # Draw border lines for rulers
+ draw.line(
+ [(ruler_thickness, ruler_thickness), (new_width, ruler_thickness)],
+ fill=tick_color,
+ width=1,
+ )
+ draw.line(
+ [(ruler_thickness, ruler_thickness), (ruler_thickness, new_height)],
+ fill=tick_color,
+ width=1,
+ )
+
+ # Save to bytes
+ output = BytesIO()
+ new_image.save(output, format='PNG')
+ return output.getvalue()
+
+
logger = get_logger(__name__)
@@ -74,6 +283,7 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
"browser_forward",
"browser_get_page_snapshot",
"browser_get_som_screenshot",
+ "browser_get_screenshot",
"browser_click",
"browser_type",
"browser_select",
@@ -337,6 +547,10 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
"total_tabs": len(tab_info),
}
+ # In full_visual_mode, clear the snapshot
+ if self._full_visual_mode:
+ response["snapshot"] = ""
+
# Always include note field for consistency (empty if not present)
if include_note:
response["note"] = result.get("note", "")
@@ -623,28 +837,147 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
logger.error(f"Failed to get screenshot: {e}")
return f"Error capturing screenshot: {e}"
- async def browser_click(self, *, ref: str) -> Dict[str, Any]:
+ async def browser_get_screenshot(
+ self,
+ read_image: bool = True,
+ ) -> "str | ToolResult":
+ r"""Captures a plain screenshot of the current page without markers.
+
+ This tool takes a screenshot without any visual annotations. Use this
+ in full_visual_mode for visual analysis where element ref IDs are not
+ needed.
+
+ Args:
+ read_image (bool, optional): If `True`, the screenshot image will
+ be included in the agent's context for direct visual analysis.
+ If `False`, only a text message (including the saved file
+ path) will be returned.
+ (default: :obj:`True`)
+
+ Returns:
+ str | ToolResult: If `read_image` is `True`, returns a ToolResult
+ containing the text message and the screenshot image. If
+ `False`, returns a string with the file path only.
+ """
+ import base64
+ import datetime
+ import os
+ import urllib.parse
+
+ from camel.utils import sanitize_filename
+
+ try:
+ ws_wrapper = await self._get_ws_wrapper()
+ result = await ws_wrapper.get_screenshot()
+
+ result_text = result.text
+ file_path = None
+
+ if result.images:
+ cache_dir = os.path.abspath(self._cache_dir)
+ os.makedirs(cache_dir, exist_ok=True)
+
+ try:
+ page_info = await ws_wrapper.get_tab_info()
+ current_tab = next(
+ (tab for tab in page_info if tab.get('is_current')),
+ None,
+ )
+ url = current_tab['url'] if current_tab else 'unknown'
+ except Exception:
+ url = 'unknown'
+
+ parsed_url = urllib.parse.urlparse(url)
+ url_name = sanitize_filename(
+ str(parsed_url.path) or 'homepage', max_length=241
+ )
+ timestamp = datetime.datetime.now().strftime("%m%d%H%M%S")
+ file_path = os.path.join(
+ cache_dir, f"{url_name}_{timestamp}.png"
+ )
+
+ # Process images and optionally add rulers
+ processed_images = []
+ for _, image_data in enumerate(result.images):
+ if image_data.startswith('data:image/png;base64,'):
+ base64_data = image_data.split(',', 1)[1]
+ image_bytes = base64.b64decode(base64_data)
+
+ # Add rulers in full_visual_mode
+ if self._full_visual_mode:
+ image_bytes = _add_rulers_to_image(
+ image_bytes, tick_interval=100
+ )
+ # Re-encode to base64 for the processed image
+ processed_base64 = base64.b64encode(
+ image_bytes
+ ).decode('utf-8')
+ processed_images.append(
+ f'data:image/png;base64,{processed_base64}'
+ )
+ else:
+ processed_images.append(image_data)
+
+ with open(file_path, 'wb') as f:
+ f.write(image_bytes)
+
+ logger.info(f"Screenshot saved to: {file_path}")
+
+ result_text += f" (saved to: {file_path})"
+ break
+
+ if read_image and result.images:
+ logger.info(
+ f"Returning ToolResult with {len(result.images)} image(s) "
+ "for agent context"
+ )
+ # Use processed images (with rulers) if in full_visual_mode
+ images_to_return = (
+ processed_images
+ if self._full_visual_mode and processed_images
+ else result.images
+ )
+ return ToolResult(
+ text=result_text,
+ images=images_to_return,
+ )
+ else:
+ return result_text
+ except Exception as e:
+ logger.error(f"Failed to get screenshot: {e}")
+ return f"Error capturing screenshot: {e}"
+
+ async def browser_click(
+ self,
+ *,
+ ref: Optional[str] = None,
+ x: Optional[float] = None,
+ y: Optional[float] = None,
+ ) -> Dict[str, Any]:
r"""Performs a click on an element on the page.
+ Supports two modes:
+ - Ref mode: Click by element ref ID (from snapshot)
+ - Pixel mode: Click by x, y pixel coordinates
+
Args:
- ref (str): The `ref` ID of the element to click. This ID is
- obtained from a page snapshot (`get_page_snapshot` or
- `get_som_screenshot`).
+ ref (Optional[str]): The `ref` ID of the element to click.
+ x (Optional[float]): X pixel coordinate for click.
+ y (Optional[float]): Y pixel coordinate for click.
Returns:
- Dict[str, Any]: A dictionary with the result of the action:
- - "result" (str): Confirmation of the action.
- - "snapshot" (str): A textual snapshot of the page after the
- click.
- - "tabs" (List[Dict]): Information about all open tabs.
- - "current_tab" (int): Index of the active tab.
- - "total_tabs" (int): Total number of open tabs.
- - "note" (str): A note about the loading status of the page.
- - "timing" (Dict): Timing information for the action.
+ Dict[str, Any]: A dictionary with the result of the action.
"""
try:
ws_wrapper = await self._get_ws_wrapper()
- result = await ws_wrapper.click(ref)
+ if x is not None and y is not None:
+ result = await ws_wrapper.mouse_control('click', x, y)
+ elif ref is not None:
+ result = await ws_wrapper.click(ref)
+ else:
+ raise ValueError(
+ "Must provide either 'ref' or both 'x' and 'y'"
+ )
return await self._build_action_response(result, ws_wrapper)
except Exception as e:
logger.error(f"Failed to click element: {e}")
@@ -656,47 +989,45 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
ref: Optional[str] = None,
text: Optional[str] = None,
inputs: Optional[List[Dict[str, str]]] = None,
+ x: Optional[float] = None,
+ y: Optional[float] = None,
) -> Dict[str, Any]:
r"""Types text into one or more input elements on the page.
- This method supports two modes:
- 1. Single input mode (backward compatible): Provide 'ref' and 'text'
- 2. Multiple inputs mode: Provide 'inputs' as a list of dictionaries
- with 'ref' and 'text' keys
+ Supports multiple modes:
+ - Ref mode: Provide 'ref' and 'text'
+ - Pixel mode: Provide 'x', 'y' and 'text' (clicks to focus, then types)
+ - Multiple inputs mode: Provide 'inputs' list
Args:
- ref (Optional[str]): The `ref` ID of the input element, from a
- snapshot. Required when using single input mode.
- text (Optional[str]): The text to type into the element. Required
- when using single input mode.
- inputs (Optional[List[Dict[str, str]]]): List of dictionaries,
- each containing 'ref' and 'text' keys for typing into multiple
- elements. Example: [{'ref': '1', 'text': 'username'},
- {'ref': '2', 'text': 'password'}]
+ ref (Optional[str]): The `ref` ID of the input element.
+ text (Optional[str]): The text to type.
+ inputs (Optional[List[Dict[str, str]]]): List of inputs with
+ 'ref' and 'text' keys.
+ x (Optional[float]): X pixel coordinate of input field.
+ y (Optional[float]): Y pixel coordinate of input field.
Returns:
- Dict[str, Any]: A dictionary with the result of the action:
- - "result" (str): Confirmation of the action.
- - "snapshot" (str): A textual snapshot of the page after
- typing.
- - "tabs" (List[Dict]): Information about all open tabs.
- - "current_tab" (int): Index of the active tab.
- - "total_tabs" (int): Total number of open tabs.
- - "details" (Dict[str, Any]): When using multiple inputs,
- contains success/error status for each ref.
- - "note" (str): A note about the loading status of the page.
+ Dict[str, Any]: A dictionary with the result of the action.
"""
try:
ws_wrapper = await self._get_ws_wrapper()
- if ref is not None and text is not None:
+ if x is not None and y is not None and text is not None:
+ # Pixel mode: click to focus, then type using keyboard
+ await ws_wrapper.mouse_control('click', x, y)
+ await asyncio.sleep(0.1) # Wait for focus
+ result = await ws_wrapper.batch_keyboard_input(
+ [{"type": "type", "text": text, "delay": 0}]
+ )
+ elif ref is not None and text is not None:
result = await ws_wrapper.type(ref, text)
elif inputs is not None:
result = await ws_wrapper.type_multiple(inputs)
else:
raise ValueError(
- "Either provide 'ref' and 'text' for single input, "
- "or 'inputs' for multiple inputs"
+ "Provide 'ref' and 'text', or 'x', 'y' and 'text', "
+ "or 'inputs' list"
)
return await self._build_action_response(result, ws_wrapper)
@@ -811,26 +1142,42 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
return self._build_error_response(f"Error with mouse control: {e}")
async def browser_mouse_drag(
- self, *, from_ref: str, to_ref: str
+ self,
+ *,
+ from_ref: Optional[str] = None,
+ to_ref: Optional[str] = None,
+ from_x: Optional[float] = None,
+ from_y: Optional[float] = None,
+ to_x: Optional[float] = None,
+ to_y: Optional[float] = None,
) -> Dict[str, Any]:
- r"""Control the mouse to drag and drop in the browser using ref IDs.
+ r"""Drag and drop in the browser using ref IDs or pixel coordinates.
+
+ Supports two modes:
+ - Ref mode: Provide from_ref and to_ref
+ - Pixel mode: Provide from_x, from_y, to_x, to_y
Args:
- from_ref (str): The `ref` ID of the source element to drag from.
- to_ref (str): The `ref` ID of the target element to drag to.
+ from_ref (Optional[str]): The ref ID of the source element.
+ to_ref (Optional[str]): The ref ID of the target element.
+ from_x (Optional[float]): Source X pixel coordinate.
+ from_y (Optional[float]): Source Y pixel coordinate.
+ to_x (Optional[float]): Target X pixel coordinate.
+ to_y (Optional[float]): Target Y pixel coordinate.
Returns:
- Dict[str, Any]: A dictionary with the result of the action:
- - "result" (str): Confirmation of the action.
- - "snapshot" (str): A new page snapshot.
- - "tabs" (List[Dict]): Information about all open tabs.
- - "current_tab" (int): Index of the active tab.
- - "total_tabs" (int): Total number of open tabs.
- - "note" (str): A note about the loading status of the page.
+ Dict[str, Any]: A dictionary with the result of the action.
"""
try:
ws_wrapper = await self._get_ws_wrapper()
- result = await ws_wrapper.mouse_drag(from_ref, to_ref)
+ result = await ws_wrapper.mouse_drag(
+ from_ref=from_ref,
+ to_ref=to_ref,
+ from_x=from_x,
+ from_y=from_y,
+ to_x=to_x,
+ to_y=to_y,
+ )
return await self._build_action_response(result, ws_wrapper)
except Exception as e:
logger.error(f"Error with mouse drag and drop: {e}")
@@ -1191,9 +1538,8 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
try:
for i in range(0, len(operations), CHUNK_SIZE):
chunk = operations[i : i + CHUNK_SIZE]
- await ws_wrapper._send_command(
- 'batch_keyboard_input',
- {'operations': chunk, 'skipStabilityWait': True},
+ await ws_wrapper.batch_keyboard_input(
+ chunk, skip_stability_wait=True
)
# Small delay between chunks
await asyncio.sleep(0.2)
@@ -1409,22 +1755,14 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
{"type": "wait", "delay": 100},
{"type": "press", "keys": ["Meta", "c"]},
]
- await ws_wrapper._send_command(
- 'batch_keyboard_input',
- {
- 'operations': select_all_copy_ops,
- 'skipStabilityWait': True,
- },
+ await ws_wrapper.batch_keyboard_input(
+ select_all_copy_ops, skip_stability_wait=True
)
await asyncio.sleep(0.2)
# Repeat to capture correct one
- await ws_wrapper._send_command(
- 'batch_keyboard_input',
- {
- 'operations': select_all_copy_ops,
- 'skipStabilityWait': True,
- },
+ await ws_wrapper.batch_keyboard_input(
+ select_all_copy_ops, skip_stability_wait=True
)
await asyncio.sleep(0.2)
else:
@@ -1433,22 +1771,14 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
{"type": "wait", "delay": 100},
{"type": "press", "keys": ["Control", "c"]},
]
- await ws_wrapper._send_command(
- 'batch_keyboard_input',
- {
- 'operations': select_all_copy_ops,
- 'skipStabilityWait': True,
- },
+ await ws_wrapper.batch_keyboard_input(
+ select_all_copy_ops, skip_stability_wait=True
)
await asyncio.sleep(0.2)
# Repeat to capture correct one
- await ws_wrapper._send_command(
- 'batch_keyboard_input',
- {
- 'operations': select_all_copy_ops,
- 'skipStabilityWait': True,
- },
+ await ws_wrapper.batch_keyboard_input(
+ select_all_copy_ops, skip_stability_wait=True
)
await asyncio.sleep(0.2)
@@ -1667,10 +1997,174 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
full_visual_mode=self._full_visual_mode,
)
+ # Tools not available in full_visual_mode (require ref, no pixel alt)
+ _TOOLS_EXCLUDED_IN_VISUAL_MODE: ClassVar[List[str]] = [
+ "browser_select",
+ "browser_get_page_snapshot",
+ "browser_get_som_screenshot",
+ ]
+
+ def _create_mode_wrapper(
+ self,
+ method: Callable[..., Any],
+ tool_name: str,
+ pixel_mode: bool,
+ ) -> Callable[..., Any]:
+ """Create a wrapper with mode-specific signature and docstring.
+
+ Args:
+ method: The original method to wrap.
+ tool_name: Name of the tool.
+ pixel_mode: If True, create pixel-coordinate wrapper.
+ If False, create ref-based wrapper.
+ """
+ if tool_name == "browser_click":
+ if pixel_mode:
+
+ async def browser_click_pixel(
+ *, x: float, y: float
+ ) -> Dict[str, Any]:
+ r"""Clicks at the specified pixel coordinates on the page.
+
+ Use browser_get_screenshot to visually identify the
+ target position, then provide the x,y coordinates.
+
+ Args:
+ x (float): X pixel coordinate (horizontal position from
+ left edge of viewport).
+ y (float): Y pixel coordinate (vertical position from
+ top edge of viewport).
+
+ Returns:
+ Dict[str, Any]: Result of the action.
+ """
+ return await method(x=x, y=y)
+
+ browser_click_pixel.__name__ = "browser_click"
+ return browser_click_pixel
+ else:
+
+ async def browser_click_ref(*, ref: str) -> Dict[str, Any]:
+ r"""Clicks on an element identified by its ref ID.
+
+ The ref ID is obtained from a page snapshot
+ (browser_get_page_snapshot or browser_get_som_screenshot).
+
+ Args:
+ ref (str): The ref ID of the element to click.
+
+ Returns:
+ Dict[str, Any]: Result of the action.
+ """
+ return await method(ref=ref)
+
+ browser_click_ref.__name__ = "browser_click"
+ return browser_click_ref
+
+ elif tool_name == "browser_type":
+ if pixel_mode:
+
+ async def browser_type_pixel(
+ *, x: float, y: float, text: str
+ ) -> Dict[str, Any]:
+ r"""Types text at the specified pixel coordinates.
+
+ Clicks at the coordinates to focus the input field, then
+ types the given text.
+
+ Args:
+ x (float): X pixel coordinate of the input field.
+ y (float): Y pixel coordinate of the input field.
+ text (str): The text to type into the input field.
+
+ Returns:
+ Dict[str, Any]: Result of the action.
+ """
+ return await method(x=x, y=y, text=text)
+
+ browser_type_pixel.__name__ = "browser_type"
+ return browser_type_pixel
+ else:
+
+ async def browser_type_ref(
+ *,
+ ref: Optional[str] = None,
+ text: Optional[str] = None,
+ inputs: Optional[List[Dict[str, str]]] = None,
+ ) -> Dict[str, Any]:
+ r"""Types text into input elements identified by ref ID.
+
+ Supports single input (ref + text) or multiple inputs.
+
+ Args:
+ ref (Optional[str]): The ref ID of the input element.
+ text (Optional[str]): The text to type.
+ inputs (Optional[List[Dict[str, str]]]): List of
+ inputs, each with 'ref' and 'text' keys.
+
+ Returns:
+ Dict[str, Any]: Result of the action.
+ """
+ return await method(ref=ref, text=text, inputs=inputs)
+
+ browser_type_ref.__name__ = "browser_type"
+ return browser_type_ref
+
+ elif tool_name == "browser_mouse_drag":
+ if pixel_mode:
+
+ async def browser_mouse_drag_pixel(
+ *, from_x: float, from_y: float, to_x: float, to_y: float
+ ) -> Dict[str, Any]:
+ r"""Drags from one position to another using pixels.
+
+ Use browser_get_screenshot to identify element positions.
+
+ Args:
+ from_x (float): Source X pixel coordinate.
+ from_y (float): Source Y pixel coordinate.
+ to_x (float): Target X pixel coordinate.
+ to_y (float): Target Y pixel coordinate.
+
+ Returns:
+ Dict[str, Any]: Result of the action.
+ """
+ return await method(
+ from_x=from_x, from_y=from_y, to_x=to_x, to_y=to_y
+ )
+
+ browser_mouse_drag_pixel.__name__ = "browser_mouse_drag"
+ return browser_mouse_drag_pixel
+ else:
+
+ async def browser_mouse_drag_ref(
+ *, from_ref: str, to_ref: str
+ ) -> Dict[str, Any]:
+ r"""Drags from one element to another using ref IDs.
+
+ The ref IDs are obtained from a page snapshot.
+
+ Args:
+ from_ref (str): The ref ID of the source element.
+ to_ref (str): The ref ID of the target element.
+
+ Returns:
+ Dict[str, Any]: Result of the action.
+ """
+ return await method(from_ref=from_ref, to_ref=to_ref)
+
+ browser_mouse_drag_ref.__name__ = "browser_mouse_drag"
+ return browser_mouse_drag_ref
+
+ return method
+
def get_tools(self) -> List[FunctionTool]:
- r"""Get available function tools based
- on enabled_tools configuration."""
- # Map tool names to their corresponding methods
+ r"""Get available function tools based on enabled_tools configuration.
+
+ In full_visual_mode:
+ - Tools requiring ref with no pixel alternative are excluded
+ - browser_click and browser_type use pixel coordinates instead of ref
+ """
tool_map = {
"browser_open": self.browser_open,
"browser_close": self.browser_close,
@@ -1679,6 +2173,7 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
"browser_forward": self.browser_forward,
"browser_get_page_snapshot": self.browser_get_page_snapshot,
"browser_get_som_screenshot": self.browser_get_som_screenshot,
+ "browser_get_screenshot": self.browser_get_screenshot,
"browser_click": self.browser_click,
"browser_type": self.browser_type,
"browser_select": self.browser_select,
@@ -1697,16 +2192,38 @@ class HybridBrowserToolkit(BaseToolkit, RegisteredAgentToolkit):
"browser_sheet_read": self.browser_sheet_read,
}
+ # Tools that need mode-specific wrappers (different signatures)
+ mode_specific_tools = {
+ "browser_click",
+ "browser_type",
+ "browser_mouse_drag",
+ }
+
enabled_tools = []
for tool_name in self.enabled_tools:
- if tool_name in tool_map:
- tool = FunctionTool(
- cast(Callable[..., Any], tool_map[tool_name])
- )
- enabled_tools.append(tool)
- else:
+ # Skip tools not available in full_visual_mode
+ if (
+ self._full_visual_mode
+ and tool_name in self._TOOLS_EXCLUDED_IN_VISUAL_MODE
+ ):
+ logger.debug(f"Skipping {tool_name} in full_visual_mode")
+ continue
+
+ if tool_name not in tool_map:
logger.warning(f"Unknown tool name: {tool_name}")
+ continue
+
+ method = tool_map[tool_name]
+
+ # Apply mode-specific wrapper for tools with different signatures
+ if tool_name in mode_specific_tools:
+ method = self._create_mode_wrapper(
+ method, tool_name, pixel_mode=self._full_visual_mode
+ )
+
+ tool = FunctionTool(cast(Callable[..., Any], method))
+ enabled_tools.append(tool)
logger.info(f"Returning {len(enabled_tools)} enabled tools")
return enabled_tools
diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts
index 79e737021..5f7618741 100644
--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts
+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts
@@ -1,5 +1,5 @@
import { Page, Browser, BrowserContext, chromium, ConsoleMessage, Frame } from 'playwright';
-import { BrowserToolkitConfig, SnapshotResult, SnapshotElement, ActionResult, TabInfo, BrowserAction, DetailedTiming, PageStabilityResult } from './types';
+import { BrowserToolkitConfig, SnapshotResult, SnapshotElement, ActionResult, TabInfo, BrowserAction, DetailedTiming, PageStabilityResult, INTERACTIVE_ROLES, NearestElementInfo } from './types';
import { ConfigLoader, StealthConfig } from './config-loader';
// Constants for loading element detection
@@ -53,6 +53,206 @@ export class HybridBrowserSession {
return typeof result === 'string' ? result : result.full;
}
+ /**
+ * Parse frame prefix from ref (e.g., "f1e5" -> { frameIndex: 1, localRef: "e5" })
+ * Refs without frame prefix (e.g., "e5") return frameIndex: 0
+ */
+ private parseFrameRef(ref: string): { frameIndex: number; localRef: string } {
+ const frameMatch = ref.match(/^f(\d+)(e.*)$/);
+ if (frameMatch) {
+ return {
+ frameIndex: parseInt(frameMatch[1], 10),
+ localRef: frameMatch[2]
+ };
+ }
+ return { frameIndex: 0, localRef: ref };
+ }
+
+ /**
+ * Try to find element in a specific frame with given selector
+ */
+ private async tryFindInFrame(
+ frame: Frame,
+ selector: string
+ ): Promise<ReturnType<Frame['locator']> | null> {
+ try {
+ const element = frame.locator(selector).first();
+ if (await element.count() > 0) {
+ return element;
+ }
+ } catch {
+ // Frame might be detached or selector invalid
+ }
+ return null;
+ }
+
+ /**
+ * Find element across frames with optimized search strategy
+ * Search order: 1) Target frame with localRef, 2) All frames with full ref
+ */
+ private async findElementAcrossFrames(
+ page: Page,
+ ref: string
+ ): Promise<{ locator: ReturnType<Frame['locator']>; frame: Frame } | null> {
+ const allFrames = page.frames();
+ const { frameIndex, localRef } = this.parseFrameRef(ref);
+
+ // Strategy 1: If ref has frame prefix, try target frame with localRef
+ if (frameIndex > 0 && frameIndex < allFrames.length) {
+ const targetFrame = allFrames[frameIndex];
+ const element = await this.tryFindInFrame(targetFrame, `aria-ref=${localRef}`);
+ if (element) {
+ return { locator: element, frame: targetFrame };
+ }
+ }
+
+ // Strategy 2: Search all frames with full ref
+ for (const frame of allFrames) {
+ const element = await this.tryFindInFrame(frame, `aria-ref=${ref}`);
+ if (element) {
+ return { locator: element, frame };
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Get element coordinates from boundingBox
+ */
+ private async getElementCoordinates(
+ element: ReturnType<Frame['locator']>
+ ): Promise<{ x: number; y: number; width: number; height: number } | null> {
+ const box = await element.boundingBox();
+ if (!box) return null;
+ return {
+ x: Math.round(box.x),
+ y: Math.round(box.y),
+ width: Math.round(box.width),
+ height: Math.round(box.height)
+ };
+ }
+
+ /**
+ * Calculate distance from point to element center
+ */
+ private distanceToElement(
+ x: number,
+ y: number,
+ coords: { x: number; y: number; width: number; height: number }
+ ): number {
+ const centerX = coords.x + coords.width / 2;
+ const centerY = coords.y + coords.height / 2;
+ return Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
+ }
+
+ /**
+ * Find N nearest interactive elements to a given point
+ * Returns elements with clickable center coordinates and aria info
+ */
+ private findNearestElements(
+ elements: Record<string, any>,
+ snapshot: string,
+ x: number,
+ y: number,
+ count: number = 5
+ ): NearestElementInfo[] {
+ // Parse aria-label/name from snapshot text
+ const elementNames = this.parseElementNamesFromSnapshot(snapshot);
+
+ const elementsWithDistance: NearestElementInfo[] = [];
+
+ for (const [ref, element] of Object.entries(elements)) {
+ if (!element.coordinates) continue;
+
+ const role = element.role || 'unknown';
+ if (!INTERACTIVE_ROLES.has(role)) continue;
+
+ const coords = element.coordinates;
+ elementsWithDistance.push({
+ ref,
+ role,
+ name: elementNames.get(ref) || '',
+ distance: Math.round(this.distanceToElement(x, y, coords)),
+ clickableCoord: {
+ x: Math.round(coords.x + coords.width / 2),
+ y: Math.round(coords.y + coords.height / 2)
+ },
+ boundingBox: coords
+ });
+ }
+
+ return elementsWithDistance
+ .sort((a, b) => a.distance - b.distance)
+ .slice(0, count);
+ }
+
+ /**
+ * Parse element names/labels from snapshot text
+ */
+ private parseElementNamesFromSnapshot(snapshot: string): Map<string, string> {
+ const elementNames = new Map<string, string>();
+ for (const line of snapshot.split('\n')) {
+ const refMatch = line.match(/\[ref=([^\]]+)\]/);
+ if (refMatch) {
+ const nameMatch = line.match(/-\s+\w+\s+"([^"]+)"/);
+ if (nameMatch) {
+ elementNames.set(refMatch[1], nameMatch[1]);
+ }
+ }
+ }
+ return elementNames;
+ }
+
+ /**
+ * Format nearest elements as readable text for LLM
+ */
+ private formatNearestElementsMessage(
+ clickX: number,
+ clickY: number,
+ nearestElements: NearestElementInfo[]
+ ): string {
+ const lines: string[] = [
+ `Click at (${clickX}, ${clickY}) may be ineffective - page content unchanged.`,
+ `Nearest interactive elements:`
+ ];
+
+ for (let i = 0; i < nearestElements.length; i++) {
+ const el = nearestElements[i];
+ const nameStr = el.name ? ` "${el.name}"` : '';
+ const box = el.boundingBox;
+ lines.push(
+ ` ${i + 1}. [${el.role}]${nameStr} - click at (${el.clickableCoord.x}, ${el.clickableCoord.y}), ` +
+ `area: (${box.x}, ${box.y}) to (${box.x + box.width}, ${box.y + box.height})`
+ );
+ }
+
+ return lines.join('\n');
+ }
+
+ /**
+ * Check if a point is within a canvas element
+ */
+ private async isPointOnCanvas(page: Page, x: number, y: number): Promise<boolean> {
+ return await page.evaluate(({ x, y }) => {
+ const element = document.elementFromPoint(x, y);
+ if (!element) return false;
+ // Check if element is canvas or inside canvas
+ return element.tagName.toUpperCase() === 'CANVAS' ||
+ element.closest('canvas') !== null;
+ }, { x, y });
+ }
+
+ /**
+ * Compare two snapshots to detect if page changed
+ * Returns true if snapshots are meaningfully different
+ */
+ private snapshotsAreDifferent(before: string, after: string): boolean {
+ // Normalize whitespace and compare
+ const normalize = (s: string) => s.replace(/\s+/g, ' ').trim();
+ return normalize(before) !== normalize(after);
+ }
+
private registerNewPage(tabId: string, page: Page): void {
// Register page and logs with tabId
this.pages.set(tabId, page);
@@ -499,33 +699,32 @@ export class HybridBrowserSession {
}
if (includeCoordinates) {
- // Get coordinates for each ref using aria-ref selector
- for (const ref of refs) {
- try {
- const selector = `aria-ref=${ref}`;
- const element = await page.locator(selector).first();
- const exists = await element.count() > 0;
-
- if (exists) {
- // Get bounding box
- const boundingBox = await element.boundingBox();
-
- if (boundingBox) {
- // Add coordinates to existing element info
+ // Enrich elements with coordinates using parallel processing
+ // Process in batches to avoid overwhelming the browser
+ const BATCH_SIZE = 10;
+ for (let i = 0; i < refs.length; i += BATCH_SIZE) {
+ const batch = refs.slice(i, i + BATCH_SIZE);
+ await Promise.all(batch.map(async (ref) => {
+ const result = await this.findElementAcrossFrames(page, ref);
+ if (result) {
+ const coords = await this.getElementCoordinates(result.locator);
+ if (coords) {
+ // NOTE: We use parseFrameRef(ref) to get frameIndex from the ref string,
+ // not from result.frame. This is correct because Playwright's snapshot
+ // automatically prefixes refs with frame info (e.g., "f1e5" for iframe 1).
+ // Using result.frame directly via indexOf() causes issues with object
+ // reference comparison and can incorrectly set frameIndex to 0 for all
+ // elements, breaking iframe visibility detection in SOM screenshots.
+ const { frameIndex } = this.parseFrameRef(ref);
playwrightMapping[ref] = {
...playwrightMapping[ref],
- coordinates: {
- x: Math.round(boundingBox.x),
- y: Math.round(boundingBox.y),
- width: Math.round(boundingBox.width),
- height: Math.round(boundingBox.height)
- }
+ coordinates: coords,
+ frameIndex,
+ frameUrl: frameIndex > 0 ? result.frame.url() : undefined
};
}
}
- } catch (error) {
- console.warn(`Failed to get coordinates for ref ${ref}:`, error);
- }
+ }));
}
}
@@ -603,18 +802,15 @@ export class HybridBrowserSession {
// Ensure we have the latest snapshot and mapping
await this.getSnapshot(page);
- // Use Playwright's aria-ref selector engine
- const selector = `aria-ref=${ref}`;
-
- // Check if element exists
- const element = await page.locator(selector).first();
- const exists = await element.count() > 0;
+ // Use findElementAcrossFrames to support elements inside iframes
+ const result = await this.findElementAcrossFrames(page, ref);
- if (!exists) {
+ if (!result) {
page.off('dialog', dialogHandler);
- return { success: false, error: `Element with ref ${ref} not found` };
+ return { success: false, error: `Element with ref ${ref} not found in any frame` };
}
+ const element = result.locator;
const role = await element.getAttribute('role');
const elementTagName = await element.evaluate(el => el.tagName.toLowerCase());
const isCombobox = role === 'combobox' || elementTagName === 'combobox';
@@ -857,14 +1053,15 @@ export class HybridBrowserSession {
// Handle single input (backward compatibility)
if (ref && text !== undefined) {
- const selector = `aria-ref=${ref}`;
- const element = await page.locator(selector).first();
+ // Use findElementAcrossFrames to support elements inside iframes
+ const result = await this.findElementAcrossFrames(page, ref);
- const exists = await element.count() > 0;
- if (!exists) {
- return { success: false, error: `Element with ref ${ref} not found` };
+ if (!result) {
+ return { success: false, error: `Element with ref ${ref} not found in any frame` };
}
+ const element = result.locator;
+
// Get element attributes to check if it's readonly or a special input type
let originalPlaceholder: string | null = null;
let isReadonly = false;
@@ -1192,15 +1389,15 @@ export class HybridBrowserSession {
// Ensure we have the latest snapshot
await this.getSnapshot(page);
- // Use Playwright's aria-ref selector
- const selector = `aria-ref=${ref}`;
- const element = await page.locator(selector).first();
+ // Use findElementAcrossFrames to support elements inside iframes
+ const result = await this.findElementAcrossFrames(page, ref);
- const exists = await element.count() > 0;
- if (!exists) {
- return { success: false, error: `Element with ref ${ref} not found` };
+ if (!result) {
+ return { success: false, error: `Element with ref ${ref} not found in any frame` };
}
+ const element = result.locator;
+
// Select value using Playwright's built-in selectOption method
await element.selectOption(value);
@@ -1211,9 +1408,75 @@ export class HybridBrowserSession {
}
/**
- * Simplified mouse control implementation
+ * Show highlight animation at given coordinates
*/
- private async performMouseControl(page: Page, control: string, x: number, y: number): Promise<{ success: boolean; error?: string }> {
+ private async showClickHighlight(page: Page, x: number, y: number): Promise<void> {
+ await page.evaluate(({ x, y }) => {
+ // Create highlight element
+ const highlight = document.createElement('div');
+ highlight.id = 'claude-click-highlight-' + Date.now();
+ highlight.style.cssText = `
+ position: fixed;
+ left: ${x}px;
+ top: ${y}px;
+ width: 20px;
+ height: 20px;
+ margin-left: -10px;
+ margin-top: -10px;
+ border-radius: 50%;
+ background: rgba(59, 130, 246, 0.5);
+ border: 2px solid rgba(59, 130, 246, 0.8);
+ pointer-events: none;
+ z-index: 2147483647;
+ animation: claude-highlight-pulse 0.6s ease-out forwards;
+ `;
+
+ // Add keyframes if not already present
+ if (!document.getElementById('claude-highlight-styles')) {
+ const style = document.createElement('style');
+ style.id = 'claude-highlight-styles';
+ style.textContent = `
+ @keyframes claude-highlight-pulse {
+ 0% {
+ transform: scale(1);
+ opacity: 1;
+ }
+ 50% {
+ transform: scale(2);
+ opacity: 0.7;
+ }
+ 100% {
+ transform: scale(2.5);
+ opacity: 0;
+ }
+ }
+ `;
+ document.head.appendChild(style);
+ }
+
+ document.body.appendChild(highlight);
+
+ // Remove after animation
+ setTimeout(() => {
+ highlight.remove();
+ }, 600);
+ }, { x, y });
+ }
+
+ /**
+ * Mouse control implementation with ineffective click detection
+ * For full visual mode: detects when click has no effect and suggests nearest elements
+ */
+ private async performMouseControl(
+ page: Page,
+ control: string,
+ x: number,
+ y: number
+ ): Promise<{
+ success: boolean;
+ error?: string;
+ resultMessage?: string; // Custom result message for ineffective clicks
+ }> {
try {
const viewport = page.viewportSize();
if (!viewport) {
@@ -1222,6 +1485,24 @@ export class HybridBrowserSession {
if (x < 0 || y < 0 || x > viewport.width || y > viewport.height) {
return { success: false, error: `Invalid coordinates, outside viewport bounds: (${x}, ${y})` };
}
+
+ // Check if clicking on canvas element
+ const isOnCanvas = await this.isPointOnCanvas(page, x, y);
+
+ // Get snapshot before click (with coordinates for nearest element calculation)
+ let snapshotBefore: string | null = null;
+ let elementsWithCoords: Record<string, any> | null = null;
+
+ if (!isOnCanvas && control === 'click') {
+ const snapshotResult = await this.getSnapshotForAINative(true, false);
+ snapshotBefore = snapshotResult.snapshot;
+ elementsWithCoords = snapshotResult.elements;
+ }
+
+ // Show highlight animation at click position
+ await this.showClickHighlight(page, x, y);
+
+ // Perform the click action
switch (control) {
case 'click': {
await page.mouse.click(x, y);
@@ -1239,6 +1520,25 @@ export class HybridBrowserSession {
return { success: false, error: `Invalid control action: ${control}` };
}
+ // For non-canvas clicks, check if the click had any effect
+ if (!isOnCanvas && control === 'click' && snapshotBefore && elementsWithCoords) {
+ // Wait a moment for any UI changes
+ await page.waitForTimeout(100);
+
+ // Get snapshot after click
+ const snapshotAfter = await this.getSnapshot(page);
+
+ // Check if snapshot changed
+ if (!this.snapshotsAreDifferent(snapshotBefore, snapshotAfter)) {
+ // Click had no effect - find nearest interactive elements and format message
+ const nearestCount = this.configLoader.getWebSocketConfig().nearestElementsCount;
+ const nearestElements = this.findNearestElements(elementsWithCoords, snapshotBefore, x, y, nearestCount);
+ const resultMessage = this.formatNearestElementsMessage(x, y, nearestElements);
+
+ return { success: true, resultMessage };
+ }
+ }
+
return { success: true };
} catch (error) {
return { success: false, error: `Mouse action failed: ${error}` };
@@ -1246,53 +1546,75 @@ export class HybridBrowserSession {
}
/**
- * Enhanced mouse drag and drop implementation using ref IDs
+ * Mouse drag and drop implementation supporting both ref and pixel modes
*/
- private async performMouseDrag(page: Page, fromRef: string, toRef: string): Promise<{ success: boolean; error?: string }> {
+ private async performMouseDrag(
+ page: Page,
+ action: { from_ref?: string; to_ref?: string; from_x?: number; from_y?: number; to_x?: number; to_y?: number }
+ ): Promise<{ success: boolean; error?: string }> {
try {
- // Ensure we have the latest snapshot
- await this.getSnapshot(page);
-
- // Get elements using Playwright's aria-ref selector
- const fromSelector = `aria-ref=${fromRef}`;
- const toSelector = `aria-ref=${toRef}`;
-
- const fromElement = await page.locator(fromSelector).first();
- const toElement = await page.locator(toSelector).first();
-
- // Check if elements exist
- const fromExists = await fromElement.count() > 0;
- const toExists = await toElement.count() > 0;
+ let fromX: number, fromY: number, toX: number, toY: number;
+
+ // Pixel mode: use coordinates directly
+ if (action.from_x !== undefined && action.from_y !== undefined &&
+ action.to_x !== undefined && action.to_y !== undefined) {
+ fromX = action.from_x;
+ fromY = action.from_y;
+ toX = action.to_x;
+ toY = action.to_y;
+
+ // Validate coordinates are within viewport bounds
+ const viewport = page.viewportSize();
+ if (!viewport) {
+ return { success: false, error: 'Viewport size not available from page.' };
+ }
+ if (fromX < 0 || fromY < 0 || fromX > viewport.width || fromY > viewport.height) {
+ return { success: false, error: `Invalid from coordinates (${fromX}, ${fromY}), viewport is ${viewport.width}x${viewport.height}` };
+ }
+ if (toX < 0 || toY < 0 || toX > viewport.width || toY > viewport.height) {
+ return { success: false, error: `Invalid to coordinates (${toX}, ${toY}), viewport is ${viewport.width}x${viewport.height}` };
+ }
- if (!fromExists) {
- return { success: false, error: `Source element with ref ${fromRef} not found` };
+ // Show highlight at start and end positions for pixel mode
+ await this.showClickHighlight(page, fromX, fromY);
+ await this.showClickHighlight(page, toX, toY);
}
+ // Ref mode: get coordinates from elements (supports iframes)
+ else if (action.from_ref && action.to_ref) {
+ await this.getSnapshot(page);
- if (!toExists) {
- return { success: false, error: `Target element with ref ${toRef} not found` };
- }
+ // Use findElementAcrossFrames to support elements inside iframes
+ const fromResult = await this.findElementAcrossFrames(page, action.from_ref);
+ const toResult = await this.findElementAcrossFrames(page, action.to_ref);
- // Get the center coordinates of both elements
- const fromBox = await fromElement.boundingBox();
- const toBox = await toElement.boundingBox();
+ if (!fromResult) {
+ return { success: false, error: `Source element with ref ${action.from_ref} not found in any frame` };
+ }
+ if (!toResult) {
+ return { success: false, error: `Target element with ref ${action.to_ref} not found in any frame` };
+ }
- if (!fromBox) {
- return { success: false, error: `Could not get bounding box for source element with ref ${fromRef}` };
- }
+ const fromBox = await fromResult.locator.boundingBox();
+ const toBox = await toResult.locator.boundingBox();
- if (!toBox) {
- return { success: false, error: `Could not get bounding box for target element with ref ${toRef}` };
- }
+ if (!fromBox) {
+ return { success: false, error: `Could not get bounding box for source element` };
+ }
+ if (!toBox) {
+ return { success: false, error: `Could not get bounding box for target element` };
+ }
- const fromX = fromBox.x + fromBox.width / 2;
- const fromY = fromBox.y + fromBox.height / 2;
- const toX = toBox.x + toBox.width / 2;
- const toY = toBox.y + toBox.height / 2;
+ fromX = fromBox.x + fromBox.width / 2;
+ fromY = fromBox.y + fromBox.height / 2;
+ toX = toBox.x + toBox.width / 2;
+ toY = toBox.y + toBox.height / 2;
+ } else {
+ return { success: false, error: 'Must provide either (from_ref, to_ref) or (from_x, from_y, to_x, to_y)' };
+ }
// Perform the drag operation
await page.mouse.move(fromX, fromY);
await page.mouse.down();
- // Destination coordinates
await page.mouse.move(toX, toY);
await page.mouse.up();
@@ -1420,6 +1742,12 @@ export class HybridBrowserSession {
if (!mouseControlResult.success) {
throw new Error(`Action failed: ${mouseControlResult.error}`);
}
+
+ // Use custom result message if click was ineffective
+ if (mouseControlResult.resultMessage) {
+ customMessage = mouseControlResult.resultMessage;
+ }
+
actionExecutionTime = Date.now() - mouseControlStart;
break;
}
@@ -1427,7 +1755,7 @@ export class HybridBrowserSession {
case 'mouse_drag': {
elementSearchTime = Date.now() - elementSearchStart;
const mouseDragStart = Date.now();
- const mouseDragResult = await this.performMouseDrag(page, action.from_ref, action.to_ref);
+ const mouseDragResult = await this.performMouseDrag(page, action);
if (!mouseDragResult.success) {
throw new Error(`Action failed: ${mouseDragResult.error}`);
@@ -2080,7 +2408,11 @@ export class HybridBrowserSession {
return tabInfo;
}
- async takeScreenshot(): Promise<{ buffer: Buffer; timing: { screenshot_time_ms: number } }> {
+ async takeScreenshot(): Promise<{
+ buffer: Buffer;
+ timing: { screenshot_time_ms: number };
+ viewport: { width: number; height: number };
+ }> {
const startTime = Date.now();
const page = await this.getCurrentPage();
@@ -2090,6 +2422,7 @@ export class HybridBrowserSession {
fullPage: browserConfig.fullPageScreenshot
});
+ const viewport = page.viewportSize() || browserConfig.viewport;
const screenshotTime = Date.now() - startTime;
return {
@@ -2097,6 +2430,7 @@ export class HybridBrowserSession {
timing: {
screenshot_time_ms: screenshotTime,
},
+ viewport,
};
}
diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.ts
index ebc99c45b..8d7262961 100644
--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.ts
+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.ts
@@ -83,6 +83,7 @@ export interface WebSocketConfig {
session_id?: string;
viewport_limit: boolean;
fullVisualMode?: boolean;
+ nearestElementsCount: number; // Number of nearest elements to show for ineffective clicks
}
// Default stealth configuration
@@ -152,7 +153,8 @@ function getDefaultBrowserConfig(): BrowserConfig {
function getDefaultWebSocketConfig(): WebSocketConfig {
return {
browser_log_to_file: false,
- viewport_limit: false
+ viewport_limit: false,
+ nearestElementsCount: 5 // Default number of nearest elements for ineffective click detection
};
}
@@ -222,6 +224,7 @@ export class ConfigLoader {
if (config.session_id !== undefined) wsConfig.session_id = config.session_id;
if (config.viewport_limit !== undefined) wsConfig.viewport_limit = config.viewport_limit;
if (config.fullVisualMode !== undefined) wsConfig.fullVisualMode = config.fullVisualMode;
+ if (config.nearestElementsCount !== undefined) wsConfig.nearestElementsCount = config.nearestElementsCount;
// CDP connection options
if (config.connectOverCdp !== undefined) browserConfig.connectOverCdp = config.connectOverCdp;
diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.ts
index e46371b6b..d0fce3c92 100644
--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.ts
+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.ts
@@ -1,5 +1,5 @@
import {HybridBrowserSession} from './browser-session';
-import {ActionResult, BrowserAction, BrowserToolkitConfig, PageStabilityResult, SnapshotResult, TabInfo, VisualMarkResult} from './types';
+import {ActionResult, BrowserAction, BrowserToolkitConfig, PageStabilityResult, SnapshotResult, TabInfo, VisualMarkResult, INTERACTIVE_ROLES} from './types';
import {ConfigLoader} from './config-loader';
import {ConsoleMessage} from 'playwright';
import {SomScreenshotInjected} from './som-screenshot-injected';
@@ -191,7 +191,6 @@ export class HybridBrowserToolkit {
async getSomScreenshot(): Promise<VisualMarkResult & { timing: any }> {
const startTime = Date.now();
- console.log('[HybridBrowserToolkit] Starting getSomScreenshot...');
try {
// Get page and snapshot data
@@ -200,11 +199,9 @@ export class HybridBrowserToolkit {
// Parse clickable elements from snapshot text
const clickableElements = this.parseClickableElements(snapshotResult.snapshot);
- console.log(`[HybridBrowserToolkit] Found ${clickableElements.size} clickable elements`);
// Apply hierarchy-based filtering
const filteredElements = filterClickableByHierarchy(snapshotResult.snapshot, clickableElements);
- console.log(`[HybridBrowserToolkit] After filtering: ${filteredElements.size} elements remain`);
// Use injected SOM-screenshot method without export path
const result = await SomScreenshotInjected.captureOptimized(
@@ -235,21 +232,59 @@ export class HybridBrowserToolkit {
}
}
+ async getScreenshot(): Promise<VisualMarkResult & { timing: any; viewport?: { width: number; height: number } }> {
+ const startTime = Date.now();
+ console.log('[HybridBrowserToolkit] Starting getScreenshot...');
+
+ try {
+ const result = await this.session.takeScreenshot();
+ const base64Image = `data:image/png;base64,${result.buffer.toString('base64')}`;
+ const totalTime = Date.now() - startTime;
+
+ return {
+ text: `Screenshot captured successfully. Viewport size: ${result.viewport.width}x${result.viewport.height}. Valid coordinate range: x=[0, ${result.viewport.width}], y=[0, ${result.viewport.height}]`,
+ images: [base64Image],
+ timing: {
+ total_time_ms: totalTime,
+ screenshot_time_ms: result.timing.screenshot_time_ms,
+ },
+ viewport: result.viewport,
+ };
+ } catch (error) {
+ const totalTime = Date.now() - startTime;
+ return {
+ text: `Error capturing screenshot: ${error}`,
+ images: [],
+ timing: {
+ total_time_ms: totalTime,
+ screenshot_time_ms: 0,
+ },
+ };
+ }
+ }
/**
- * Parse clickable elements from snapshot text
+ * Parse clickable/interactive elements from snapshot text
*/
private parseClickableElements(snapshotText: string): Set<string> {
const clickableElements = new Set<string>();
- const lines = snapshotText.split('\n');
- for (const line of lines) {
- // Look for lines containing [cursor=pointer] or [active] and extract ref
+ for (const line of snapshotText.split('\n')) {
+ const refMatch = line.match(/\[ref=([^\]]+)\]/);
+ if (!refMatch) continue;
+
+ const ref = refMatch[1];
+
+ // Include elements with cursor=pointer or active state
if (line.includes('[cursor=pointer]') || line.includes('[active]')) {
- const refMatch = line.match(/\[ref=([^\]]+)\]/);
- if (refMatch) {
- clickableElements.add(refMatch[1]);
- }
+ clickableElements.add(ref);
+ continue;
+ }
+
+ // Include interactive form elements by role (uses shared INTERACTIVE_ROLES)
+ const roleMatch = line.match(/^\s*-\s+(\w+)\s/);
+ if (roleMatch && INTERACTIVE_ROLES.has(roleMatch[1])) {
+ clickableElements.add(ref);
}
}
@@ -352,8 +387,15 @@ export class HybridBrowserToolkit {
return this.executeActionWithSnapshot(action);
}
- async mouseDrag(from_ref: string, to_ref: string): Promise<any> {
- const action: BrowserAction = { type: 'mouse_drag', from_ref, to_ref };
+ async mouseDrag(params: {
+ from_ref?: string;
+ to_ref?: string;
+ from_x?: number;
+ from_y?: number;
+ to_x?: number;
+ to_y?: number;
+ }): Promise<any> {
+ const action: BrowserAction = { type: 'mouse_drag', ...params };
return this.executeActionWithSnapshot(action);
}
diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/som-screenshot-injected.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/som-screenshot-injected.ts
index a649a4e6a..285e4274e 100644
--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/som-screenshot-injected.ts
+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/som-screenshot-injected.ts
@@ -21,11 +21,6 @@ export class SomScreenshotInjected {
const startTime = Date.now();
try {
- // Use the already filtered clickableElements directly
- const filterStartTime = Date.now();
- const filterTime = Date.now() - filterStartTime;
- console.log(`Using pre-filtered clickable elements: ${clickableElements.size} elements`);
-
// Prepare element geometry data for export
const elementGeometry: any[] = [];
// Inject and capture in one go
@@ -33,22 +28,46 @@ export class SomScreenshotInjected {
const visibilityDebugInfo: any[] = [];
const result = await page.evaluate(async (data) => {
- const { elements, clickable, filterDebugInfo } = data;
+ const { elements, clickable, filterDebugInfo, enableDebug } = data;
const markedElements: any[] = [];
- // Debug info collector - include filter debug info
- const debugInfo: any[] = [...filterDebugInfo];
+ // Use Set for O(1) lookup instead of Array.includes O(n)
+ const clickableSet = new Set(clickable);
+
+ // Debug info collector - only if enabled
+ const debugInfo: any[] = enableDebug ? [...filterDebugInfo] : [];
// Helper function to check element visibility based on coordinates
+ // Returns both visibility result and cached elementsAtCenter for reuse
function checkElementVisibilityByCoords(
coords: { x: number, y: number, width: number, height: number },
ref: string,
elementInfo: any
- ): 'visible' | 'partial' | 'hidden' {
+ ): { visibility: 'visible' | 'partial' | 'hidden', elementsAtCenter: Element[] | null } {
// Skip if element is outside viewport
if (coords.y + coords.height < 0 || coords.y > window.innerHeight ||
coords.x + coords.width < 0 || coords.x > window.innerWidth) {
- return 'hidden';
+ return { visibility: 'hidden', elementsAtCenter: null };
+ }
+
+ // For elements inside iframes (indicated by frameIndex or frameUrl),
+ // we cannot use document.elementsFromPoint() to check visibility
+ // because it doesn't penetrate iframes. Check if an iframe exists
+ // at the element's position.
+ if (elementInfo?.frameIndex > 0 || elementInfo?.frameUrl) {
+ const centerX = coords.x + coords.width * 0.5;
+ const centerY = coords.y + coords.height * 0.5;
+
+ // Check if there's an iframe at this position
+ const iframeElements = document.elementsFromPoint(centerX, centerY);
+ for (const elem of iframeElements) {
+ if (elem.tagName.toUpperCase() === 'IFRAME') {
+ return { visibility: 'visible', elementsAtCenter: iframeElements };
+ }
+ }
+ // Element has frame info but no iframe found at position -
+ // still consider visible as iframe might be transformed/scrolled.
+ return { visibility: 'visible', elementsAtCenter: iframeElements };
}
// Simple approach: just check the center point
@@ -59,7 +78,7 @@ export class SomScreenshotInjected {
try {
const elementsAtCenter = document.elementsFromPoint(centerX, centerY);
if (!elementsAtCenter || elementsAtCenter.length === 0) {
- return 'hidden';
+ return { visibility: 'hidden', elementsAtCenter: null };
}
// Find our target element in the stack
@@ -80,18 +99,27 @@ export class SomScreenshotInjected {
// If target is topmost, it's definitely visible
if (targetIsTopmost) {
- return 'visible';
+ return { visibility: 'visible', elementsAtCenter };
}
// If not topmost, check if the topmost element is a child of our target
const topmostElem = elementsAtCenter[0];
- if (elem.contains(topmostElem)) {
- // Topmost is our child - element is visible
- return 'visible';
+ const containsTopmost = elem.contains(topmostElem);
+
+ // Also check if they share a common parent (sibling relationship in composite widgets)
+ // This handles Material Design buttons where DIV (ripple) and SPAN (text) are siblings
+ const shareParent = elem.parentElement && elem.parentElement.contains(topmostElem);
+ const isCompositeWidget = shareParent &&
+ ['DIV', 'SPAN', 'I', 'SVG', 'IMG'].includes(topmostElem.tagName.toUpperCase()) &&
+ ['DIV', 'SPAN', 'BUTTON', 'A'].includes(elem.tagName.toUpperCase());
+
+ if (containsTopmost || isCompositeWidget) {
+ // Topmost is our child or sibling in composite widget - element is visible
+ return { visibility: 'visible', elementsAtCenter };
}
// Otherwise, we're obscured
- return 'hidden';
+ return { visibility: 'hidden', elementsAtCenter };
}
}
@@ -100,11 +128,62 @@ export class SomScreenshotInjected {
// Special handling for composite widgets
const topElement = elementsAtCenter[0];
const tagName = topElement.tagName.toUpperCase();
+ const topRect = topElement.getBoundingClientRect();
+
+ // Check if topElement is a Web Component (custom element with Shadow DOM)
+ // Custom elements have a hyphen in their tag name (e.g., NTP-APP, MY-COMPONENT)
+ const isCustomElement = tagName.includes('-');
+ // Also check if it's a shadow host
+ const isShadowHost = !!(topElement as any).shadowRoot;
+
+ // If the top element is a Web Component that covers our target area,
+ // assume the target is visible inside the shadow DOM
+ if (isCustomElement || isShadowHost) {
+ // Check if our target coords are within the custom element's bounds
+ const targetInCustomElement =
+ coords.x >= topRect.left - 5 &&
+ coords.y >= topRect.top - 5 &&
+ coords.x + coords.width <= topRect.right + 5 &&
+ coords.y + coords.height <= topRect.bottom + 5;
+
+ if (targetInCustomElement) {
+ return { visibility: 'visible', elementsAtCenter };
+ }
+ }
// Get element role/type for better decision making
const elementRole = elementInfo?.role || '';
const elementTagName = elementInfo?.tagName || '';
+ // Check if topElement is likely a child of our target element using multiple strategies:
+ // 1. Check if topElement center is within target bounds (most reliable)
+ const topCenterX = topRect.left + topRect.width / 2;
+ const topCenterY = topRect.top + topRect.height / 2;
+ const topCenterInTarget =
+ topCenterX >= coords.x - 5 &&
+ topCenterX <= coords.x + coords.width + 5 &&
+ topCenterY >= coords.y - 5 &&
+ topCenterY <= coords.y + coords.height + 5;
+
+ // 2. Check for significant overlap between topElement and target
+ const overlapLeft = Math.max(topRect.left, coords.x);
+ const overlapRight = Math.min(topRect.right, coords.x + coords.width);
+ const overlapTop = Math.max(topRect.top, coords.y);
+ const overlapBottom = Math.min(topRect.bottom, coords.y + coords.height);
+ const overlapWidth = Math.max(0, overlapRight - overlapLeft);
+ const overlapHeight = Math.max(0, overlapBottom - overlapTop);
+ const overlapArea = overlapWidth * overlapHeight;
+ const topArea = topRect.width * topRect.height;
+ const significantOverlap = topArea > 0 && (overlapArea / topArea) > 0.5;
+
+ // If top element overlaps significantly with our target (like SPAN/DIV inside button),
+ // consider the target visible
+ if ((topCenterInTarget || significantOverlap) &&
+ (elementRole === 'button' || elementRole === 'link' ||
+ elementTagName.toUpperCase() === 'BUTTON' || elementTagName.toUpperCase() === 'A')) {
+ return { visibility: 'visible', elementsAtCenter };
+ }
+
// Only apply special handling for form controls that are part of composite widgets
if (['SELECT', 'INPUT', 'TEXTAREA', 'BUTTON'].includes(tagName)) {
const isFormRelatedElement = ['combobox', 'select', 'textbox', 'searchbox', 'spinbutton'].includes(elementRole) ||
@@ -119,49 +198,44 @@ export class SomScreenshotInjected {
// Check for specific composite widget patterns
// For combobox with search input (like Amazon search)
if (elementRole === 'combobox' && tagName === 'INPUT') {
- // This is likely a search box with category selector - mark as visible
- return 'visible';
+ return { visibility: 'visible', elementsAtCenter };
}
// For button/generic elements covered by INPUT with exact same bounds
- // This usually indicates the INPUT is the actual interactive element for the button
if ((elementRole === 'button' || elementRole === 'generic') && tagName === 'INPUT') {
const rectMatch = Math.abs(rect.left - coords.x) < 2 &&
Math.abs(rect.top - coords.y) < 2 &&
Math.abs(rect.width - coords.width) < 2 &&
Math.abs(rect.height - coords.height) < 2;
if (rectMatch) {
- // The INPUT is the actual interactive element for this button
- return 'visible';
+ return { visibility: 'visible', elementsAtCenter };
}
}
- // For other form-related elements, only mark as visible if they share similar positioning
- // (i.e., they're likely part of the same widget)
+ // For other form-related elements with similar positioning
const sizeDiff = Math.abs(rect.width - coords.width) + Math.abs(rect.height - coords.height);
- if (sizeDiff < 50) { // Tolerance for size difference
- return 'visible';
+ if (sizeDiff < 50) {
+ return { visibility: 'visible', elementsAtCenter };
}
}
}
- return 'hidden';
+ return { visibility: 'hidden', elementsAtCenter };
}
- return 'partial';
+ return { visibility: 'partial', elementsAtCenter };
} catch (e) {
// Fallback: use simple elementFromPoint check
const elem = document.elementFromPoint(centerX, centerY);
- if (!elem) return 'hidden';
+ if (!elem) return { visibility: 'hidden', elementsAtCenter: null };
const rect = elem.getBoundingClientRect();
- // Check if the element at center matches our bounds
if (Math.abs(rect.left - coords.x) < 5 &&
Math.abs(rect.top - coords.y) < 5) {
- return 'visible';
+ return { visibility: 'visible', elementsAtCenter: null };
}
- return 'partial';
+ return { visibility: 'partial', elementsAtCenter: null };
}
}
@@ -183,40 +257,31 @@ export class SomScreenshotInjected {
const elementStates = new Map<string, 'visible' | 'partial' | 'hidden'>();
Object.entries(elements).forEach(([ref, element]: [string, any]) => {
- if (element.coordinates && clickable.includes(ref)) {
- const visibility = checkElementVisibilityByCoords(element.coordinates, ref, element);
- elementStates.set(ref, visibility);
-
- // Add debug info
- const centerX = element.coordinates.x + element.coordinates.width * 0.5;
- const centerY = element.coordinates.y + element.coordinates.height * 0.5;
-
- try {
- const elementsAtCenter = document.elementsFromPoint(centerX, centerY);
- const topmostElement = elementsAtCenter[0];
+ // Use Set for O(1) lookup
+ if (element.coordinates && clickableSet.has(ref)) {
+ const result = checkElementVisibilityByCoords(element.coordinates, ref, element);
+ elementStates.set(ref, result.visibility);
+
+ // Add debug info only if enabled (reuse cached elementsAtCenter)
+ if (enableDebug) {
+ const centerX = element.coordinates.x + element.coordinates.width * 0.5;
+ const centerY = element.coordinates.y + element.coordinates.height * 0.5;
+ const elementsAtCenter = result.elementsAtCenter;
+ const topmostElement = elementsAtCenter?.[0];
debugInfo.push({
ref,
coords: element.coordinates,
centerPoint: { x: centerX, y: centerY },
- visibilityResult: visibility,
+ visibilityResult: result.visibility,
elementRole: element.role || 'unknown',
elementTagName: element.tagName || '',
topmostElement: topmostElement ? {
tagName: topmostElement.tagName,
- className: topmostElement.className,
+ className: (topmostElement as HTMLElement).className || '',
id: topmostElement.id
} : null,
- elementsAtCenterCount: elementsAtCenter.length
- });
- } catch (e) {
- debugInfo.push({
- ref,
- coords: element.coordinates,
- visibilityResult: visibility,
- elementRole: element.role || 'unknown',
- elementTagName: element.tagName || '',
- error: 'Failed to get elements at center'
+ elementsAtCenterCount: elementsAtCenter?.length || 0
});
}
}
@@ -330,7 +395,7 @@ export class SomScreenshotInjected {
// Add labels and collect geometry data (only for filtered elements)
Object.entries(elements).forEach(([ref, element]: [string, any]) => {
- if (element.coordinates && clickable.includes(ref)) {
+ if (element.coordinates && clickableSet.has(ref)) {
const state = elementStates.get(ref);
// Skip completely hidden elements
@@ -431,7 +496,7 @@ export class SomScreenshotInjected {
await new Promise(resolve => requestAnimationFrame(resolve));
return {
- overlayId: overlay.id, // Use the ID that was set earlier
+ overlayId: overlay.id,
elementCount: overlay.children.length,
markedElements,
debugInfo
@@ -439,19 +504,17 @@ export class SomScreenshotInjected {
}, {
elements: snapshotResult.elements,
clickable: Array.from(clickableElements),
- filterDebugInfo: []
+ filterDebugInfo: [],
+ enableDebug: !!exportPath // Only enable debug when exporting
});
- // Take screenshot
+ // Take screenshot immediately (no need to wait)
const screenshotBuffer = await page.screenshot({
fullPage: false,
type: 'png'
});
- // Keep the overlay visible for 1 second before cleanup
- await page.waitForTimeout(1000);
-
- // Clean up
+ // Clean up overlay immediately after screenshot
await page.evaluate((overlayId) => {
const overlay = document.getElementById(overlayId);
if (overlay) overlay.remove();
@@ -523,15 +586,15 @@ export class SomScreenshotInjected {
images: [dataUrl],
timing: {
total_time_ms: Date.now() - startTime,
- screenshot_time_ms: Date.now() - startTime - 1100, // Approximate screenshot time (excluding 1s wait)
+ screenshot_time_ms: Date.now() - startTime,
snapshot_time_ms: 0, // Will be filled by caller
coordinate_enrichment_time_ms: 0, // Will be filled by caller
- visual_marking_time_ms: 1100, // Injection, rendering and 1s display time
+ visual_marking_time_ms: Date.now() - startTime,
injection_method: 'optimized',
elements_count: result.elementCount,
- display_duration_ms: 1000, // Time the overlay is kept visible
- parent_child_filter_time_ms: filterTime,
- filtered_count: 0 // Filtering is done before this method is called
+ display_duration_ms: 0, // No artificial wait
+ parent_child_filter_time_ms: 0, // Filtering is done before this method
+ filtered_count: 0
}
};
diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/src/types.ts b/camel/toolkits/hybrid_browser_toolkit/ts/src/types.ts
index a656e876b..e8f3c6540 100644
--- a/camel/toolkits/hybrid_browser_toolkit/ts/src/types.ts
+++ b/camel/toolkits/hybrid_browser_toolkit/ts/src/types.ts
@@ -125,8 +125,14 @@ export interface MouseAction {
export interface MouseDragAction {
type: 'mouse_drag';
- from_ref: string;
- to_ref: string;
+ // Ref mode
+ from_ref?: string;
+ to_ref?: string;
+ // Pixel mode
+ from_x?: number;
+ from_y?: number;
+ to_x?: number;
+ to_y?: number;
}
export interface PressKeyAction {
@@ -140,3 +146,25 @@ export interface VisualMarkResult {
text: string;
images: string[];
}
+
+/**
+ * Interactive element roles for click detection and visual marking
+ * Used by both browser-session.ts and hybrid-browser-toolkit.ts
+ */
+export const INTERACTIVE_ROLES = new Set([
+ 'button', 'link', 'textbox', 'checkbox', 'radio', 'combobox', 'listbox',
+ 'slider', 'spinbutton', 'switch', 'searchbox', 'menuitem',
+ 'menuitemcheckbox', 'menuitemradio', 'option', 'tab'
+]);
+
+/**
+ * Nearest element info for ineffective click detection
+ */
+export interface NearestElementInfo {
+ ref: string;
+ role: string;
+ name: string;
+ distance: number;
+ clickableCoord: { x: number; y: number };
+ boundingBox: { x: number; y: number; width: number; height: number };
+}
diff --git a/camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.js b/camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.js
index a130cc2c1..a24f89b7a 100644
--- a/camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.js
+++ b/camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.js
@@ -164,6 +164,17 @@ class WebSocketBrowserServer {
console.log(`Screenshot completed in ${endTime - startTime}ms`);
return result;
}
+
+ case 'get_screenshot': {
+ if (!this.toolkit) throw new Error('Toolkit not initialized');
+ console.log('Starting plain screenshot (no SOM)...');
+ const startTime = Date.now();
+ const result = await this.toolkit.getScreenshot();
+ const endTime = Date.now();
+ console.log(`Plain screenshot completed in ${endTime - startTime}ms`);
+ return result;
+ }
+
case 'click':
if (!this.toolkit) throw new Error('Toolkit not initialized');
return await this.toolkit.click(params.ref);
@@ -197,7 +208,7 @@ class WebSocketBrowserServer {
case 'mouse_drag':
if (!this.toolkit) throw new Error('Toolkit not initialized');
- return await this.toolkit.mouseDrag(params.from_ref, params.to_ref);
+ return await this.toolkit.mouseDrag(params);
case 'press_key':
if (!this.toolkit) throw new Error('Toolkit not initialized');
diff --git a/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py b/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py
index 4352d8ec9..5eae69940 100644
--- a/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py
+++ b/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py
@@ -777,14 +777,31 @@ class WebSocketBrowserWrapper:
@action_logger
async def get_som_screenshot(self) -> ToolResult:
- """Get screenshot."""
- logger.info("Requesting screenshot via WebSocket...")
+ """Get screenshot with SOM markers."""
+ logger.info("Requesting SOM screenshot via WebSocket...")
start_time = time.time()
response = await self._send_command('get_som_screenshot', {})
end_time = time.time()
- logger.info(f"Screenshot completed in {end_time - start_time:.2f}s")
+ logger.info(
+ f"SOM screenshot completed in {end_time - start_time:.2f}s"
+ )
+
+ return ToolResult(text=response['text'], images=response['images'])
+
+ @action_logger
+ async def get_screenshot(self) -> ToolResult:
+ """Get plain screenshot without SOM markers."""
+ logger.info("Requesting plain screenshot via WebSocket...")
+ start_time = time.time()
+
+ response = await self._send_command('get_screenshot', {})
+
+ end_time = time.time()
+ logger.info(
+ f"Plain screenshot completed in {end_time - start_time:.2f}s"
+ )
return ToolResult(text=response['text'], images=response['images'])
@@ -892,13 +909,39 @@ class WebSocketBrowserWrapper:
return response
@action_logger
- async def mouse_drag(self, from_ref: str, to_ref: str) -> Dict[str, Any]:
- """Control the mouse to drag and drop in the browser using ref IDs."""
- response = await self._send_command(
- 'mouse_drag',
- {'from_ref': from_ref, 'to_ref': to_ref},
- )
- return response
+ async def mouse_drag(
+ self,
+ from_ref: Optional[str] = None,
+ to_ref: Optional[str] = None,
+ from_x: Optional[float] = None,
+ from_y: Optional[float] = None,
+ to_x: Optional[float] = None,
+ to_y: Optional[float] = None,
+ ) -> Dict[str, Any]:
+ """Drag and drop using ref IDs or pixel coordinates.
+
+ NOTE: This method accepts both ref and pixel parameters, but mixing
+ them is prevented at a higher level. The toolkit's _create_mode_wrapper
+ generates mode-specific wrappers with exclusive signatures:
+ - full_visual_mode: only (from_x, from_y, to_x, to_y) exposed
+ - normal mode: only (from_ref, to_ref) exposed
+ So users cannot mix ref and coordinate modes through the toolkit API.
+ """
+ params: Dict[str, Any] = {}
+ if from_ref is not None and to_ref is not None:
+ params = {'from_ref': from_ref, 'to_ref': to_ref}
+ elif all(v is not None for v in [from_x, from_y, to_x, to_y]):
+ params = {
+ 'from_x': from_x,
+ 'from_y': from_y,
+ 'to_x': to_x,
+ 'to_y': to_y,
+ }
+ else:
+ raise ValueError(
+ "Provide (from_ref, to_ref) or (from_x, from_y, to_x, to_y)"
+ )
+ return await self._send_command('mouse_drag', params)
@action_logger
async def press_key(self, keys: List[str]) -> Dict[str, Any]:
@@ -906,6 +949,22 @@ class WebSocketBrowserWrapper:
response = await self._send_command('press_key', {'keys': keys})
return response
+ @action_logger
+ async def batch_keyboard_input(
+ self,
+ operations: List[Dict[str, Any]],
+ skip_stability_wait: bool = True,
+ ) -> Dict[str, Any]:
+ """Execute batch keyboard operations."""
+ response = await self._send_command(
+ 'batch_keyboard_input',
+ {
+ 'operations': operations,
+ 'skipStabilityWait': skip_stability_wait,
+ },
+ )
+ return response
+
@action_logger
async def back(self) -> Dict[str, Any]:
"""Navigate back."""
diff --git a/pyproject.toml b/pyproject.toml
index c818b4535..47583dcf3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -717,4 +717,4 @@ skip = '.git*,*.pdf,*.svg,*.lock,*.css,examples/toolkits/semantic_scholar_toolki
check-hidden = true
# Ignore long lines as usually some kind of base64 encodings e.g. in ipynb
ignore-regex = '^\s*"image/\S+": ".*|^.{300,}|\b(NotIn|Unsupport)\b'
-ignore-words-list = 'ans,datas,rouge,doubleClick,OCE,ACI,aci,Pinter,SoM,checkin,ND,'
+ignore-words-list = 'ans,datas,rouge,doubleClick,OCE,ACI,aci,Pinter,SoM,SOM,checkin,ND,'