Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

better logging

Nick Sweeting6b8360c475eb
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index e77f038fd..49fbd0967 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -15,50 +15,27 @@ jobs:
find_tests:
runs-on: ubuntu-latest
outputs:
- matrix: ${{ steps.set-matrix.outputs.matrix }}
+ filename_list: ${{ steps.list_test_files.outputs.filename_list }} # ./tests/ci/test_controller.py, ./tests/ci/test_browser.py, etc.
steps:
- uses: actions/checkout@v4
- - id: set-matrix
- run: echo "::set-output name=matrix::$(ls tests/ci/*.py | jq -R -s -c 'split("\n")[:-1]')"
+ - id: list_test_files
+ run: echo "::set-output name=filename_list::$(ls tests/ci/*.py | jq -R -s -c 'split("\n")[:-1]')"
# https://code.dblock.org/2021/09/03/generating-task-matrix-by-looping-over-repo-files-with-github-actions.html
tests:
- name: ${{matrix.test}}
+ name: ${{matrix.test_filename}}
runs-on: ubuntu-latest
env:
IN_DOCKER: 'True'
strategy:
matrix:
- test: ${{ fromJson(needs.find_tests.outputs.matrix) }}
- # should be working in matrix ^
+ test_filename: ${{ fromJson(needs.find_tests.outputs.filename_list) }}
+ # autodiscovers all the files in tests/ci/test_*.py
# - test_browser
# - test_controller
# - test_browser_session
# - test_tab_management
- # - test_sensitive_data
- # - test_url_allowlist_security
- # TODO:
- # - browser/patchright
- # - browser/playwright
- # - browser/user_binary
- # - browser/remote_cdp
- # - models/openai
- # - models/google
- # - models/anthropic
- # - models/azure
- # - models/deepseek
- # - models/grok
- # - functionality/click
- # - functionality/tabs
- # - functionality/input
- # - functionality/scroll
- # - functionality/upload
- # - functionality/download
- # - functionality/save
- # - functionality/vision
- # - functionality/memory
- # - functionality/planner
- # - functionality/hooks
+ # ... and more
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
@@ -68,7 +45,7 @@ jobs:
- run: uv sync
- - name: Detect installed Playwright or Patchright version
+ - name: Detect installed Playwright version
run: echo "PLAYWRIGHT_VERSION=$(uv pip list --format json | jq -r '.[] | select(.name == "playwright") | .version')" >> $GITHUB_ENV
- name: Cache playwright binaries
@@ -81,4 +58,4 @@ jobs:
- run: playwright install chrome
- run: playwright install chromium
- - run: pytest tests/${{ matrix.test }}.py
+ - run: pytest tests/ci/${{ matrix.test_filename }}.py
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 27a7b254c..24d256606 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import logging
+import re
from langchain_core.messages import (
AIMessage,
@@ -181,18 +182,125 @@ class MessageManager:
msg = AIMessage(content=plan)
self._add_message_with_tokens(msg, position)
+ def _generate_history_log(self) -> str:
+ """Generate a formatted log string of message history for debugging / printing to terminal"""
+ total_input_tokens = 0
+ message_lines = []
+
+ for i, m in enumerate(self.state.history.messages):
+ total_input_tokens += m.metadata.tokens
+ is_last_message = i == len(self.state.history.messages) - 1
+
+ # Get emoji based on message type
+ message_type = m.message.__class__.__name__
+ if message_type == 'HumanMessage':
+ emoji = '๐Ÿ’ฌ'
+ elif message_type == 'AIMessage':
+ emoji = '๐Ÿง '
+ elif message_type == 'ToolMessage':
+ emoji = '๐Ÿ”จ'
+ else:
+ emoji = '๐ŸŽฎ' # fallback for other message types produced by controller
+
+ # Special handling for last message if it's a HumanMessage with list content
+ if is_last_message and message_type == 'HumanMessage' and isinstance(m.message.content, list):
+ # Extract text from the list content
+ text_content = ''
+ for item in m.message.content:
+ if isinstance(item, dict) and 'text' in item:
+ text_content += item['text']
+
+ # Clean up whitespace
+ text_content = re.sub(r'\s+', ' ', text_content).strip()
+
+ # Look for current state section
+ if '[Current state starts here]' in text_content:
+ # Extract just the current state portion
+ start_idx = text_content.find('[Current state starts here]')
+ content = text_content[start_idx : start_idx + 150] # Show more of current state
+ if len(text_content) > start_idx + 150:
+ content += '...'
+ else:
+ # Fallback to showing beginning of content
+ content = text_content[:150]
+ if len(text_content) > 150:
+ content += '...'
+ else:
+ # Get simple content preview - replace all repeated whitespace with single space
+ content = str(m.message.content)[:80]
+ content = re.sub(r'\s+', ' ', content).strip()
+
+ # For AIMessages with empty content but tool calls, show useful tool info
+ if hasattr(m.message, 'tool_calls') and m.message.tool_calls and not content.strip():
+ tool_call = m.message.tool_calls[0]
+ tool_name = tool_call.get('name', 'unknown')
+
+ if tool_name == 'AgentOutput':
+ # Extract useful info from AgentOutput
+ args = tool_call.get('args', {})
+ action_info = ''
+ if 'action' in args and args['action']:
+ # Get the action name
+ first_action = (
+ args['action'][0] if isinstance(args['action'], list) and args['action'] else args['action']
+ )
+ if isinstance(first_action, dict):
+ action_name = next(iter(first_action.keys())) if first_action else 'unknown'
+ action_info = f' โ†’ {action_name}()'
+
+ # Get the goal
+ goal_info = ''
+ if 'current_state' in args and isinstance(args['current_state'], dict):
+ next_goal = args['current_state'].get('next_goal', '').strip()
+ if next_goal:
+ goal_info = f': {next_goal[:40]}{"..." if len(next_goal) > 40 else ""}'
+
+ if action_info and goal_info:
+ content = f'{action_info[3:]}{goal_info}' # Remove ' โ†’ ' prefix
+ elif action_info:
+ content = action_info[3:] # Just the action name without ' โ†’ '
+ elif goal_info:
+ content = goal_info[2:] # Remove ': ' prefix for goal-only
+ else:
+ content = 'AgentOutput'
+ else:
+ content = f'[TOOL: {tool_name}]'
+ elif len(str(m.message.content)) > 80:
+ content += '...'
+
+ # Left-justify the emoji and token count for alignment
+ left_part = f' {emoji}[{m.metadata.tokens}]'
+
+ # For last message, allow multiple lines if needed
+ if is_last_message and '\n' not in content:
+ # Wrap long last messages nicely
+ import textwrap
+
+ wrapped = textwrap.wrap(content, width=80, subsequent_indent=' ' * 14)
+ if len(wrapped) > 2:
+ wrapped = wrapped[:2]
+ wrapped[-1] = wrapped[-1][:77] + '...'
+ message_lines.append(f'{left_part.ljust(12)}: {wrapped[0]}')
+ for line in wrapped[1:]:
+ message_lines.append(line)
+ else:
+ message_lines.append(f'{left_part.ljust(12)}: {content}')
+
+ # Log all messages in a single call
+ history_log = (
+ f'Messages in history: {len(self.state.history.messages)}:\n'
+ + '\n'.join(message_lines)
+ + f'\nTotal input tokens: {total_input_tokens}'
+ )
+ return history_log
+
@time_execution_sync('--get_messages')
def get_messages(self) -> list[BaseMessage]:
"""Get current message list, potentially trimmed to max tokens"""
-
msg = [m.message for m in self.state.history.messages]
- # debug which messages are in history with token count # log
- total_input_tokens = 0
- logger.debug(f'Messages in history: {len(self.state.history.messages)}:')
- for m in self.state.history.messages:
- total_input_tokens += m.metadata.tokens
- logger.debug(f'{m.message.__class__.__name__} - Token count: {m.metadata.tokens}')
- logger.debug(f'Total input tokens: {total_input_tokens}')
+
+ # Log message history for debugging
+ logger.debug(self._generate_history_log())
return msg
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 024b89f3b..db5cca27e 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -72,21 +72,46 @@ logger = logging.getLogger(__name__)
SKIP_LLM_API_KEY_VERIFICATION = os.environ.get('SKIP_LLM_API_KEY_VERIFICATION', 'false').lower()[0] in 'ty1'
-def log_response(response: AgentOutput) -> None:
+def log_response(response: AgentOutput, registry=None) -> None:
"""Utility function to log the model's response."""
if 'Success' in response.current_state.evaluation_previous_goal:
emoji = '๐Ÿ‘'
elif 'Failed' in response.current_state.evaluation_previous_goal:
- emoji = 'โš '
+ emoji = 'โš ๏ธ'
else:
- emoji = '๐Ÿคท'
+ emoji = 'โ“'
logger.info(f'{emoji} Eval: {response.current_state.evaluation_previous_goal}')
logger.info(f'๐Ÿง  Memory: {response.current_state.memory}')
logger.info(f'๐ŸŽฏ Next goal: {response.current_state.next_goal}')
for i, action in enumerate(response.action):
- logger.info(f'๐Ÿ› ๏ธ Action {i + 1}/{len(response.action)}: {action.model_dump_json(exclude_unset=True)}')
+ # Extract action name and parameters from the action model
+ action_data = action.model_dump(exclude_unset=True)
+ action_name = next(iter(action_data.keys())) if action_data else 'unknown'
+
+ # Get the parameters for this action
+ action_params = action_data.get(action_name, {}) if action_data else {}
+
+ # Get actual function module if registry is available
+ module_path = 'browser_use.controller.service'
+ if registry and action_name in registry.actions:
+ action_function = registry.actions[action_name].function
+ if hasattr(action_function, '__module__'):
+ module_path = action_function.__module__
+
+ # Format parameters as function call arguments
+ if action_params:
+ param_strings = []
+ for key, value in action_params.items():
+ if isinstance(value, str):
+ param_strings.append(f'{key}="{value}"')
+ else:
+ param_strings.append(f'{key}={value}')
+ params_str = ', '.join(param_strings)
+ logger.info(f'๐Ÿ› ๏ธ Next Action {i + 1}/{len(response.action)}: {module_path}.{action_name}({params_str})')
+ else:
+ logger.info(f'๐Ÿ› ๏ธ Next Action {i + 1}/{len(response.action)}: {module_path}.{action_name}()')
Context = TypeVar('Context')
@@ -498,7 +523,6 @@ class Agent(Generic[Context]):
@time_execution_async('--step (agent)')
async def step(self, step_info: AgentStepInfo | None = None) -> None:
"""Execute one step of the task"""
- logger.info(f'๐Ÿ“ Step {self.state.n_steps}')
browser_state_summary = None
model_output = None
result: list[ActionResult] = []
@@ -509,6 +533,8 @@ class Agent(Generic[Context]):
browser_state_summary = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=True)
current_page = await self.browser_session.get_current_page()
+ self._log_step_context(current_page, browser_state_summary)
+
# generate procedural memory if needed
if self.enable_memory and self.memory and self.state.n_steps % self.memory.config.memory_interval == 0:
self.memory.create_procedural_memory(self.state.n_steps)
@@ -668,6 +694,9 @@ class Agent(Generic[Context]):
)
self._make_history_item(model_output, browser_state_summary, result, metadata)
+ # Log step completion summary
+ self._log_step_completion_summary(step_start_time, result)
+
@time_execution_async('--handle_step_error (agent)')
async def _handle_step_error(self, error: Exception) -> list[ActionResult]:
"""Handle all types of errors that can occur during a step"""
@@ -763,7 +792,20 @@ class Agent(Generic[Context]):
input_messages = self._convert_input_messages(input_messages)
if self.tool_calling_method == 'raw':
- logger.debug(f'Using {self.tool_calling_method} for {self.chat_model_library}')
+ # Count messages and check for images
+ message_count = len(input_messages)
+ total_chars = sum(len(str(msg.content)) for msg in input_messages)
+ has_images = any(
+ hasattr(msg, 'content')
+ and isinstance(msg.content, list)
+ and any(isinstance(item, dict) and item.get('type') == 'image_url' for item in msg.content)
+ for msg in input_messages
+ )
+ current_tokens = getattr(self._message_manager.state.history, 'current_tokens', 0)
+
+ logger.debug(
+ f'๐Ÿง  LLM call: {self.chat_model_library} ({self.tool_calling_method}) | {message_count} msgs, ~{current_tokens} tokens, {total_chars} chars | {"๐Ÿ“ท images" if has_images else "no images"} | raw text output'
+ )
try:
output = self.llm.invoke(input_messages)
response = {'raw': output, 'parsed': None}
@@ -791,7 +833,20 @@ class Agent(Generic[Context]):
raise LLMException(401, 'LLM API call failed') from e
else:
- logger.debug(f'Using {self.tool_calling_method} for {self.chat_model_library}')
+ # Count messages and check for images
+ message_count = len(input_messages)
+ total_chars = sum(len(str(msg.content)) for msg in input_messages)
+ has_images = any(
+ hasattr(msg, 'content')
+ and isinstance(msg.content, list)
+ and any(isinstance(item, dict) and item.get('type') == 'image_url' for item in msg.content)
+ for msg in input_messages
+ )
+ current_tokens = getattr(self._message_manager.state.history, 'current_tokens', 0)
+
+ logger.debug(
+ f'๐Ÿง  LLM call: {self.chat_model_library} ({self.tool_calling_method}) | {message_count} msgs, ~{current_tokens} tokens, {total_chars} chars | {"๐Ÿ“ท images" if has_images else "no images"} | structured output + tools'
+ )
structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True, method=self.tool_calling_method)
response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignore
@@ -836,8 +891,9 @@ class Agent(Generic[Context]):
parsed.action = parsed.action[: self.settings.max_actions_per_step]
if not (hasattr(self.state, 'paused') and (self.state.paused or self.state.stopped)):
- log_response(parsed)
+ log_response(parsed, self.controller.registry.registry)
+ self._log_next_action_summary(parsed)
return parsed
def _log_agent_run(self) -> None:
@@ -846,6 +902,76 @@ class Agent(Generic[Context]):
logger.debug(f'Version: {self.version}, Source: {self.source}')
+ def _log_step_context(self, current_page, browser_state_summary) -> None:
+ """Log step context information"""
+ url_short = current_page.url[:50] + '...' if len(current_page.url) > 50 else current_page.url
+ interactive_count = len(browser_state_summary.selector_map) if browser_state_summary else 0
+ logger.info(f'๐Ÿ“ Step {self.state.n_steps}: Evaluating {url_short} ({interactive_count} interactive elements)...')
+
+ def _log_next_action_summary(self, parsed: 'AgentOutput') -> None:
+ """Log a comprehensive summary of the next action(s)"""
+ if not (logger.isEnabledFor(logging.DEBUG) and parsed.action):
+ return
+
+ action_count = len(parsed.action)
+
+ # Collect action details
+ action_details = []
+ for i, action in enumerate(parsed.action):
+ action_data = action.model_dump(exclude_unset=True)
+ action_name = next(iter(action_data.keys())) if action_data else 'unknown'
+ action_params = action_data.get(action_name, {}) if action_data else {}
+
+ # Format key parameters concisely
+ param_summary = []
+ if isinstance(action_params, dict):
+ for key, value in action_params.items():
+ if key == 'index':
+ param_summary.append(f'#{value}')
+ elif key == 'text' and isinstance(value, str):
+ text_preview = value[:30] + '...' if len(value) > 30 else value
+ param_summary.append(f'text="{text_preview}"')
+ elif key == 'url':
+ param_summary.append(f'url="{value}"')
+ elif key == 'success':
+ param_summary.append(f'success={value}')
+ elif isinstance(value, (str, int, bool)) and len(str(value)) < 20:
+ param_summary.append(f'{key}={value}')
+
+ param_str = f'({", ".join(param_summary)})' if param_summary else ''
+ action_details.append(f'{action_name}{param_str}')
+
+ # Create summary based on single vs multi-action
+ if action_count == 1:
+ logger.debug(f'โšก๏ธ Decided next action: {action_details[0]}')
+ else:
+ summary_lines = [f'โšก๏ธ Decided next {action_count} multi-actions:']
+ for i, detail in enumerate(action_details):
+ summary_lines.append(f' {i + 1}. {detail}')
+ logger.debug('\n'.join(summary_lines))
+
+ def _log_step_completion_summary(self, step_start_time: float, result: list[ActionResult]) -> None:
+ """Log step completion summary with action count, timing, and success/failure stats"""
+ if not result:
+ return
+
+ step_duration = time.time() - step_start_time
+ action_count = len(result)
+
+ # Count success and failures
+ success_count = sum(1 for r in result if not r.error)
+ failure_count = action_count - success_count
+
+ # Format success/failure indicators
+ success_indicator = f'โœ… {success_count}' if success_count > 0 else ''
+ failure_indicator = f'โŒ {failure_count}' if failure_count > 0 else ''
+ status_parts = [part for part in [success_indicator, failure_indicator] if part]
+ status_str = ' | '.join(status_parts) if status_parts else 'โœ… 0'
+
+ logger.info(
+ f'๐Ÿ“ Step {self.state.n_steps}: Complete. Ran {action_count} action{"s" if action_count != 1 else ""} in {step_duration:.2f}s: {status_str}'
+ )
+
def _log_agent_event(self, max_steps: int, agent_run_error: str | None = None) -> None:
"""Sent the agent event for this run to telemetry"""
@@ -1118,7 +1244,10 @@ class Agent(Generic[Context]):
results.append(result)
- logger.debug(f'Executed action {i + 1} / {len(actions)}')
+ # Get action name from the action model
+ action_data = action.model_dump(exclude_unset=True)
+ action_name = next(iter(action_data.keys())) if action_data else 'unknown'
+ logger.debug(f'Executed action {i + 1} / {len(actions)}: {action_name}()')
if results[-1].is_done or results[-1].error or i == len(actions) - 1:
break
@@ -1183,11 +1312,10 @@ class Agent(Generic[Context]):
async def log_completion(self) -> None:
"""Log the completion of the task"""
- logger.info('โœ… Task completed')
if self.state.history.is_successful():
- logger.info('โœ… Successfully')
+ logger.info('โœ… Task completed successfully')
else:
- logger.info('โŒ Unfinished')
+ logger.info('โŒ Task completed without success')
total_tokens = self.state.history.total_input_tokens()
logger.debug(f'๐Ÿ“ Total input tokens used (approximate): {total_tokens}')
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.py
index 4905a9a8c..e49903452 100644
--- a/browser_use/controller/registry/service.py
+++ b/browser_use/controller/registry/service.py
@@ -6,6 +6,7 @@ from inspect import iscoroutinefunction, signature
from typing import Any, Generic, Optional, TypeVar
from langchain_core.language_models.chat_models import BaseChatModel
+from playwright.async_api import Page
from pydantic import BaseModel, Field, create_model
from browser_use.browser import BrowserSession
@@ -26,6 +27,26 @@ Context = TypeVar('Context')
logger = logging.getLogger(__name__)
+class SpecialActionParameters(BaseModel):
+ """Model defining all special parameters that can be injected into actions"""
+
+ model_config = {'arbitrary_types_allowed': True}
+
+ context: Context | None = None
+ browser_session: BrowserSession | None = None
+ browser: BrowserSession | None = None # legacy support
+ browser_context: BrowserSession | None = None # legacy support
+ page: Page | None = None
+ page_extraction_llm: BaseChatModel | None = None
+ available_file_paths: list[str] | None = None
+ has_sensitive_data: bool = False
+
+ @classmethod
+ def get_browser_requiring_params(cls) -> set[str]:
+ """Get parameter names that require browser_session"""
+ return {'browser_session', 'browser', 'browser_context', 'page'}
+
+
class Registry(Generic[Context]):
"""Service for registering and managing actions"""
@@ -38,14 +59,11 @@ class Registry(Generic[Context]):
def _create_param_model(self, function: Callable) -> type[BaseModel]:
"""Creates a Pydantic model from function signature"""
sig = signature(function)
+ special_param_names = set(SpecialActionParameters.model_fields.keys())
params = {
name: (param.annotation, ... if param.default == param.empty else param.default)
for name, param in sig.parameters.items()
- if name != 'browser'
- and name != 'page_extraction_llm'
- and name != 'available_file_paths'
- and name != 'browser_session'
- and name != 'browser_context'
+ if name not in special_param_names
}
# TODO: make the types here work
return create_model(
@@ -59,9 +77,15 @@ class Registry(Generic[Context]):
description: str,
param_model: type[BaseModel] | None = None,
domains: list[str] | None = None,
+ allowed_domains: list[str] | None = None,
page_filter: Callable[[Any], bool] | None = None,
):
"""Decorator for registering actions"""
+ # Handle aliases: domains and allowed_domains are the same parameter
+ if allowed_domains is not None and domains is not None:
+ raise ValueError("Cannot specify both 'domains' and 'allowed_domains' - they are aliases for the same parameter")
+
+ final_domains = allowed_domains if allowed_domains is not None else domains
def decorator(func: Callable):
# Skip registration if action is in exclude_actions
@@ -90,7 +114,7 @@ class Registry(Generic[Context]):
description=description,
function=wrapped_func,
param_model=actual_param_model,
- domains=domains,
+ domains=final_domains,
page_filter=page_filter,
)
self.registry.actions[func.__name__] = action
@@ -110,7 +134,7 @@ class Registry(Generic[Context]):
#
context: Context | None = None,
) -> Any:
- """Execute a registered action"""
+ """Execute a registered action with enhanced parameter handling for backward compatibility"""
if action_name not in self.registry.actions:
raise ValueError(f'Action {action_name} not found')
@@ -122,85 +146,112 @@ class Registry(Generic[Context]):
except Exception as e:
raise ValueError(f'Invalid parameters {params} for action {action_name}: {type(e)}: {e}') from e
- # Check if the first parameter is a Pydantic model
+ # Analyze function signature for smart parameter injection
sig = signature(action.function)
parameters = list(sig.parameters.values())
- is_pydantic = parameters and issubclass(parameters[0].annotation, BaseModel)
parameter_names = [param.name for param in parameters]
+ # Check if the first parameter is a Pydantic model (using original safe logic)
+ # Only consider it pydantic if:
+ # 1. There are parameters
+ # 2. First parameter has a BaseModel annotation
+ # 3. AND the function signature actually takes a BaseModel as first param (not auto-generated)
+ try:
+ is_pydantic = (
+ parameters
+ and len(parameters) > 0
+ and hasattr(parameters[0], 'annotation')
+ and parameters[0].annotation != parameters[0].empty
+ and issubclass(parameters[0].annotation, BaseModel)
+ and
+ # Additional check: make sure the first parameter name suggests it's actually a pydantic model
+ parameters[0].name in ['params', 'param', 'model']
+ or parameters[0].name.endswith('_model')
+ )
+ except (TypeError, AttributeError):
+ is_pydantic = False
+
if sensitive_data:
validated_params = self._replace_sensitive_data(validated_params, sensitive_data, browser_session)
- # Check if the action requires browser
+ # Check if the action requires special parameters and validate they're provided
if (
- 'browser_session' in parameter_names or 'browser' in parameter_names or 'browser_context' in parameter_names
+ 'browser_session' in parameter_names
+ or 'browser' in parameter_names
+ or 'browser_context' in parameter_names
+ or 'page' in parameter_names
) and not browser_session:
raise ValueError(f'Action {action_name} requires browser_session but none provided.')
if 'page_extraction_llm' in parameter_names and not page_extraction_llm:
raise ValueError(f'Action {action_name} requires page_extraction_llm but none provided.')
if 'available_file_paths' in parameter_names and not available_file_paths:
raise ValueError(f'Action {action_name} requires available_file_paths but none provided.')
-
if 'context' in parameter_names and not context:
raise ValueError(f'Action {action_name} requires context but none provided.')
- # Prepare arguments based on parameter type
- extra_args = {}
- if 'context' in parameter_names:
- extra_args['context'] = context
- if 'browser_session' in parameter_names:
- extra_args['browser_session'] = browser_session
- if 'browser' in parameter_names: # support legacy browser: BrowserContext arg
+ # Create special parameters model with all available values
+ special_params_data = {
+ 'context': context,
+ 'browser_session': browser_session,
+ 'browser': browser_session, # legacy support
+ 'browser_context': browser_session, # legacy support
+ 'page_extraction_llm': page_extraction_llm,
+ 'available_file_paths': available_file_paths,
+ 'has_sensitive_data': action_name == 'input_text' and bool(sensitive_data),
+ }
+
+ # Handle async page parameter if needed
+ if 'page' in parameter_names and browser_session:
+ special_params_data['page'] = await browser_session.get_current_page()
+
+ # Create special parameters object without validation to preserve BrowserSession state
+ # We bypass model_validate to avoid copying BrowserSession and losing private attributes
+ special_params = SpecialActionParameters.model_construct(**special_params_data)
+
+ # Log legacy usage
+ if 'browser' in parameter_names:
logger.debug(
- f'You should update this action {action_name}(browser: BrowserContext) -> to take {action_name}(browser_session: BrowserSession) instead'
+ f'You should update this action {action_name}(browser: BrowserContext) -> to take {action_name}(browser_session: BrowserSession) instead'
)
- extra_args['browser'] = browser_session
- if 'browser_context' in parameter_names: # support legacy browser: BrowserContext arg
+ if 'browser_context' in parameter_names:
logger.debug(
- f'You should update this action {action_name}(browser_context: BrowserContext) -> to take {action_name}(browser_session: BrowserSession) instead'
+ f'You should update this action {action_name}(browser_context: BrowserContext) -> to take {action_name}(browser_session: BrowserSession) instead'
)
- extra_args['browser_context'] = browser_session
- if 'page_extraction_llm' in parameter_names:
- extra_args['page_extraction_llm'] = page_extraction_llm
- if 'available_file_paths' in parameter_names:
- extra_args['available_file_paths'] = available_file_paths
- if action_name == 'input_text' and sensitive_data:
- extra_args['has_sensitive_data'] = True
+ # Enhanced parameter injection logic using Pydantic
if is_pydantic:
- # Check for browser-related fields in Pydantic model
- # Another approach to fix the issue
- # First check if validated_params has browser_session field via reflection
- model_fields = vars(validated_params).get('__fields__', {})
-
- # Log some debug info
- logger.debug(f'Action: {action_name}, Model fields: {model_fields}')
-
- # Remove any browser-related keys from extra_args for Pydantic models
- browser_keys = ['browser_session', 'browser', 'browser_context']
- for key in browser_keys:
- if key in extra_args:
- logger.debug(f'Removing {key} from extra_args for Pydantic model {action_name}')
- extra_args.pop(key, None)
- return await action.function(
- validated_params,
- **extra_args,
- )
-
- # Convert validated params to dict
- param_dict = validated_params.model_dump()
-
- # Remove browser_session from params if it exists to avoid passing it twice
- for key in ['browser_session', 'browser', 'browser_context']:
- if key in param_dict and key in extra_args:
- del param_dict[key]
-
- return await action.function(
- **{
- **param_dict,
- **extra_args,
- }
- )
+ # For pydantic functions: function(pydantic_model, **special_params)
+ # Extract special parameters needed by this function (keep objects, don't serialize)
+ needed_special_params = set(parameter_names[1:]) & set(SpecialActionParameters.model_fields.keys())
+ injection_params = {}
+ for param_name in needed_special_params:
+ value = getattr(special_params, param_name, None)
+ if value is not None:
+ injection_params[param_name] = value
+
+ return await action.function(validated_params, **injection_params)
+ else:
+ # For individual parameter functions: function(**all_params)
+ # Merge user params with needed special params, avoiding conflicts
+ param_dict = validated_params.model_dump()
+
+ # Extract special parameters needed by this function (keep objects, don't serialize)
+ needed_special_params = set(parameter_names) & set(SpecialActionParameters.model_fields.keys())
+ injection_params = {}
+ for param_name in needed_special_params:
+ value = getattr(special_params, param_name, None)
+ if value is not None:
+ injection_params[param_name] = value
+
+ # Remove any special params from user params to avoid conflicts (special params take precedence)
+ for param_name in injection_params:
+ if param_name in param_dict:
+ logger.debug(f'Removing {param_name} from param_dict to avoid conflict')
+ param_dict.pop(param_name)
+
+ # Combine all parameters
+ final_params = {**param_dict, **injection_params}
+ return await action.function(**final_params)
except Exception as e:
raise RuntimeError(f'Error executing action {action_name}: {str(e)}') from e
diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.py
index 8f41cb948..cd13f1cf4 100644
--- a/browser_use/controller/registry/views.py
+++ b/browser_use/controller/registry/views.py
@@ -76,7 +76,7 @@ class ActionRegistry(BaseModel):
Match a list of domain glob patterns against a URL.
Args:
- domain_patterns: A list of domain patterns that can include glob patterns (* wildcard)
+ domains: A list of domain patterns that can include glob patterns (* wildcard)
url: The URL to match against
Returns:
@@ -86,26 +86,13 @@ class ActionRegistry(BaseModel):
if domains is None or not url:
return True
- import fnmatch
- from urllib.parse import urlparse
-
- # Parse the URL to get the domain
- try:
- parsed_url = urlparse(url)
- if not parsed_url.netloc:
- return False
-
- domain = parsed_url.netloc
- # Remove port if present
- if ':' in domain:
- domain = domain.split(':')[0]
-
- for domain_pattern in domains:
- if fnmatch.fnmatch(domain, domain_pattern): # Perform glob *.matching.*
- return True
- return False
- except Exception:
- return False
+ # Use the centralized URL matching logic from utils
+ from browser_use.utils import match_url_with_domain_pattern
+
+ for domain_pattern in domains:
+ if match_url_with_domain_pattern(url, domain_pattern):
+ return True
+ return False
@staticmethod
def _match_page_filter(page_filter: Callable[[Page], bool] | None, page: Page) -> bool:
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 626e77205..1e24a4298 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -108,7 +108,7 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=msg, include_in_memory=True)
@self.registry.action('Go back', param_model=NoParamsAction)
- async def go_back(_: NoParamsAction, browser_session: BrowserSession):
+ async def go_back(params: NoParamsAction, browser_session: BrowserSession):
await browser_session.go_back()
msg = '๐Ÿ”™ Navigated back'
logger.info(msg)
@@ -368,7 +368,7 @@ class Controller(Generic[Context]):
if await locator.count() == 0:
continue
- element = await locator.first
+ element = locator.first
is_visible = await element.is_visible()
bbox = await element.bounding_box()
@@ -772,7 +772,7 @@ class Controller(Generic[Context]):
logger.error(error_msg)
return ActionResult(error=error_msg, include_in_memory=True)
- @self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['sheets.google.com'])
+ @self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['docs.google.com'])
async def get_sheet_contents(browser_session: BrowserSession):
page = await browser_session.get_current_page()
@@ -785,8 +785,8 @@ class Controller(Generic[Context]):
extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')
return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)
- # preserve undecorated function as util so other functions can use it by passing browser_session in manually
- async def _select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
+ @self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['docs.google.com'])
+ async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
page = await browser_session.get_current_page()
await page.keyboard.press('Enter') # make sure we dont delete current cell contents if we were last editing
@@ -804,33 +804,25 @@ class Controller(Generic[Context]):
await page.keyboard.press('Escape') # to make sure the popup still closes in the case where the jump failed
return ActionResult(extracted_content=f'Selected cell {cell_or_range}', include_in_memory=False)
- @self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['sheets.google.com'])
- async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
- # Pass browser_session positionally to avoid the "multiple values" error
- # This prevents the error when Registry.execute_action also includes browser_session in extra_args
- return await _select_cell_or_range(browser_session, cell_or_range)
-
- @self.registry.action(
- 'Google Sheets: Get the contents of a specific cell or range of cells', domains=['sheets.google.com']
- )
+ @self.registry.action('Google Sheets: Get the contents of a specific cell or range of cells', domains=['docs.google.com'])
async def get_range_contents(browser_session: BrowserSession, cell_or_range: str):
page = await browser_session.get_current_page()
- await _select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)
+ await select_cell_or_range(browser_session, cell_or_range)
await page.keyboard.press('ControlOrMeta+C')
await asyncio.sleep(0.1)
extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')
return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)
- @self.registry.action('Google Sheets: Clear the currently selected cells', domains=['sheets.google.com'])
+ @self.registry.action('Google Sheets: Clear the currently selected cells', domains=['docs.google.com'])
async def clear_selected_range(browser_session: BrowserSession):
page = await browser_session.get_current_page()
await page.keyboard.press('Backspace')
return ActionResult(extracted_content='Cleared selected range', include_in_memory=False)
- @self.registry.action('Google Sheets: Input text into the currently selected cell', domains=['sheets.google.com'])
+ @self.registry.action('Google Sheets: Input text into the currently selected cell', domains=['docs.google.com'])
async def input_selected_cell_text(browser_session: BrowserSession, text: str):
page = await browser_session.get_current_page()
@@ -839,7 +831,7 @@ class Controller(Generic[Context]):
await page.keyboard.press('ArrowUp')
return ActionResult(extracted_content=f'Inputted text {text}', include_in_memory=False)
- @self.registry.action('Google Sheets: Batch update a range of cells', domains=['sheets.google.com'])
+ @self.registry.action('Google Sheets: Batch update a range of cells', domains=['docs.google.com'])
async def update_range_contents(browser_session: BrowserSession, range: str, new_contents_tsv: str):
page = await browser_session.get_current_page()
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
index 93c4fcafd..fe8d18f58 100644
--- a/browser_use/dom/buildDomTree.js
+++ b/browser_use/dom/buildDomTree.js
@@ -824,30 +824,12 @@
if (hasInteractiveRole) return true;
- // check whether element has event listeners
- try {
- if (typeof getEventListeners === 'function') {
- const listeners = getEventListeners(element);
- const mouseEvents = ['click', 'mousedown', 'mouseup', 'dblclick'];
- for (const eventType of mouseEvents) {
- for (const listener of listeners) {
- if (listener.type === eventType) {
- return true; // Found a mouse interaction listener
- }
- }
- }
- } else {
- // Fallback: Check common event attributes if getEventListeners is not available
- const commonMouseAttrs = ['onclick', 'onmousedown', 'onmouseup', 'ondblclick'];
- for (const attr of commonMouseAttrs) {
- if (element.hasAttribute(attr) || typeof element[attr] === 'function') {
- return true;
- }
- }
+ // Check common event attributes (getEventListeners doesn't work in page.evaluate context)
+ const commonMouseAttrs = ['onclick', 'onmousedown', 'onmouseup', 'ondblclick'];
+ for (const attr of commonMouseAttrs) {
+ if (element.hasAttribute(attr) || typeof element[attr] === 'function') {
+ return true;
}
- } catch (e) {
- // console.warn(`Could not check event listeners for ${element.tagName}:`, e);
- // If checking listeners fails, rely on other checks
}
return false
@@ -1116,29 +1098,11 @@
if (element.hasAttribute('onclick') || typeof element.onclick === 'function') {
return true;
}
- // Check for other common interaction event listeners
- try {
- const getEventListeners = window.getEventListenersForNode;
- if (typeof getEventListeners === 'function') {
- const listeners = getEventListeners(element);
- const interactionEvents = ['click', 'mousedown', 'mouseup', 'keydown', 'keyup', 'submit', 'change', 'input', 'focus', 'blur'];
- for (const eventType of interactionEvents) {
- for (const listener of listeners) {
- if (listener.type === eventType) {
- return true; // Found a common interaction listener
- }
- }
- }
- } else {
- // Fallback: Check common event attributes if getEventListeners is not available
- const commonEventAttrs = ['onmousedown', 'onmouseup', 'onkeydown', 'onkeyup', 'onsubmit', 'onchange', 'oninput', 'onfocus', 'onblur'];
- if (commonEventAttrs.some(attr => element.hasAttribute(attr))) {
- return true;
- }
- }
- } catch (e) {
- // console.warn(`Could not check event listeners for ${element.tagName}:`, e);
- // If checking listeners fails, rely on other checks
+
+ // Check common event attributes (getEventListenersForNode doesn't work in page.evaluate context)
+ const commonEventAttrs = ['onmousedown', 'onmouseup', 'onkeydown', 'onkeyup', 'onsubmit', 'onchange', 'oninput', 'onfocus', 'onblur'];
+ if (commonEventAttrs.some(attr => element.hasAttribute(attr))) {
+ return true;
}
// if the element is not strictly interactive but appears clickable based on heuristic signals
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index e75bc62b3..3114e5c36 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -1,4 +1,3 @@
-import json
import logging
from dataclasses import dataclass
from importlib import resources
@@ -105,10 +104,27 @@ class DomService:
# Only log performance metrics in debug mode
if debug_mode and 'perfMetrics' in eval_page:
+ perf = eval_page['perfMetrics']
+
+ # Get key metrics for summary
+ total_nodes = perf.get('nodeMetrics', {}).get('totalNodes', 0)
+ processed_nodes = perf.get('nodeMetrics', {}).get('processedNodes', 0)
+
+ # Count interactive elements from the DOM map
+ interactive_count = 0
+ if 'map' in eval_page:
+ for node_data in eval_page['map'].values():
+ if isinstance(node_data, dict) and node_data.get('isInteractive'):
+ interactive_count += 1
+
+ # Create concise summary
+ url_short = self.page.url[:50] + '...' if len(self.page.url) > 50 else self.page.url
logger.debug(
- 'DOM Tree Building Performance Metrics for: %s\n%s',
- self.page.url,
- json.dumps(eval_page['perfMetrics'], indent=2),
+ 'ran buildDOMTree.js on: %s total_nodes=%d processed=%d interactive=%d',
+ url_short,
+ total_nodes,
+ processed_nodes,
+ interactive_count,
)
return await self._construct_dom_tree(eval_page)
diff --git a/browser_use/logging_config.py b/browser_use/logging_config.py
index 1109cf7e4..4b62d6141 100644
--- a/browser_use/logging_config.py
+++ b/browser_use/logging_config.py
@@ -119,6 +119,8 @@ def setup_logging():
'urllib3',
'asyncio',
'langchain',
+ 'langsmith',
+ 'langsmith.client',
'openai',
'httpcore',
'charset_normalizer',
diff --git a/browser_use/utils.py b/browser_use/utils.py
index ea595bf9d..c456b16b5 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -306,7 +306,9 @@ def time_execution_sync(additional_text: str = '') -> Callable[[Callable[P, R]],
start_time = time.time()
result = func(*args, **kwargs)
execution_time = time.time() - start_time
- logger.debug(f'{additional_text} Execution time: {execution_time:.2f} seconds')
+ # Only log if execution takes more than 0.25 seconds
+ if execution_time > 0.25:
+ logger.debug(f'{additional_text} Execution time: {execution_time:.2f} seconds')
return result
return wrapper
@@ -323,7 +325,9 @@ def time_execution_async(
start_time = time.time()
result = await func(*args, **kwargs)
execution_time = time.time() - start_time
- logger.debug(f'{additional_text} Execution time: {execution_time:.2f} seconds')
+ # Only log if execution takes more than 0.25 seconds
+ if execution_time > 0.25:
+ logger.debug(f'{additional_text} Execution time: {execution_time:.2f} seconds')
return result
return wrapper
diff --git a/debug_pydantic.py b/debug_pydantic.py
new file mode 100644
index 000000000..5be286300
--- /dev/null
+++ b/debug_pydantic.py
@@ -0,0 +1,34 @@
+import inspect
+
+from pydantic import BaseModel
+
+from browser_use.controller.views import ClickElementAction
+
+
+# Check the pydantic detection logic
+def click_element_by_index(params: ClickElementAction, browser_session):
+ pass
+
+
+sig = inspect.signature(click_element_by_index)
+parameters = list(sig.parameters.values())
+parameter_names = [param.name for param in parameters]
+
+print('Parameters:', parameter_names)
+print('First param name:', parameters[0].name)
+print('First param annotation:', parameters[0].annotation)
+print('Is BaseModel:', issubclass(parameters[0].annotation, BaseModel))
+
+# Check the name detection logic
+name_check = parameters[0].name in ['params', 'param', 'model'] or parameters[0].name.endswith('_model')
+print('Name check passed:', name_check)
+
+is_pydantic = (
+ parameters
+ and len(parameters) > 0
+ and hasattr(parameters[0], 'annotation')
+ and parameters[0].annotation != parameters[0].empty
+ and issubclass(parameters[0].annotation, BaseModel)
+ and name_check
+)
+print('Is pydantic:', is_pydantic)
diff --git a/examples/use-cases/google_sheets.py b/examples/use-cases/google_sheets.py
index 2aea882b7..a110a5050 100644
--- a/examples/use-cases/google_sheets.py
+++ b/examples/use-cases/google_sheets.py
@@ -4,11 +4,10 @@ import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import asyncio
-import pyperclip
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
-from browser_use import ActionResult, Agent, Controller
+from browser_use import Agent, Controller
from browser_use.browser import BrowserProfile, BrowserSession
# Load environment variables
@@ -16,106 +15,17 @@ load_dotenv()
if not os.getenv('OPENAI_API_KEY'):
raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')
-
+# Use the default controller with built-in Google Sheets actions
+# The controller already includes all the necessary Google Sheets actions:
+# - select_cell_or_range: Select specific cells or ranges (Ctrl+G navigation)
+# - get_range_contents: Get contents of cells using clipboard
+# - get_sheet_contents: Get entire sheet contents
+# - clear_selected_range: Clear selected cells
+# - input_selected_cell_text: Input text into selected cells
+# - update_range_contents: Batch update ranges with TSV data
controller = Controller()
-
-def is_google_sheet(page) -> bool:
- return page.url.startswith('https://docs.google.com/spreadsheets/')
-
-
[email protected]('Google Sheets: Open a specific Google Sheet')
-async def open_google_sheet(browser_session: BrowserSession, google_sheet_url: str):
- page = await browser_session.get_current_page()
- if page.url != google_sheet_url:
- await page.goto(google_sheet_url)
- await page.wait_for_load_state()
- if not is_google_sheet(page):
- return ActionResult(error='Failed to open Google Sheet, are you sure you have permissions to access this sheet?')
- return ActionResult(extracted_content=f'Opened Google Sheet {google_sheet_url}', include_in_memory=False)
-
-
[email protected]('Google Sheets: Get the contents of the entire sheet', page_filter=is_google_sheet)
-async def get_sheet_contents(browser_session: BrowserSession):
- page = await browser_session.get_current_page()
-
- # select all cells
- await page.keyboard.press('Enter')
- await page.keyboard.press('Escape')
- await page.keyboard.press('ControlOrMeta+A')
- await page.keyboard.press('ControlOrMeta+C')
-
- extracted_tsv = pyperclip.paste()
- return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)
-
-
[email protected]('Google Sheets: Select a specific cell or range of cells', page_filter=is_google_sheet)
-async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
- page = await browser_session.get_current_page()
-
- await page.keyboard.press('Enter') # make sure we dont delete current cell contents if we were last editing
- await page.keyboard.press('Escape') # to clear current focus (otherwise select range popup is additive)
- await asyncio.sleep(0.1)
- await page.keyboard.press('Home') # move cursor to the top left of the sheet first
- await page.keyboard.press('ArrowUp')
- await asyncio.sleep(0.1)
- await page.keyboard.press('Control+G') # open the goto range popup
- await asyncio.sleep(0.2)
- await page.keyboard.type(cell_or_range, delay=0.05)
- await asyncio.sleep(0.2)
- await page.keyboard.press('Enter')
- await asyncio.sleep(0.2)
- await page.keyboard.press('Escape') # to make sure the popup still closes in the case where the jump failed
- return ActionResult(extracted_content=f'Selected cell {cell_or_range}', include_in_memory=False)
-
-
[email protected]('Google Sheets: Get the contents of a specific cell or range of cells', page_filter=is_google_sheet)
-async def get_range_contents(browser_session: BrowserSession, cell_or_range: str):
- page = await browser_session.get_current_page()
-
- await select_cell_or_range(cell_or_range=cell_or_range)
-
- await page.keyboard.press('ControlOrMeta+C')
- await asyncio.sleep(0.1)
- extracted_tsv = pyperclip.paste()
- return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)
-
-
[email protected]('Google Sheets: Clear the currently selected cells', page_filter=is_google_sheet)
-async def clear_selected_range(browser_session: BrowserSession):
- page = await browser_session.get_current_page()
-
- await page.keyboard.press('Backspace')
- return ActionResult(extracted_content='Cleared selected range', include_in_memory=False)
-
-
[email protected]('Google Sheets: Input text into the currently selected cell', page_filter=is_google_sheet)
-async def input_selected_cell_text(browser_session: BrowserSession, text: str):
- page = await browser_session.get_current_page()
-
- await page.keyboard.type(text, delay=0.1)
- await page.keyboard.press('Enter') # make sure to commit the input so it doesn't get overwritten by the next action
- await page.keyboard.press('ArrowUp')
- return ActionResult(extracted_content=f'Inputted text {text}', include_in_memory=False)
-
-
[email protected]('Google Sheets: Batch update a range of cells', page_filter=is_google_sheet)
-async def update_range_contents(browser_session: BrowserSession, range: str, new_contents_tsv: str):
- page = await browser_session.get_current_page()
-
- await select_cell_or_range(cell_or_range=range)
-
- # simulate paste event from clipboard with TSV content
- await page.evaluate(f"""
- const clipboardData = new DataTransfer();
- clipboardData.setData('text/plain', `{new_contents_tsv}`);
- document.activeElement.dispatchEvent(new ClipboardEvent('paste', {{clipboardData}}));
- """)
-
- return ActionResult(extracted_content=f'Updated cell {range} with {new_contents_tsv}', include_in_memory=False)
-
-
-# many more snippets for keyboard-shortcut based Google Sheets automation can be found here, see:
+# For more Google Sheets keyboard shortcuts and automation ideas, see:
# - https://github.com/philc/sheetkeys/blob/master/content_scripts/sheet_actions.js
# - https://github.com/philc/sheetkeys/blob/master/content_scripts/commands.js
# - https://support.google.com/docs/answer/181110?hl=en&co=GENIE.Platform%3DDesktop#zippy=%2Cmac-shortcuts
@@ -129,7 +39,8 @@ async def main():
browser_profile=BrowserProfile(
executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
user_data_dir='~/.config/browseruse/profiles/default',
- )
+ ),
+ keep_alive=True,
)
async with browser_session:
diff --git a/tests/ci/test_action_registry.py b/tests/ci/test_action_registry.py
new file mode 100644
index 000000000..537db48c5
--- /dev/null
+++ b/tests/ci/test_action_registry.py
@@ -0,0 +1,625 @@
+"""
+Comprehensive tests for the action registry system to ensure backward compatibility
+and proper parameter handling for all existing patterns.
+
+Tests cover:
+1. Existing parameter patterns (individual params, pydantic models)
+2. Special parameter injection (browser_session, page_extraction_llm, etc.)
+3. Action-to-action calling scenarios
+4. Mixed parameter patterns
+5. Registry execution edge cases
+"""
+
+import asyncio
+import logging
+
+import pytest
+from playwright.async_api import Page
+from pydantic import Field
+from pytest_httpserver import HTTPServer
+
+from browser_use.agent.views import ActionResult
+from browser_use.browser import BrowserSession
+from browser_use.controller.registry.service import Registry
+from browser_use.controller.registry.views import ActionModel as BaseActionModel
+from browser_use.controller.views import (
+ ClickElementAction,
+ InputTextAction,
+ NoParamsAction,
+ SearchGoogleAction,
+)
+
+# Configure logging
+logging.basicConfig(level=logging.DEBUG)
+logger = logging.getLogger(__name__)
+
+
+class MockLLM:
+ """Mock LLM for testing"""
+
+ async def ainvoke(self, prompt):
+ class MockResponse:
+ content = 'Mocked LLM response'
+
+ return MockResponse()
+
+
+class TestContext:
+ """Simple context for testing"""
+
+ pass
+
+
+# Test parameter models
+class SimpleParams(BaseActionModel):
+ """Simple parameter model"""
+
+ value: str = Field(description='Test value')
+
+
+class ComplexParams(BaseActionModel):
+ """Complex parameter model with multiple fields"""
+
+ text: str = Field(description='Text input')
+ number: int = Field(description='Number input', default=42)
+ optional_flag: bool = Field(description='Optional boolean', default=False)
+
+
+# Test fixtures
[email protected](scope='module')
+def event_loop():
+ """Create and provide an event loop for async tests."""
+ loop = asyncio.get_event_loop_policy().new_event_loop()
+ yield loop
+ loop.close()
+
+
[email protected](scope='module')
+def http_server():
+ """Create and provide a test HTTP server that serves static content."""
+ server = HTTPServer()
+ server.start()
+
+ # Add a simple test page
+ server.expect_request('/test').respond_with_data(
+ '<html><head><title>Test Page</title></head><body><h1>Test Page</h1><p>Hello from test page</p></body></html>',
+ content_type='text/html',
+ )
+
+ yield server
+ server.stop()
+
+
+def base_url(http_server):
+ """Return the base URL for the test HTTP server."""
+ return f'http://{http_server.host}:{http_server.port}'
+
+
[email protected](scope='module')
+async def browser_session(event_loop):
+ """Create and provide a real BrowserSession instance."""
+ browser_session = BrowserSession(
+ headless=True,
+ user_data_dir=None,
+ )
+ await browser_session.start()
+ yield browser_session
+ await browser_session.stop()
+
+
+def mock_llm():
+ """Create a mock LLM"""
+ return MockLLM()
+
+
+def registry():
+ """Create a fresh registry for each test"""
+ return Registry[TestContext]()
+
+
+async def test_browser(base_url):
+ """Create a real BrowserSession for testing"""
+ browser_session = BrowserSession(
+ headless=True,
+ user_data_dir=None,
+ )
+ await browser_session.start()
+ # Navigate to test page
+ await browser_session.create_new_tab(f'{base_url}/test')
+ yield browser_session
+ await browser_session.stop()
+
+
+class TestActionRegistryParameterPatterns:
+ """Test different parameter patterns that should all continue to work"""
+
+ @pytest.mark.asyncio
+ async def test_individual_parameters_no_browser(self, registry):
+ """Test action with individual parameters, no special injection"""
+
+ @registry.action('Simple action with individual params')
+ async def simple_action(text: str, number: int = 10):
+ return ActionResult(extracted_content=f'Text: {text}, Number: {number}')
+
+ # Test execution
+ result = await registry.execute_action('simple_action', {'text': 'hello', 'number': 42})
+
+ assert isinstance(result, ActionResult)
+ assert 'Text: hello, Number: 42' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_individual_parameters_with_browser(self, registry, browser_session, base_url):
+ """Test action with individual parameters plus browser_session injection"""
+
+ @registry.action('Action with individual params and browser')
+ async def action_with_browser(text: str, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
+ return ActionResult(extracted_content=f'Text: {text}, URL: {page.url}')
+
+ # Navigate to test page first
+ await browser_session.create_new_tab(f'{base_url}/test')
+
+ # Test execution
+ result = await registry.execute_action('action_with_browser', {'text': 'hello'}, browser_session=browser_session)
+
+ assert isinstance(result, ActionResult)
+ assert 'Text: hello, URL:' in result.extracted_content
+ assert base_url in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_page_parameter_injection(self, registry, browser_session, base_url):
+ """Test action with direct Page parameter injection"""
+
+ @registry.action('Action with page parameter')
+ async def action_with_page(text: str, page: Page):
+ title = await page.title()
+ return ActionResult(extracted_content=f'Text: {text}, Page Title: {title}')
+
+ # Navigate to test page first
+ await browser_session.create_new_tab(f'{base_url}/test')
+
+ # Test execution
+ result = await registry.execute_action('action_with_page', {'text': 'hello'}, browser_session=browser_session)
+
+ assert isinstance(result, ActionResult)
+ assert 'Text: hello, Page Title: Test Page' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_pydantic_model_with_page_parameter(self, registry, browser_session, base_url):
+ """Test pydantic model action with page parameter injection"""
+
+ @registry.action('Pydantic action with page', param_model=ComplexParams)
+ async def pydantic_action_with_page(params: ComplexParams, page: Page):
+ title = await page.title()
+ return ActionResult(extracted_content=f'Text: {params.text}, Number: {params.number}, Page Title: {title}')
+
+ # Navigate to test page first
+ await browser_session.create_new_tab(f'{base_url}/test')
+
+ # Test execution
+ result = await registry.execute_action(
+ 'pydantic_action_with_page', {'text': 'test', 'number': 100}, browser_session=browser_session
+ )
+
+ assert isinstance(result, ActionResult)
+ assert 'Text: test, Number: 100, Page Title: Test Page' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_pydantic_model_parameters(self, registry, browser_session, base_url):
+ """Test action that takes a pydantic model as first parameter"""
+
+ @registry.action('Action with pydantic model', param_model=ComplexParams)
+ async def pydantic_action(params: ComplexParams, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
+ return ActionResult(
+ extracted_content=f'Text: {params.text}, Number: {params.number}, Flag: {params.optional_flag}, URL: {page.url}'
+ )
+
+ # Navigate to test page first
+ await browser_session.create_new_tab(f'{base_url}/test')
+
+ # Test execution
+ result = await registry.execute_action(
+ 'pydantic_action', {'text': 'test', 'number': 100, 'optional_flag': True}, browser_session=browser_session
+ )
+
+ assert isinstance(result, ActionResult)
+ assert 'Text: test, Number: 100, Flag: True' in result.extracted_content
+ assert base_url in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_mixed_special_parameters(self, registry, browser_session, base_url, mock_llm):
+ """Test action with multiple special injected parameters"""
+
+ @registry.action('Action with multiple special params')
+ async def multi_special_action(
+ text: str,
+ browser_session: BrowserSession,
+ page_extraction_llm: MockLLM,
+ available_file_paths: list[str] | None = None,
+ ):
+ page = await browser_session.get_current_page()
+ llm_response = await page_extraction_llm.ainvoke('test')
+ files = available_file_paths or []
+
+ return ActionResult(
+ extracted_content=f'Text: {text}, URL: {page.url}, LLM: {llm_response.content}, Files: {len(files)}'
+ )
+
+ # Navigate to test page first
+ await browser_session.create_new_tab(f'{base_url}/test')
+
+ # Test execution
+ result = await registry.execute_action(
+ 'multi_special_action',
+ {'text': 'hello'},
+ browser_session=browser_session,
+ page_extraction_llm=mock_llm,
+ available_file_paths=['file1.txt', 'file2.txt'],
+ )
+
+ assert isinstance(result, ActionResult)
+ assert 'Text: hello' in result.extracted_content
+ assert base_url in result.extracted_content
+ assert 'LLM: Mocked LLM response' in result.extracted_content
+ assert 'Files: 2' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_no_params_action(self, registry, test_browser):
+ """Test action with NoParamsAction model"""
+
+ @registry.action('No params action', param_model=NoParamsAction)
+ async def no_params_action(params: NoParamsAction, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
+ return ActionResult(extracted_content=f'No params action executed on {page.url}')
+
+ # Test execution with any parameters (should be ignored)
+ result = await registry.execute_action(
+ 'no_params_action', {'random': 'data', 'should': 'be', 'ignored': True}, browser_session=test_browser
+ )
+
+ assert isinstance(result, ActionResult)
+ assert 'No params action executed on' in result.extracted_content
+ assert '/test' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_legacy_browser_parameter_names(self, registry, test_browser):
+ """Test that legacy browser parameter names still work"""
+
+ @registry.action('Action with legacy browser param')
+ async def legacy_browser_action(text: str, browser: BrowserSession):
+ page = await browser.get_current_page()
+ return ActionResult(extracted_content=f'Legacy browser: {text}, URL: {page.url}')
+
+ @registry.action('Action with legacy browser_context param')
+ async def legacy_context_action(text: str, browser_context: BrowserSession):
+ page = await browser_context.get_current_page()
+ return ActionResult(extracted_content=f'Legacy context: {text}, URL: {page.url}')
+
+ # Test legacy browser parameter
+ result1 = await registry.execute_action('legacy_browser_action', {'text': 'test1'}, browser_session=test_browser)
+ assert 'Legacy browser: test1, URL:' in result1.extracted_content
+ assert '/test' in result1.extracted_content
+
+ # Test legacy browser_context parameter
+ result2 = await registry.execute_action('legacy_context_action', {'text': 'test2'}, browser_session=test_browser)
+ assert 'Legacy context: test2, URL:' in result2.extracted_content
+ assert '/test' in result2.extracted_content
+
+
+class TestActionToActionCalling:
+ """Test scenarios where actions call other actions"""
+
+ @pytest.mark.asyncio
+ async def test_action_calling_action_with_kwargs(self, registry, test_browser):
+ """Test action calling another action using kwargs (current problematic pattern)"""
+
+ # Helper function that actions can call
+ async def helper_function(browser_session: BrowserSession, data: str):
+ page = await browser_session.get_current_page()
+ return f'Helper processed: {data} on {page.url}'
+
+ @registry.action('First action')
+ async def first_action(text: str, browser_session: BrowserSession):
+ # This should work without parameter conflicts
+ result = await helper_function(browser_session=browser_session, data=text)
+ return ActionResult(extracted_content=f'First: {result}')
+
+ @registry.action('Calling action')
+ async def calling_action(message: str, browser_session: BrowserSession):
+ # Call the first action through the registry (simulates action-to-action calling)
+ intermediate_result = await registry.execute_action(
+ 'first_action', {'text': message}, browser_session=browser_session
+ )
+ return ActionResult(extracted_content=f'Called result: {intermediate_result.extracted_content}')
+
+ # Test the calling chain
+ result = await registry.execute_action('calling_action', {'message': 'test'}, browser_session=test_browser)
+
+ assert isinstance(result, ActionResult)
+ assert 'Called result: First: Helper processed: test on' in result.extracted_content
+ assert '/test' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_google_sheets_style_calling_pattern(self, registry, test_browser):
+ """Test the specific pattern from Google Sheets actions that causes the error"""
+
+ # Simulate the _select_cell_or_range helper function
+ async def _select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
+ page = await browser_session.get_current_page()
+ return ActionResult(extracted_content=f'Selected cell {cell_or_range} on {page.url}')
+
+ @registry.action('Select cell or range')
+ async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
+ # This is the PROBLEMATIC pattern that currently fails
+ # Passing browser_session by name causes "multiple values for argument" error
+ return await _select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)
+
+ @registry.action('Select cell or range (fixed)')
+ async def select_cell_or_range_fixed(browser_session: BrowserSession, cell_or_range: str):
+ # This is the WORKING pattern using positional args
+ return await _select_cell_or_range(browser_session, cell_or_range)
+
+ @registry.action('Update range contents')
+ async def update_range_contents(browser_session: BrowserSession, range_name: str, new_contents: str):
+ # This action calls select_cell_or_range, simulating the real Google Sheets pattern
+ await select_cell_or_range_fixed(browser_session, range_name) # Should use positional args
+ return ActionResult(extracted_content=f'Updated range {range_name} with {new_contents}')
+
+ # Test the fixed version (should work)
+ result_fixed = await registry.execute_action(
+ 'select_cell_or_range_fixed', {'cell_or_range': 'A1:F100'}, browser_session=test_browser
+ )
+ assert 'Selected cell A1:F100 on' in result_fixed.extracted_content
+ assert '/test' in result_fixed.extracted_content
+
+ # Test the chained calling pattern
+ result_chain = await registry.execute_action(
+ 'update_range_contents', {'range_name': 'B2:D4', 'new_contents': 'test data'}, browser_session=test_browser
+ )
+ assert 'Updated range B2:D4 with test data' in result_chain.extracted_content
+
+ # Test the problematic version (may fail with current registry, should work with enhanced registry)
+ try:
+ result_problematic = await registry.execute_action(
+ 'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=test_browser
+ )
+ # If this succeeds, great! The enhanced registry is working
+ assert 'Selected cell A1:F100 on' in result_problematic.extracted_content
+ assert '/test' in result_problematic.extracted_content
+ except TypeError as e:
+ # This is the expected error with the current registry
+ assert 'multiple values for argument' in str(e) or 'got multiple values' in str(e)
+ logger.info(f'Expected error with current registry: {e}')
+
+ @pytest.mark.asyncio
+ async def test_complex_action_chain(self, registry, test_browser):
+ """Test a complex chain of actions calling other actions"""
+
+ @registry.action('Base action')
+ async def base_action(value: str, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
+ return ActionResult(extracted_content=f'Base: {value} on {page.url}')
+
+ @registry.action('Middle action')
+ async def middle_action(input_val: str, browser_session: BrowserSession):
+ # Call base action
+ base_result = await registry.execute_action(
+ 'base_action', {'value': f'processed-{input_val}'}, browser_session=browser_session
+ )
+ return ActionResult(extracted_content=f'Middle: {base_result.extracted_content}')
+
+ @registry.action('Top action')
+ async def top_action(original: str, browser_session: BrowserSession):
+ # Call middle action
+ middle_result = await registry.execute_action(
+ 'middle_action', {'input_val': f'enhanced-{original}'}, browser_session=browser_session
+ )
+ return ActionResult(extracted_content=f'Top: {middle_result.extracted_content}')
+
+ # Test the full chain
+ result = await registry.execute_action('top_action', {'original': 'test'}, browser_session=test_browser)
+
+ assert isinstance(result, ActionResult)
+ assert 'Top: Middle: Base: processed-enhanced-test on' in result.extracted_content
+ assert '/test' in result.extracted_content
+
+
+class TestRegistryEdgeCases:
+ """Test edge cases and error conditions"""
+
+ @pytest.mark.asyncio
+ async def test_missing_required_browser_session(self, registry):
+ """Test that actions requiring browser_session fail appropriately when not provided"""
+
+ @registry.action('Requires browser')
+ async def requires_browser(text: str, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
+ return ActionResult(extracted_content=f'Text: {text}, URL: {page.url}')
+
+ # Should raise RuntimeError when browser_session is required but not provided
+ with pytest.raises(RuntimeError, match='requires browser_session but none provided'):
+ await registry.execute_action(
+ 'requires_browser',
+ {'text': 'test'},
+ # No browser_session provided
+ )
+
+ @pytest.mark.asyncio
+ async def test_missing_required_llm(self, registry, test_browser):
+ """Test that actions requiring page_extraction_llm fail appropriately when not provided"""
+
+ @registry.action('Requires LLM')
+ async def requires_llm(text: str, browser_session: BrowserSession, page_extraction_llm: MockLLM):
+ page = await browser_session.get_current_page()
+ llm_response = await page_extraction_llm.ainvoke('test')
+ return ActionResult(extracted_content=f'Text: {text}, LLM: {llm_response.content}')
+
+ # Should raise RuntimeError when page_extraction_llm is required but not provided
+ with pytest.raises(RuntimeError, match='requires page_extraction_llm but none provided'):
+ await registry.execute_action(
+ 'requires_llm',
+ {'text': 'test'},
+ browser_session=test_browser,
+ # No page_extraction_llm provided
+ )
+
+ @pytest.mark.asyncio
+ async def test_invalid_parameters(self, registry, test_browser):
+ """Test handling of invalid parameters"""
+
+ @registry.action('Typed action')
+ async def typed_action(number: int, browser_session: BrowserSession):
+ return ActionResult(extracted_content=f'Number: {number}')
+
+ # Should raise RuntimeError when parameter validation fails
+ with pytest.raises(RuntimeError, match='Invalid parameters'):
+ await registry.execute_action(
+ 'typed_action',
+ {'number': 'not a number'}, # Invalid type
+ browser_session=test_browser,
+ )
+
+ @pytest.mark.asyncio
+ async def test_nonexistent_action(self, registry, test_browser):
+ """Test calling a non-existent action"""
+
+ with pytest.raises(ValueError, match='Action nonexistent_action not found'):
+ await registry.execute_action('nonexistent_action', {'param': 'value'}, browser_session=test_browser)
+
+ @pytest.mark.asyncio
+ async def test_sync_action_wrapper(self, registry, test_browser):
+ """Test that sync functions are properly wrapped to be async"""
+
+ @registry.action('Sync action')
+ def sync_action(text: str, browser_session: BrowserSession):
+ # This is a sync function that should be wrapped
+ return ActionResult(extracted_content=f'Sync: {text}')
+
+ # Should work even though the original function is sync
+ result = await registry.execute_action('sync_action', {'text': 'test'}, browser_session=test_browser)
+
+ assert isinstance(result, ActionResult)
+ assert 'Sync: test' in result.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_excluded_actions(self, test_browser):
+ """Test that excluded actions are not registered"""
+
+ registry_with_exclusions = Registry[TestContext](exclude_actions=['excluded_action'])
+
+ @registry_with_exclusions.action('Excluded action')
+ async def excluded_action(text: str):
+ return ActionResult(extracted_content=f'Should not execute: {text}')
+
+ @registry_with_exclusions.action('Included action')
+ async def included_action(text: str):
+ return ActionResult(extracted_content=f'Should execute: {text}')
+
+ # Excluded action should not be in registry
+ assert 'excluded_action' not in registry_with_exclusions.registry.actions
+ assert 'included_action' in registry_with_exclusions.registry.actions
+
+ # Should raise error when trying to execute excluded action
+ with pytest.raises(ValueError, match='Action excluded_action not found'):
+ await registry_with_exclusions.execute_action('excluded_action', {'text': 'test'})
+
+ # Included action should work
+ result = await registry_with_exclusions.execute_action('included_action', {'text': 'test'})
+ assert 'Should execute: test' in result.extracted_content
+
+
+class TestExistingControllerActions:
+ """Test that existing controller actions continue to work"""
+
+ @pytest.mark.asyncio
+ async def test_existing_action_models(self, registry, test_browser):
+ """Test that existing action parameter models work correctly"""
+
+ @registry.action('Test search', param_model=SearchGoogleAction)
+ async def test_search(params: SearchGoogleAction, browser_session: BrowserSession):
+ return ActionResult(extracted_content=f'Searched for: {params.query}')
+
+ @registry.action('Test click', param_model=ClickElementAction)
+ async def test_click(params: ClickElementAction, browser_session: BrowserSession):
+ return ActionResult(extracted_content=f'Clicked element: {params.index}')
+
+ @registry.action('Test input', param_model=InputTextAction)
+ async def test_input(params: InputTextAction, browser_session: BrowserSession):
+ return ActionResult(extracted_content=f'Input text: {params.text} at index: {params.index}')
+
+ # Test SearchGoogleAction
+ result1 = await registry.execute_action('test_search', {'query': 'python testing'}, browser_session=test_browser)
+ assert 'Searched for: python testing' in result1.extracted_content
+
+ # Test ClickElementAction
+ result2 = await registry.execute_action('test_click', {'index': 42}, browser_session=test_browser)
+ assert 'Clicked element: 42' in result2.extracted_content
+
+ # Test InputTextAction
+ result3 = await registry.execute_action('test_input', {'index': 5, 'text': 'test input'}, browser_session=test_browser)
+ assert 'Input text: test input at index: 5' in result3.extracted_content
+
+ @pytest.mark.asyncio
+ async def test_pydantic_vs_individual_params_consistency(self, registry, test_browser):
+ """Test that pydantic and individual parameter patterns produce consistent results"""
+
+ # Action using individual parameters
+ @registry.action('Individual params')
+ async def individual_params_action(text: str, number: int, browser_session: BrowserSession):
+ return ActionResult(extracted_content=f'Individual: {text}-{number}')
+
+ # Action using pydantic model
+ class TestParams(BaseActionModel):
+ text: str
+ number: int
+
+ @registry.action('Pydantic params', param_model=TestParams)
+ async def pydantic_params_action(params: TestParams, browser_session: BrowserSession):
+ return ActionResult(extracted_content=f'Pydantic: {params.text}-{params.number}')
+
+ # Both should produce similar results
+ test_data = {'text': 'hello', 'number': 42}
+
+ result1 = await registry.execute_action('individual_params_action', test_data, browser_session=test_browser)
+
+ result2 = await registry.execute_action('pydantic_params_action', test_data, browser_session=test_browser)
+
+ # Both should extract the same content (just different prefixes)
+ assert 'hello-42' in result1.extracted_content
+ assert 'hello-42' in result2.extracted_content
+ assert 'Individual:' in result1.extracted_content
+ assert 'Pydantic:' in result2.extracted_content
+
+
+# Test runner for manual execution
+if __name__ == '__main__':
+ # Run a simple test manually
+ import asyncio
+
+ async def manual_test():
+ """Manual test runner for debugging"""
+ print('Running manual test...')
+
+ registry = Registry[TestContext]()
+ browser_session = BrowserSession(headless=True)
+ await browser_session.start()
+ await browser_session.create_new_tab('https://example.com')
+
+ @registry.action('Manual test action')
+ async def manual_action(text: str, browser_session: BrowserSession):
+ page = await browser_session.get_current_page()
+ return ActionResult(extracted_content=f'Manual: {text} on {page.url}')
+
+ result = await registry.execute_action('manual_action', {'text': 'test'}, browser_session=browser_session)
+
+ print(f'Result: {result.extracted_content}')
+ await browser_session.stop()
+ print('Manual test passed!')
+
+ if __name__ == '__main__':
+ asyncio.run(manual_test())
diff --git a/tests/ci/test_browser_session_param.py b/tests/ci/test_browser_session_param.py
index 6171e73d3..e88ad5d2f 100644
--- a/tests/ci/test_browser_session_param.py
+++ b/tests/ci/test_browser_session_param.py
@@ -30,16 +30,22 @@ logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
-# Mock BrowserSession for testing
-class MockBrowserSession:
- """Mock browser session for testing"""
+# Use real browser session for testing
+import pytest
+
+from browser_use.browser import BrowserSession
- async def get_current_page(self):
- return None
- async def create_new_tab(self, url=None):
- logger.info(f'Creating new tab with URL: {url}')
- return None
+async def browser_session():
+ """Create and provide a real BrowserSession instance."""
+ browser_session = BrowserSession(
+ headless=True,
+ user_data_dir=None,
+ )
+ await browser_session.start()
+ yield browser_session
+ await browser_session.stop()
# Model that doesn't include browser_session (renamed to avoid pytest collecting it)
@@ -50,7 +56,7 @@ class CellActionParams(ActionModel):
# Model that includes browser_session
class ModelWithBrowser(ActionModel):
value: str = Field(description='Test value')
- browser_session: MockBrowserSession = None
+ browser_session: BrowserSession = None
# Simple context for testing
@@ -58,7 +64,7 @@ class TestContext:
pass
-async def main():
+async def main(browser_session):
"""Run the test to diagnose browser_session parameter issue
This test demonstrates the problem and our fix. The issue happens because:
@@ -102,8 +108,7 @@ async def main():
class CellRangeParams(ActionModel):
cell_or_range: str = Field(description='Cell or range to select')
- # Create mock browser session
- mock_browser = MockBrowserSession()
+ # Use the provided real browser session
# Test with the real issue: select_cell_or_range
logger.info('\n\n=== Test: Simulating select_cell_or_range issue with correct model ===')
@@ -117,7 +122,7 @@ async def main():
# This simulates the actual issue we're seeing in the real code
# The browser_session parameter is in both the function signature and passed as a named arg
@registry.action('Google Sheets: Select a cell or range', param_model=CellRangeParams)
- async def select_cell_or_range(browser_session: MockBrowserSession, cell_or_range: str):
+ async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
logger.info(f'select_cell_or_range called with browser_session={browser_session}, cell_or_range={cell_or_range}')
# PROBLEMATIC LINE: browser_session is passed by name, matching the parameter name
@@ -126,7 +131,7 @@ async def main():
# Fix attempt: Register a version that uses positional args instead
@registry.action('Google Sheets: Select a cell or range (fixed)', param_model=CellRangeParams)
- async def select_cell_or_range_fixed(browser_session: MockBrowserSession, cell_or_range: str):
+ async def select_cell_or_range_fixed(browser_session: BrowserSession, cell_or_range: str):
logger.info(f'select_cell_or_range_fixed called with browser_session={browser_session}, cell_or_range={cell_or_range}')
# FIXED LINE: browser_session is passed positionally, avoiding the parameter name conflict
@@ -134,7 +139,7 @@ async def main():
# Another attempt: explicitly call using **kwargs to simulate what the registry does
@registry.action('Google Sheets: Select with kwargs', param_model=CellRangeParams)
- async def select_with_kwargs(browser_session: MockBrowserSession, cell_or_range: str):
+ async def select_with_kwargs(browser_session: BrowserSession, cell_or_range: str):
logger.info(f'select_with_kwargs called with browser_session={browser_session}, cell_or_range={cell_or_range}')
# Get params and extra_args, like in Registry.execute_action
@@ -164,7 +169,7 @@ async def main():
logger.info('\n--- Testing original problematic version ---')
try:
result1 = await registry.execute_action(
- 'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=mock_browser
+ 'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
)
logger.info(f'Success! Result: {result1}')
except Exception as e:
@@ -174,7 +179,7 @@ async def main():
logger.info('\n--- Testing fixed version (positional args) ---')
try:
result2 = await registry.execute_action(
- 'select_cell_or_range_fixed', {'cell_or_range': 'A1:F100'}, browser_session=mock_browser
+ 'select_cell_or_range_fixed', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
)
logger.info(f'Success! Result: {result2}')
except Exception as e:
@@ -183,7 +188,9 @@ async def main():
# Test with kwargs version that simulates what Registry.execute_action does
logger.info('\n--- Testing kwargs simulation version ---')
try:
- result3 = await registry.execute_action('select_with_kwargs', {'cell_or_range': 'A1:F100'}, browser_session=mock_browser)
+ result3 = await registry.execute_action(
+ 'select_with_kwargs', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
+ )
logger.info(f'Success! Result: {result3}')
except Exception as e:
logger.error(f'Error: {str(e)}')
@@ -196,7 +203,7 @@ async def main():
# First check if the extra_args approach works
logger.info('Checking if extra_args approach works:')
- extra_args = {'browser_session': mock_browser}
+ extra_args = {'browser_session': browser_session}
# If we were to modify Registry.execute_action:
# 1. Check if the function parameter needs browser_session
@@ -231,12 +238,20 @@ import pytest
@pytest.mark.asyncio
-async def test_browser_session_parameter_issue():
+async def test_browser_session_parameter_issue(browser_session):
"""Test that the browser_session parameter issue is fixed."""
# Run the main test logic
- await main()
+ await main(browser_session)
if __name__ == '__main__':
# For direct execution (not through pytest)
- asyncio.run(main())
+ async def run_with_real_browser():
+ browser_session = BrowserSession(headless=True, user_data_dir=None)
+ await browser_session.start()
+ try:
+ await main(browser_session)
+ finally:
+ await browser_session.stop()
+
+ asyncio.run(run_with_real_browser())
diff --git a/tests/ci/test_debug_selector_map.py b/tests/ci/test_debug_selector_map.py
new file mode 100644
index 000000000..55dcbc072
--- /dev/null
+++ b/tests/ci/test_debug_selector_map.py
@@ -0,0 +1,436 @@
+"""
+Systematic debugging of the selector map issue.
+Test each assumption step by step to isolate the problem.
+"""
+
+import os
+
+import pytest
+
+from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.controller.service import Controller
+
+
+async def browser_session():
+ """Create a real browser session for testing."""
+ session = BrowserSession(
+ browser_profile=BrowserProfile(
+ executable_path=os.getenv('BROWSER_PATH'),
+ user_data_dir=None, # Use temporary profile
+ headless=True,
+ )
+ )
+ async with session:
+ yield session
+
+
+def controller():
+ """Create a controller instance."""
+ return Controller()
+
+
+async def test_assumption_1_dom_processing_works(browser_session):
+ """Test assumption 1: DOM processing works and finds elements."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ # Trigger DOM processing
+ state = await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+
+ print('DOM processing result:')
+ print(f' - Elements found: {len(state.selector_map)}')
+ print(f' - Element indices: {list(state.selector_map.keys())}')
+
+ # Verify DOM processing works
+ assert len(state.selector_map) > 0, 'DOM processing should find elements'
+ assert 0 in state.selector_map, 'Element index 0 should exist'
+
+
+async def test_assumption_2_cached_selector_map_persists(browser_session):
+ """Test assumption 2: Cached selector map persists after get_state_summary."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ # Trigger DOM processing and cache
+ state = await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ initial_selector_map = dict(state.selector_map)
+
+ # Check if cached selector map is still available
+ cached_selector_map = await browser_session.get_selector_map()
+
+ print('Selector map persistence:')
+ print(f' - Initial elements: {len(initial_selector_map)}')
+ print(f' - Cached elements: {len(cached_selector_map)}')
+ print(f' - Maps are identical: {initial_selector_map.keys() == cached_selector_map.keys()}')
+
+ # Verify the cached map persists
+ assert len(cached_selector_map) > 0, 'Cached selector map should persist'
+ assert initial_selector_map.keys() == cached_selector_map.keys(), 'Cached map should match initial map'
+
+
+async def test_assumption_3_action_gets_same_selector_map(browser_session, controller):
+ """Test assumption 3: Action gets the same selector map as cached."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ # Trigger DOM processing and cache
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ cached_selector_map = await browser_session.get_selector_map()
+
+ print('Pre-action state:')
+ print(f' - Cached elements: {len(cached_selector_map)}')
+ print(f' - Element 0 exists in cache: {0 in cached_selector_map}')
+
+ # Create a test action that checks the selector map it receives
+ @controller.registry.action('Test: Check selector map')
+ async def test_check_selector_map(browser_session: BrowserSession):
+ from browser_use import ActionResult
+
+ action_selector_map = await browser_session.get_selector_map()
+ return ActionResult(
+ extracted_content=f'Action sees {len(action_selector_map)} elements, index 0 exists: {0 in action_selector_map}',
+ include_in_memory=False,
+ )
+
+ # Execute the test action
+ result = await controller.registry.execute_action('test_check_selector_map', {}, browser_session=browser_session)
+
+ print(f'Action result: {result.extracted_content}')
+
+ # Verify the action sees the same selector map
+ assert 'index 0 exists: True' in result.extracted_content, 'Action should see element 0'
+
+
+async def test_assumption_4_click_action_specific_issue(browser_session, controller):
+ """Test assumption 4: Specific issue with click_element_by_index action."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ # Trigger DOM processing and cache
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ cached_selector_map = await browser_session.get_selector_map()
+
+ print('Pre-click state:')
+ print(f' - Cached elements: {len(cached_selector_map)}')
+ print(f' - Element 0 exists: {0 in cached_selector_map}')
+
+ # Create a test action that replicates click_element_by_index logic
+ @controller.registry.action('Test: Debug click logic')
+ async def test_debug_click_logic(browser_session: BrowserSession, index: int):
+ from browser_use import ActionResult
+
+ # This is the exact logic from click_element_by_index
+ selector_map = await browser_session.get_selector_map()
+
+ print(f' - Action selector map size: {len(selector_map)}')
+ print(f' - Action selector map keys: {list(selector_map.keys())[:10]}') # First 10
+ print(f' - Index {index} in selector map: {index in selector_map}')
+
+ if index not in selector_map:
+ return ActionResult(
+ error=f'Debug: Element with index {index} does not exist in map of size {len(selector_map)}',
+ include_in_memory=False,
+ )
+
+ return ActionResult(
+ extracted_content=f'Debug: Element {index} found in map of size {len(selector_map)}', include_in_memory=False
+ )
+
+ # Test with index 0
+ result = await controller.registry.execute_action('test_debug_click_logic', {'index': 0}, browser_session=browser_session)
+
+ print(f'Debug click result: {result.extracted_content or result.error}')
+
+ # This will help us see exactly what the click action sees
+ if result.error:
+ pytest.fail(f'Click logic debug failed: {result.error}')
+
+
+async def test_assumption_5_multiple_get_selector_map_calls(browser_session):
+ """Test assumption 5: Multiple calls to get_selector_map return consistent results."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ # Trigger DOM processing and cache
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+
+ # Call get_selector_map multiple times
+ map1 = await browser_session.get_selector_map()
+ map2 = await browser_session.get_selector_map()
+ map3 = await browser_session.get_selector_map()
+
+ print('Multiple selector map calls:')
+ print(f' - Call 1: {len(map1)} elements')
+ print(f' - Call 2: {len(map2)} elements')
+ print(f' - Call 3: {len(map3)} elements')
+ print(f' - All calls identical: {map1.keys() == map2.keys() == map3.keys()}')
+
+ # Verify consistency
+ assert len(map1) == len(map2) == len(map3), 'Multiple calls should return same size'
+ assert map1.keys() == map2.keys() == map3.keys(), 'Multiple calls should return same elements'
+
+
+async def test_assumption_6_page_changes_affect_selector_map(browser_session):
+ """Test assumption 6: Check if page navigation affects cached selector map."""
+ # Go to first page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ # Get initial selector map
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ initial_map = await browser_session.get_selector_map()
+
+ print('Page change test:')
+ print(f' - Google.com elements: {len(initial_map)}')
+
+ # Navigate to a different page (without calling get_state_summary)
+ await page.goto('https://www.example.com')
+ await page.wait_for_load_state()
+
+ # Check if cached selector map is still from old page
+ cached_map_after_nav = await browser_session.get_selector_map()
+
+ print(f' - After navigation (cached): {len(cached_map_after_nav)}')
+ print(f' - Cache unchanged after nav: {len(initial_map) == len(cached_map_after_nav)}')
+
+ # Update with new page
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ new_page_map = await browser_session.get_selector_map()
+
+ print(f' - Example.com elements (fresh): {len(new_page_map)}')
+
+ # This will tell us if cached maps get stale
+ assert len(new_page_map) != len(initial_map) or initial_map.keys() != new_page_map.keys(), (
+ 'Different pages should have different selector maps'
+ )
+
+
+async def test_assumption_8_same_browser_session_instance(browser_session, controller):
+ """Test assumption 8: Action gets the same browser_session instance."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ print('=== BROWSER SESSION INSTANCE DEBUG ===')
+
+ # Get fresh state
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+
+ # Store the ID of our browser session instance
+ original_session_id = id(browser_session)
+ print(f'1. Original browser_session ID: {original_session_id}')
+ print(f'2. Original cache exists: {browser_session._cached_browser_state_summary is not None}')
+
+ # Create action that checks browser session identity
+ @controller.registry.action('Test: Check browser session identity')
+ async def test_check_session_identity(browser_session: BrowserSession):
+ from browser_use import ActionResult
+
+ action_session_id = id(browser_session)
+ cache_exists = browser_session._cached_browser_state_summary is not None
+ return ActionResult(
+ extracted_content=f'Action session ID: {action_session_id}, Cache exists: {cache_exists}', include_in_memory=False
+ )
+
+ # Execute action
+ result = await controller.registry.execute_action('test_check_session_identity', {}, browser_session=browser_session)
+
+ print(f'3. Action result: {result.extracted_content}')
+
+ # Parse the result to check if session IDs match
+ action_session_id = int(result.extracted_content.split('Action session ID: ')[1].split(',')[0])
+
+ if original_session_id == action_session_id:
+ print('โœ… Same browser_session instance passed to action')
+ else:
+ print('โŒ DIFFERENT browser_session instance passed to action!')
+ print(f' Original: {original_session_id}')
+ print(f' Action: {action_session_id}')
+
+
+async def test_assumption_9_pydantic_private_attrs(browser_session, controller):
+ """Test assumption 9: Pydantic model validation affects private attributes."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ print('=== PYDANTIC PRIVATE ATTRS DEBUG ===')
+
+ # Get fresh state
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+
+ print(f'1. Original browser_session cache: {browser_session._cached_browser_state_summary is not None}')
+ print(f'2. Original browser_session ID: {id(browser_session)}')
+
+ # Import the SpecialActionParameters to test directly
+ from browser_use.controller.registry.service import SpecialActionParameters
+
+ # Test what happens when we put browser_session through model_validate
+ special_params_data = {
+ 'context': None,
+ 'browser_session': browser_session,
+ 'browser': browser_session,
+ 'browser_context': browser_session,
+ 'page_extraction_llm': None,
+ 'available_file_paths': None,
+ 'has_sensitive_data': False,
+ }
+
+ print(f'3. Before model_validate - browser_session cache: {browser_session._cached_browser_state_summary is not None}')
+
+ # Test the fixed version using model_construct instead of model_validate
+ special_params = SpecialActionParameters.model_construct(**special_params_data)
+
+ print(
+ f'4. After model_validate - original browser_session cache: {browser_session._cached_browser_state_summary is not None}'
+ )
+
+ # Check the browser_session that comes out of the model
+ extracted_browser_session = special_params.browser_session
+ print(f'5. Extracted browser_session ID: {id(extracted_browser_session)}')
+ print(f'6. Extracted browser_session cache: {extracted_browser_session._cached_browser_state_summary is not None}')
+
+ # Check if they're the same object
+ if id(browser_session) == id(extracted_browser_session):
+ print('โœ… Same object - no copying occurred')
+ else:
+ print('โŒ DIFFERENT object - Pydantic copied the browser_session!')
+
+ # Check if private attributes were preserved
+ print(f'7. Original has _cached_browser_state_summary attr: {hasattr(browser_session, "_cached_browser_state_summary")}')
+ print(
+ f'8. Extracted has _cached_browser_state_summary attr: {hasattr(extracted_browser_session, "_cached_browser_state_summary")}'
+ )
+
+ if hasattr(extracted_browser_session, '_cached_browser_state_summary'):
+ print(f'9. Extracted _cached_browser_state_summary value: {extracted_browser_session._cached_browser_state_summary}')
+
+
+async def test_assumption_7_cache_gets_cleared(browser_session, controller):
+ """Test assumption 7: Check if _cached_browser_state_summary gets cleared."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ print('=== CACHE CLEARING DEBUG ===')
+
+ # Check initial cache state
+ print(f'1. Initial cache state: {browser_session._cached_browser_state_summary}')
+
+ # Get fresh state
+ state = await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ print(f'2. After get_state_summary: cache exists = {browser_session._cached_browser_state_summary is not None}')
+ print(f'3. Cache has {len(state.selector_map)} elements')
+
+ # Check cache before action
+ print(f'4. Pre-action cache: {browser_session._cached_browser_state_summary is not None}')
+
+ # Create action that checks cache state (NO page parameter)
+ @controller.registry.action('Test: Check cache state no page')
+ async def test_check_cache_state_no_page(browser_session: BrowserSession):
+ from browser_use import ActionResult
+
+ cache_exists = browser_session._cached_browser_state_summary is not None
+ if cache_exists:
+ cache_size = len(browser_session._cached_browser_state_summary.selector_map)
+ else:
+ cache_size = 0
+ return ActionResult(
+ extracted_content=f'NoPage - Cache exists: {cache_exists}, Cache size: {cache_size}', include_in_memory=False
+ )
+
+ # Create action that checks cache state (WITH page parameter)
+ @controller.registry.action('Test: Check cache state with page')
+ async def test_check_cache_state_with_page(browser_session: BrowserSession, page):
+ from browser_use import ActionResult
+
+ cache_exists = browser_session._cached_browser_state_summary is not None
+ if cache_exists:
+ cache_size = len(browser_session._cached_browser_state_summary.selector_map)
+ else:
+ cache_size = 0
+ return ActionResult(
+ extracted_content=f'WithPage - Cache exists: {cache_exists}, Cache size: {cache_size}', include_in_memory=False
+ )
+
+ # Test action WITHOUT page parameter
+ result_no_page = await controller.registry.execute_action(
+ 'test_check_cache_state_no_page', {}, browser_session=browser_session
+ )
+
+ print(f'5a. Action result (NO page): {result_no_page.extracted_content}')
+
+ # Test action WITH page parameter
+ result_with_page = await controller.registry.execute_action(
+ 'test_check_cache_state_with_page', {}, browser_session=browser_session
+ )
+
+ print(f'5b. Action result (WITH page): {result_with_page.extracted_content}')
+ print(f'6. Post-action cache: {browser_session._cached_browser_state_summary is not None}')
+
+ # This will tell us if the page parameter injection clears the cache
+
+
+async def test_final_real_click_with_debug(browser_session, controller):
+ """Final test: Try actual click with maximum debugging."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ print('=== FINAL CLICK TEST WITH FULL DEBUG ===')
+
+ # Get fresh state
+ state = await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ print(f'1. Fresh state has {len(state.selector_map)} elements')
+
+ # Check cached map
+ cached_map = await browser_session.get_selector_map()
+ print(f'2. Cached map has {len(cached_map)} elements')
+ print(f'3. Element 0 in cached map: {0 in cached_map}')
+
+ # Try the real click action
+ if 0 in cached_map:
+ print('4. Attempting real click_element_by_index...')
+ try:
+ result = await controller.registry.execute_action(
+ 'click_element_by_index', {'index': 0}, browser_session=browser_session
+ )
+ print(f'5. Click SUCCESS: {result.extracted_content}')
+ except Exception as e:
+ print(f'5. Click FAILED: {e}')
+
+ # Additional debug: check selector map inside the exception
+ debug_map = await browser_session.get_selector_map()
+ print(f'6. Post-failure selector map: {len(debug_map)} elements')
+ print(f'7. Element 0 still in map: {0 in debug_map}')
+
+ raise e
+ else:
+ pytest.fail('Element 0 not found in cached map - test setup issue')
diff --git a/tests/ci/test_google_sheets_real.py b/tests/ci/test_google_sheets_real.py
new file mode 100644
index 000000000..878dd1ca6
--- /dev/null
+++ b/tests/ci/test_google_sheets_real.py
@@ -0,0 +1,130 @@
+"""
+Real integration tests for Google Sheets actions against the actual Google Sheets website.
+Tests the enhanced action registry system with Google Sheets keyboard automation.
+Uses the existing Google Sheets actions from the main controller.
+"""
+
+import os
+
+import pytest
+
+from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.controller.service import Controller
+
+# Test Google Sheets URL (public read-only spreadsheet for testing)
+TEST_GOOGLE_SHEET_URL = 'https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit'
+
+
+async def browser_session():
+ """Create a real browser session for testing."""
+ session = BrowserSession(
+ browser_profile=BrowserProfile(
+ executable_path=os.getenv('BROWSER_PATH'),
+ user_data_dir=None, # Use temporary profile
+ headless=True,
+ )
+ )
+ async with session:
+ yield session
+
+
+def controller():
+ """Create a controller instance (Google Sheets actions are already registered)."""
+ return Controller()
+
+
+async def test_selector_map_basic(browser_session, controller):
+ """Test that the selector map gets populated on a basic page."""
+ # Go to a simple page first
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ # Update browser state to populate selector map
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+
+ # Check selector map
+ selector_map = await browser_session.get_selector_map()
+ print(f'Selector map size: {len(selector_map)}')
+
+ # Should have some elements
+ assert len(selector_map) > 0, 'No clickable elements found in selector map'
+
+
+async def test_click_element_basic(browser_session, controller):
+ """Test basic click element action to verify registry works."""
+ # Go to a simple page
+ page = await browser_session.get_current_page()
+ await page.goto('https://www.google.com')
+ await page.wait_for_load_state()
+
+ # Update browser state to populate selector map
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+
+ # Check selector map
+ selector_map = await browser_session.get_selector_map()
+ print(f'Available elements: {list(selector_map.keys())}')
+
+ if len(selector_map) > 0:
+ # Try to click the first available element
+ first_index = list(selector_map.keys())[0]
+ print(f'Trying to click element index: {first_index}')
+
+ result = await controller.registry.execute_action(
+ 'click_element_by_index', {'index': first_index}, browser_session=browser_session
+ )
+
+ # Should not have an error about element not existing
+ print(f'Click result: {result.extracted_content if result.extracted_content else "No content"}')
+ print(f'Click error: {result.error if result.error else "No error"}')
+
+ # The click might fail for other reasons (like navigation) but shouldn't fail due to "element does not exist"
+ if result.error:
+ assert 'Element with index' not in result.error, f'Element indexing failed: {result.error}'
+ else:
+ pytest.fail('No clickable elements found - DOM processing issue')
+
+
+async def test_google_sheets_open(browser_session, controller):
+ """Test opening a Google Sheet using the existing action."""
+ # First check what actions are available
+ available_actions = list(controller.registry.registry.actions.keys())
+ print(f'Available actions: {[a for a in available_actions if "Google" in a]}')
+
+ # Try to find the right action name
+ google_sheet_actions = [a for a in available_actions if 'google sheet' in a.lower()]
+
+ if not google_sheet_actions:
+ pytest.skip('No Google Sheets actions found in controller')
+
+ # Use the first Google Sheets action we find
+ open_action = google_sheet_actions[0]
+ print(f'Using action: {open_action}')
+
+ result = await controller.registry.execute_action(
+ open_action, {'google_sheet_url': TEST_GOOGLE_SHEET_URL}, browser_session=browser_session
+ )
+
+ print(f'Open result: {result.extracted_content if result.extracted_content else "No content"}')
+ print(f'Open error: {result.error if result.error else "No error"}')
+
+ # Verify we're on the Google Sheets page
+ page = await browser_session.get_current_page()
+ assert 'docs.google.com/spreadsheets' in page.url
+
+
+async def test_list_all_actions(browser_session, controller):
+ """Debug test to list all available actions."""
+ available_actions = list(controller.registry.registry.actions.keys())
+ print('All available actions:')
+ for action in sorted(available_actions):
+ print(f' - {action}')
+
+ # Just verify the controller has some actions
+ assert len(available_actions) > 0
diff --git a/tests/test_action_params.py b/tests/test_action_params.py
new file mode 100644
index 000000000..c0594c264
--- /dev/null
+++ b/tests/test_action_params.py
@@ -0,0 +1,91 @@
+import asyncio
+import logging
+from inspect import signature
+
+import pytest
+from pydantic import BaseModel, Field
+
+from browser_use.browser import BrowserSession
+from browser_use.controller.registry.service import Registry
+from browser_use.controller.registry.views import ActionModel
+
+# Configure logging
+logging.basicConfig(level=logging.DEBUG)
+logger = logging.getLogger(__name__)
+
+
+# Test model
+class TestActionParams(ActionModel):
+ value: str = Field(description='Test value')
+
+
+# Our Context type for the Registry
+class TestContext:
+ def __init__(self, value):
+ self.value = value
+
+
+async def test_registry_param_handling():
+ """Test how Registry handles parameter passing for different function signatures."""
+ # Create a Registry instance
+ registry = Registry[TestContext]()
+
+ # Create test functions with different signatures
+
+ # 1. Function with browser_session as a positional parameter
+ @registry.action('Test action with browser_session', param_model=TestActionParams)
+ async def action_with_browser_session(params: TestActionParams, browser_session: BrowserSession):
+ logger.debug(f'action_with_browser_session called with params={params}, browser_session={browser_session}')
+ return {'params': params.model_dump(), 'has_browser': browser_session is not None}
+
+ # 2. Function with browser_session in the model
+ class ModelWithBrowserSession(BaseModel):
+ value: str
+ browser_session: BrowserSession = None
+
+ @registry.action('Test action with browser_session in model')
+ async def action_with_browser_in_model(params: ModelWithBrowserSession):
+ logger.debug(f'action_with_browser_in_model called with params={params}')
+ return {'params': params.model_dump(), 'has_browser': params.browser_session is not None}
+
+ # 3. Function using **kwargs
+ @registry.action('Test action with kwargs')
+ async def action_with_kwargs(params: TestActionParams, **kwargs):
+ logger.debug(f'action_with_kwargs called with params={params}, kwargs={kwargs}')
+ return {'params': params.model_dump(), 'kwargs': kwargs}
+
+ # Create a mock browser session
+ mock_browser_session = object() # Just a placeholder
+
+ # Execute the actions
+ logger.debug('\n\n=== Testing action_with_browser_session ===')
+ result1 = await registry.execute_action(
+ 'action_with_browser_session', {'value': 'test1'}, browser_session=mock_browser_session
+ )
+ logger.debug(f'Result: {result1}')
+
+ logger.debug('\n\n=== Testing action_with_browser_in_model ===')
+ result2 = await registry.execute_action(
+ 'action_with_browser_in_model',
+ {'value': 'test2', 'browser_session': None}, # Browser session in model is None
+ browser_session=mock_browser_session, # Browser session in execute_action is provided
+ )
+ logger.debug(f'Result: {result2}')
+
+ logger.debug('\n\n=== Testing action_with_kwargs ===')
+ result3 = await registry.execute_action('action_with_kwargs', {'value': 'test3'}, browser_session=mock_browser_session)
+ logger.debug(f'Result: {result3}')
+
+ # Print all signatures
+ logger.debug('\n\n=== Function Signatures ===')
+ logger.debug(f'action_with_browser_session: {signature(action_with_browser_session)}')
+ logger.debug(f'action_with_browser_in_model: {signature(action_with_browser_in_model)}')
+ logger.debug(f'action_with_kwargs: {signature(action_with_kwargs)}')
+
+ return result1, result2, result3
+
+
+if __name__ == '__main__':
+ # Run the test
+ asyncio.run(test_registry_param_handling())