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
fix all actions to use kwargs at callsites
Nick Sweeting10ec1e884141
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex cee7e81b7..23561096f 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -40,7 +40,10 @@ class Registry(Generic[Context]):def _get_special_param_types(self) -> dict[str, type]:"""Get the expected types for special parameters from SpecialActionParameters"""- # Manually define the expected types to avoid issues with Optional handling+ # Manually define the expected types to avoid issues with Optional handling.+ # we should try to reduce this list to 0 if possible, give as few standardized objects to all the actions+ # but each driver should decide what is relevant to expose the action methods,+ # e.g. playwright page, 2fa code getters, sensitive_data wrappers, other context, etc.return {'context': None, # Context is a TypeVar, so we can't validate type'browser_session': BrowserSession,@@ -62,7 +65,7 @@ class Registry(Generic[Context]):Normalize action function to accept only kwargs.Returns:- - Normalized function that accepts (*, params: ParamModel, **special_params)+ - Normalized function that accepts (*_, params: ParamModel, **special_params)- The param model to use for registration"""sig = signature(func)@@ -70,7 +73,8 @@ class Registry(Generic[Context]):special_param_types = self._get_special_param_types()special_param_names = set(special_param_types.keys())- # Step 1: Validate no **kwargs in original function+ # Step 1: Validate no **kwargs in original function signature+ # if it needs default values it must use a dedicated param_model: BaseModel insteadfor param in parameters:if param.kind == Parameter.VAR_KEYWORD:raise ValueError(@@ -145,11 +149,11 @@ class Registry(Generic[Context]):# Step 4: Create normalized wrapper function@functools.wraps(func)- async def normalized_wrapper(*, params: BaseModel | None = None, **kwargs):+ async def normalized_wrapper(*args, params: BaseModel | None = None, **kwargs):"""Normalized action that only accepts kwargs"""# Validate no positional args- if any(k.startswith('_') for k in kwargs.keys()):- raise TypeError(f'{func.__name__}() does not accept positional arguments')+ if args:+ raise TypeError(f'{func.__name__}() does not accept positional arguments, only keyword arguments are allowed')# Prepare arguments for original functioncall_args = []@@ -164,6 +168,18 @@ class Registry(Generic[Context]):else:# Type 2 pattern - unpack params into positional argsstart_idx = 0++ # If params is None, try to create it from kwargs+ if params is None and action_params:+ # Extract action params from kwargs+ action_kwargs = {}+ for param in action_params:+ if param.name in kwargs:+ action_kwargs[param.name] = kwargs[param.name]+ if action_kwargs:+ # Use the param_model which has the correct types defined+ params = param_model(**action_kwargs)+if params is not None:params_dict = params.model_dump()# Add action params in correct orderdiff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex e57fc747e..d16221c15 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -790,7 +790,7 @@ class Controller(Generic[Context]):async def read_cell_contents(browser_session: BrowserSession, cell_or_range: str):page = await browser_session.get_current_page()- await select_cell_or_range(browser_session, cell_or_range)+ await select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)await page.keyboard.press('ControlOrMeta+C')await asyncio.sleep(0.1)@@ -803,7 +803,7 @@ class Controller(Generic[Context]):async def update_cell_contents(browser_session: BrowserSession, cell_or_range: str, new_contents_tsv: str):page = await browser_session.get_current_page()- await select_cell_or_range(browser_session, cell_or_range)+ await select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)# simulate paste event from clipboard with TSV contentawait page.evaluate(f"""@@ -818,7 +818,7 @@ class Controller(Generic[Context]):async def clear_cell_contents(browser_session: BrowserSession, cell_or_range: str):page = await browser_session.get_current_page()- await select_cell_or_range(browser_session, cell_or_range)+ await select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)await page.keyboard.press('Backspace')return ActionResult(extracted_content=f'Cleared cells: {cell_or_range}', include_in_memory=False)diff --git a/tests/ci/test_action_registry.py b/tests/ci/test_action_registry.pyindex 414436a86..24f2eae56 100644--- a/tests/ci/test_action_registry.py+++ b/tests/ci/test_action_registry.py@@ -431,6 +431,26 @@ class TestActionToActionCalling:class TestRegistryEdgeCases:"""Test edge cases and error conditions"""+ @pytest.mark.asyncio+ async def test_decorated_action_rejects_positional_args(self, registry, test_browser):+ """Test that decorated actions reject positional arguments"""++ @registry.action('Action that should reject positional args')+ async def test_action(cell_or_range: str, browser_session: BrowserSession):+ page = await browser_session.get_current_page()+ return ActionResult(extracted_content=f'Selected cell {cell_or_range} on {page.url}')++ # Test that calling with positional arguments raises TypeError+ with pytest.raises(+ TypeError, match='test_action\\(\\) does not accept positional arguments, only keyword arguments are allowed'+ ):+ await test_action(test_browser, 'A1:B2')++ # Test that calling with keyword arguments works+ result = await test_action(browser_session=test_browser, cell_or_range='A1:B2')+ assert isinstance(result, ActionResult)+ assert 'Selected cell A1:B2 on' in result.extracted_content+@pytest.mark.asyncioasync def test_missing_required_browser_session(self, registry):"""Test that actions requiring browser_session fail appropriately when not provided"""