Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Merge remote-tracking branch 'origin/main' into Enhancement/pause
magmueller76121bfcf11b
diff --cc browser_use/agent/service.pyindex 4b6fd9359,363f3e654..e7fb98f4a--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@@ -1044,17 -1029,24 +1049,39 @@@ class Agentreturn frame+ def pause(self) -> None:+ """Pause the agent before the next step"""+ logger.info('🔄 Agent pausing before next step')+ self._paused = True++ def resume(self) -> None:+ """Resume the agent"""+ logger.info('▶️ Agent resuming')+ self._paused = False++ def stop(self) -> None:+ """Stop the agent"""+ logger.info('⏹️ Agent stopping')+ self._stopped = True+++ def _convert_initial_actions(self, actions: List[Dict[str, Dict[str, Any]]]) -> List[ActionModel]:+ """Convert dictionary-based actions to ActionModel instances"""+ converted_actions = []+ action_model = self.ActionModel+ for action_dict in actions:+ # Each action_dict should have a single key-value pair+ action_name = next(iter(action_dict))+ params = action_dict[action_name]++ # Get the parameter model for this action from registry+ action_info = self.controller.registry.registry.actions[action_name]+ param_model = action_info.param_model++ # Create validated parameters using the appropriate param model+ validated_params = param_model(**params)++ # Create ActionModel instance with the validated parameters+ action_model = self.ActionModel(**{action_name: validated_params})+ converted_actions.append(action_model)++ return converted_actionsdiff --cc tests/test_service.pyindex fd2ea0a9a,ec2632077..6e05e65f9--- a/tests/test_service.py+++ b/tests/test_service.py@@@ -1,109 -1,78 +1,127 @@@- from unittest.mock import AsyncMock, MagicMock, patch+ import os+ import sys-from unittest.mock import MagicMock, Mock++from unittest.mock import AsyncMock, MagicMock, Mock, patchimport pytestfrom langchain_core.language_models.chat_models import BaseChatModel+from browser_use.agent.message_manager.service import MessageManagerfrom browser_use.agent.service import Agent+from browser_use.agent.views import ActionResult, AgentOutput+ from browser_use.browser.browser import Browser+ from browser_use.browser.context import BrowserContext+from browser_use.browser.views import BrowserState-+ from browser_use.controller.registry.service import Registry+ from browser_use.controller.registry.views import ActionModel+ from browser_use.controller.service import Controller+# run with python -m pytest tests/test_service.py++++ # run test with:+ # python -m pytest tests/test_service.pyclass TestAgent:- """Test class for Agent"""+ @pytest.fixture+ def mock_controller(self):+ controller = Mock(spec=Controller)+ registry = Mock(spec=Registry)+ registry.registry = MagicMock()+ registry.registry.actions = {'test_action': MagicMock(param_model=MagicMock())} # type: ignore+ controller.registry = registry+ return controller++ @pytest.fixture+ def mock_llm(self):+ return Mock(spec=BaseChatModel)++ @pytest.fixture+ def mock_browser(self):+ return Mock(spec=Browser)++ @pytest.fixture+ def mock_browser_context(self):+ return Mock(spec=BrowserContext)++ def test_convert_initial_actions(self, mock_controller, mock_llm, mock_browser, mock_browser_context): # type: ignore+ """+ Test that the _convert_initial_actions method correctly converts+ dictionary-based actions to ActionModel instances.++ This test ensures that:+ 1. The method processes the initial actions correctly.+ 2. The correct param_model is called with the right parameters.+ 3. The ActionModel is created with the validated parameters.+ 4. The method returns a list of ActionModel instances.+ """+ # Arrange+ agent = Agent(+ task='Test task', llm=mock_llm, controller=mock_controller, browser=mock_browser, browser_context=mock_browser_context+ )+ initial_actions = [{'test_action': {'param1': 'value1', 'param2': 'value2'}}]++ # Mock the ActionModel+ mock_action_model = MagicMock(spec=ActionModel)+ mock_action_model_instance = MagicMock()+ mock_action_model.return_value = mock_action_model_instance+ agent.ActionModel = mock_action_model # type: ignore++ # Act+ result = agent._convert_initial_actions(initial_actions)++ # Assert+ assert len(result) == 1+ mock_controller.registry.registry.actions['test_action'].param_model.assert_called_once_with( # type: ignore+ param1='value1', param2='value2'+ )+ mock_action_model.assert_called_once()+ assert isinstance(result[0], MagicMock)+ assert result[0] == mock_action_model_instance++ # Check that the ActionModel was called with the correct parameters+ call_args = mock_action_model.call_args[1]+ assert 'test_action' in call_args+ assert call_args['test_action'] == mock_controller.registry.registry.actions['test_action'].param_model.return_value # type: ignore++ @pytest.mark.asyncio+ async def test_step_error_handling(self):+ """+ Test the error handling in the step method of the Agent class.+ This test simulates a failure in the get_next_action method and+ checks if the error is properly handled and recorded.+ """+ # Mock the LLM+ mock_llm = MagicMock(spec=BaseChatModel)++ # Mock the MessageManager+ with patch('browser_use.agent.service.MessageManager') as mock_message_manager:+ # Create an Agent instance with mocked dependencies+ agent = Agent(task='Test task', llm=mock_llm)++ # Mock the get_next_action method to raise an exception+ agent.get_next_action = AsyncMock(side_effect=ValueError('Test error'))++ # Mock the browser_context+ agent.browser_context = AsyncMock()+ agent.browser_context.get_state = AsyncMock(+ return_value=BrowserState(+ url='https://example.com',+ title='Example',+ element_tree=MagicMock(), # Mocked element tree+ tabs=[],+ selector_map={},+ screenshot='',+ )+ )++ # Mock the controller+ agent.controller = AsyncMock()++ # Call the step method+ await agent.step()++ # Assert that the error was handled and recorded+ assert agent.consecutive_failures == 1+ assert len(agent._last_result) == 1+ assert isinstance(agent._last_result[0], ActionResult)+ assert 'Test error' in agent._last_result[0].error+ assert agent._last_result[0].include_in_memory == True-- """Test class for Agent"""-- @pytest.mark.asyncio- async def test_step_error_handling(self):- """- Test the error handling in the step method of the Agent class.- This test simulates a failure in the get_next_action method and- checks if the error is properly handled and recorded.- """- # Mock the LLM- mock_llm = MagicMock(spec=BaseChatModel)-- # Mock the MessageManager- with patch('browser_use.agent.service.MessageManager') as mock_message_manager_class:- mock_message_manager = MagicMock()- mock_message_manager_class.return_value = mock_message_manager-- # Mock the ProductTelemetry- with patch('browser_use.agent'):- # Create an Agent instance with mocked dependencies- agent = Agent(task='Test task', llm=mock_llm)-- # Mock the get_next_action method to raise an exception- agent.get_next_action = AsyncMock(side_effect=ValueError('Test error'))-- # Mock the browser_context- agent.browser_context = AsyncMock()- agent.browser_context.get_state = AsyncMock(- return_value=BrowserState(- url='https://example.com',- title='Example',- element_tree=MagicMock(), # Provide a mock element_tree- tabs=[],- selector_map={},- screenshot='',- )- )-- # Mock the controller- agent.controller = AsyncMock()-- # Call the step method- await agent.step()-- # Assert that the error was handled and recorded- assert agent.consecutive_failures == 1- assert len(agent._last_result) == 1- assert isinstance(agent._last_result[0], ActionResult)- assert 'Test error' in agent._last_result[0].error- assert agent._last_result[0].include_in_memory == True