Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

added dragging along path

Dillon DuPont5fc627ed6973
diff --git a/libs/agent/agent/providers/anthropic/tools/computer.py b/libs/agent/agent/providers/anthropic/tools/computer.py
index 8425f35f70..ecf232bdbc 100644
--- a/libs/agent/agent/providers/anthropic/tools/computer.py
+++ b/libs/agent/agent/providers/anthropic/tools/computer.py
@@ -161,15 +161,17 @@ class ComputerTool(BaseComputerTool, BaseAnthropicTool):
self.logger.info(f"Moving cursor to ({x}, {y})")
await self.computer.interface.move_cursor(x, y)
elif action == "left_click_drag":
- self.logger.info(f"Dragging from ({x}, {y})")
- # First move to the position
- await self.computer.interface.move_cursor(x, y)
- # Then perform drag operation - check if drag_to exists or we need to use other methods
- try:
- await self.computer.interface.drag_to(x, y)
- except Exception as e:
- self.logger.error(f"Error during drag operation: {str(e)}")
- raise ToolError(f"Failed to perform drag: {str(e)}")
+ # Get the start coordinate from kwargs
+ start_coordinate = kwargs.get("start_coordinate")
+ if not start_coordinate:
+ raise ToolError("start_coordinate is required for left_click_drag action")
+
+ start_x, start_y = start_coordinate
+ end_x, end_y = x, y
+
+ self.logger.info(f"Dragging from ({start_x}, {start_y}) to ({end_x}, {end_y})")
+ await self.computer.interface.move_cursor(start_x, start_y)
+ await self.computer.interface.drag_to(end_x, end_y)
# Wait briefly for any UI changes
await asyncio.sleep(0.5)
diff --git a/libs/agent/agent/providers/openai/tools/computer.py b/libs/agent/agent/providers/openai/tools/computer.py
index 90ef593540..c5602f4e33 100644
--- a/libs/agent/agent/providers/openai/tools/computer.py
+++ b/libs/agent/agent/providers/openai/tools/computer.py
@@ -44,6 +44,7 @@ Action = Literal[
"double_click",
"screenshot",
"scroll",
+ "drag",
]
@@ -165,6 +166,11 @@ class ComputerTool(BaseComputerTool, BaseOpenAITool):
scroll_x = kwargs.get("scroll_x", 0) // 50
scroll_y = kwargs.get("scroll_y", 0) // 50
return await self.handle_scroll(x, y, scroll_x, scroll_y)
+ elif type == "drag":
+ path = kwargs.get("path")
+ if not path or not isinstance(path, list) or len(path) < 2:
+ raise ToolError("path is required for drag action and must contain at least 2 points")
+ return await self.handle_drag(path)
elif type == "screenshot":
return await self.screenshot()
elif type == "wait":
@@ -302,6 +308,41 @@ class ComputerTool(BaseComputerTool, BaseOpenAITool):
self.logger.error(f"Error in handle_scroll: {str(e)}")
raise ToolError(f"Failed to scroll at ({x}, {y}): {str(e)}")
+ async def handle_drag(self, path: List[Dict[str, int]]) -> ToolResult:
+ """Handle mouse drag operation using a path of coordinates.
+
+ Args:
+ path: List of coordinate points {"x": int, "y": int} defining the drag path
+
+ Returns:
+ ToolResult with the operation result and screenshot
+ """
+ try:
+ # Convert from [{"x": x, "y": y}, ...] format to [(x, y), ...] format
+ points = [(p["x"], p["y"]) for p in path]
+
+ # Perform drag action
+ if len(points) == 2:
+ await self.computer.interface.move_cursor(points[0][0], points[0][1])
+ await self.computer.interface.drag_to(points[1][0], points[1][1])
+ else:
+ await self.computer.interface.drag(points, button="left")
+
+ # Wait for UI to update
+ await asyncio.sleep(0.5)
+
+ # Take screenshot after action
+ screenshot = await self.computer.interface.screenshot()
+ base64_screenshot = base64.b64encode(screenshot).decode("utf-8")
+
+ return ToolResult(
+ output=f"Dragged from ({path[0]['x']}, {path[0]['y']}) to ({path[-1]['x']}, {path[-1]['y']})",
+ base64_image=base64_screenshot,
+ )
+ except Exception as e:
+ self.logger.error(f"Error in handle_drag: {str(e)}")
+ raise ToolError(f"Failed to perform drag operation: {str(e)}")
+
async def screenshot(self) -> ToolResult:
"""Take a screenshot."""
try:
diff --git a/libs/computer-server/computer_server/handlers/base.py b/libs/computer-server/computer_server/handlers/base.py
index 818d367cdb..08d57ad5b8 100644
--- a/libs/computer-server/computer_server/handlers/base.py
+++ b/libs/computer-server/computer_server/handlers/base.py
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
-from typing import Optional, Dict, Any
+from typing import Optional, Dict, Any, List, Tuple
class BaseAccessibilityHandler(ABC):
"""Abstract base class for OS-specific accessibility handlers."""
@@ -59,6 +59,17 @@ class BaseAutomationHandler(ABC):
duration: How long the drag should take in seconds
"""
pass
+
+ @abstractmethod
+ async def drag(self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5) -> Dict[str, Any]:
+ """Drag the cursor from current position to specified coordinates.
+
+ Args:
+ path: A list of tuples of x and y coordinates to drag to
+ button: The mouse button to use ('left', 'middle', 'right')
+ duration: How long the drag should take in seconds
+ """
+ pass
# Keyboard Actions
@abstractmethod
diff --git a/libs/computer-server/computer_server/handlers/macos.py b/libs/computer-server/computer_server/handlers/macos.py
index 180f083a85..abdedc410e 100644
--- a/libs/computer-server/computer_server/handlers/macos.py
+++ b/libs/computer-server/computer_server/handlers/macos.py
@@ -1,7 +1,7 @@
import pyautogui
import base64
from io import BytesIO
-from typing import Optional, Dict, Any, List
+from typing import Optional, Dict, Any, List, Tuple
from ctypes import byref, c_void_p, POINTER
from AppKit import NSWorkspace # type: ignore
import AppKit
@@ -563,6 +563,39 @@ class MacOSAutomationHandler(BaseAutomationHandler):
except Exception as e:
return {"success": False, "error": str(e)}
+ async def drag(
+ self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5
+ ) -> Dict[str, Any]:
+ try:
+ if not path or len(path) < 2:
+ return {"success": False, "error": "Path must contain at least 2 points"}
+
+ # Move to the first point
+ start_x, start_y = path[0]
+ pyautogui.moveTo(start_x, start_y)
+
+ # Press the mouse button
+ pyautogui.mouseDown(button=button)
+
+ # Calculate time between points to distribute duration evenly
+ step_duration = duration / (len(path) - 1) if len(path) > 1 else duration
+
+ # Move through each subsequent point
+ for x, y in path[1:]:
+ pyautogui.moveTo(x, y, duration=step_duration)
+
+ # Release the mouse button
+ pyautogui.mouseUp(button=button)
+
+ return {"success": True}
+ except Exception as e:
+ # Make sure to release the mouse button if an error occurs
+ try:
+ pyautogui.mouseUp(button=button)
+ except:
+ pass
+ return {"success": False, "error": str(e)}
+
# Keyboard Actions
async def type_text(self, text: str) -> Dict[str, Any]:
try:
diff --git a/libs/computer-server/computer_server/main.py b/libs/computer-server/computer_server/main.py
index c95918d857..d7f66f89a9 100644
--- a/libs/computer-server/computer_server/main.py
+++ b/libs/computer-server/computer_server/main.py
@@ -65,6 +65,7 @@ async def websocket_endpoint(websocket: WebSocket):
"type_text": manager.automation_handler.type_text,
"press_key": manager.automation_handler.press_key,
"drag_to": manager.automation_handler.drag_to,
+ "drag": manager.automation_handler.drag,
"hotkey": manager.automation_handler.hotkey,
"get_cursor_position": manager.automation_handler.get_cursor_position,
"get_screen_size": manager.automation_handler.get_screen_size,
diff --git a/libs/computer/computer/interface/base.py b/libs/computer/computer/interface/base.py
index 31106c14dd..8fcbd21ca6 100644
--- a/libs/computer/computer/interface/base.py
+++ b/libs/computer/computer/interface/base.py
@@ -79,6 +79,17 @@ class BaseComputerInterface(ABC):
"""
pass
+ @abstractmethod
+ async def drag(self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5) -> None:
+ """Drag the cursor along a path of coordinates.
+
+ Args:
+ path: List of (x, y) coordinate tuples defining the drag path
+ button: The mouse button to use ('left', 'middle', 'right')
+ duration: Total time in seconds that the drag operation should take
+ """
+ pass
+
# Keyboard Actions
@abstractmethod
async def type_text(self, text: str) -> None:
diff --git a/libs/computer/computer/interface/macos.py b/libs/computer/computer/interface/macos.py
index a3b99f7d97..2460086c83 100644
--- a/libs/computer/computer/interface/macos.py
+++ b/libs/computer/computer/interface/macos.py
@@ -328,6 +328,11 @@ class MacOSComputerInterface(BaseComputerInterface):
"drag_to", {"x": x, "y": y, "button": button, "duration": duration}
)
+ async def drag(self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5) -> None:
+ await self._send_command(
+ "drag", {"path": path, "button": button, "duration": duration}
+ )
+
# Keyboard Actions
async def type_text(self, text: str) -> None:
await self._send_command("type_text", {"text": text})