Skip to content

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

Rename controller to tools instances

Magnus Müllercaa0e7ef1b8f
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 397499871..c2f784d05 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -93,7 +93,7 @@ jobs:
- run: uvx playwright install chromium
# TODO: just depend on the other test.yml action for this instead of re-running the tests here
- # - run: uv run pytest tests/ci/test_controller.py # final sanity check: run a few of the tests before release
+ # - run: uv run pytest tests/ci/test_tools.py # final sanity check: run a few of the tests before release
# publish to PyPI
- run: uv publish --trusted-publishing always
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index 1bddc275e..6621a5ad3 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
outputs:
TEST_FILENAMES: ${{ steps.lsgrep.outputs.TEST_FILENAMES }}
- # ["test_browser", "test_controller", "test_browser_session", "test_tab_management", ...]
+ # ["test_browser", "test_tools", "test_browser_session", "test_tab_management", ...]
steps:
- uses: actions/checkout@v4
- id: lsgrep
@@ -56,7 +56,7 @@ jobs:
test_filename: ${{ fromJson(needs.find_tests.outputs.TEST_FILENAMES || '["FAILED_TO_DISCOVER_TESTS"]') }}
# autodiscovers all the files in tests/ci/test_*.py
# - test_browser
- # - test_controller
+ # - test_tools
# - test_browser_session
# - test_tab_management
# ... and more
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 984c3b13f..751e95a53 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -242,7 +242,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
if tools is not None:
self.tools = tools
elif controller is not None:
- self.tools = controller
+ self.tools = tools
else:
self.tools = Tools(display_files_in_done_text=display_files_in_done_text)
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 6c7c9858e..19e1f74e4 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -188,7 +188,7 @@ class BrowserSession(BaseModel):
"""Event-driven browser session with backwards compatibility.
This class provides a 2-layer architecture:
- - High-level event handling for agents/controllers
+ - High-level event handling for agents/tools
- Direct CDP/Playwright calls for browser operations
Supports both event-driven and imperative calling styles.
diff --git a/browser_use/integrations/gmail/__init__.py b/browser_use/integrations/gmail/__init__.py
index 3b8bda183..e7402e28a 100644
--- a/browser_use/integrations/gmail/__init__.py
+++ b/browser_use/integrations/gmail/__init__.py
@@ -5,11 +5,11 @@ This integration enables agents to read email content and extract verification c
Usage:
from browser_use.integrations.gmail import GmailService, register_gmail_actions
# Option 1: Register Gmail actions with file-based authentication
- controller = Tools()
- register_gmail_actions(controller)
+ tools = Tools()
+ register_gmail_actions(tools)
# Option 2: Register Gmail actions with direct access token (recommended for production)
- controller = Tools()
- register_gmail_actions(controller, access_token="your_access_token_here")
+ tools = Tools()
+ register_gmail_actions(tools, access_token="your_access_token_here")
# Option 3: Use the service directly
gmail = GmailService(access_token="your_access_token_here")
await gmail.authenticate()
diff --git a/browser_use/integrations/gmail/actions.py b/browser_use/integrations/gmail/actions.py
index 601ecd154..999ccd9b7 100644
--- a/browser_use/integrations/gmail/actions.py
+++ b/browser_use/integrations/gmail/actions.py
@@ -26,13 +26,11 @@ class GetRecentEmailsParams(BaseModel):
max_results: int = Field(default=3, ge=1, le=50, description='Maximum number of emails to retrieve (1-50, default: 3)')
-def register_gmail_actions(
- controller: Tools, gmail_service: GmailService | None = None, access_token: str | None = None
-) -> Tools:
+def register_gmail_actions(tools: Tools, gmail_service: GmailService | None = None, access_token: str | None = None) -> Tools:
"""
- Register Gmail actions with the provided controller
+ Register Gmail actions with the provided tools
Args:
- controller: The browser-use controller to register actions with
+ tools: The browser-use tools to register actions with
gmail_service: Optional pre-configured Gmail service instance
access_token: Optional direct access token (alternative to file-based auth)
"""
@@ -46,7 +44,7 @@ def register_gmail_actions(
else:
_gmail_service = GmailService()
- @controller.registry.action(
+ @tools.registry.action(
description='Get recent emails from the mailbox with a keyword to retrieve verification codes, OTP, 2FA tokens, magic links, or any recent email content. Keep your query a single keyword.',
param_model=GetRecentEmailsParams,
)
@@ -114,4 +112,4 @@ def register_gmail_actions(
long_term_memory='Failed to get recent emails due to error',
)
- return controller
+ return tools
diff --git a/browser_use/mcp/__init__.py b/browser_use/mcp/__init__.py
index 3af3849b7..e849682e4 100644
--- a/browser_use/mcp/__init__.py
+++ b/browser_use/mcp/__init__.py
@@ -4,7 +4,7 @@ This module provides integration with MCP servers and clients for browser automa
"""
from browser_use.mcp.client import MCPClient
-from browser_use.mcp.controller import MCPToolWrapper
+from browser_use.mcp.tools import MCPToolWrapper
__all__ = ['MCPClient', 'MCPToolWrapper', 'BrowserUseServer'] # type: ignore
diff --git a/browser_use/mcp/client.py b/browser_use/mcp/client.py
index 3da6984a9..807bc1169 100644
--- a/browser_use/mcp/client.py
+++ b/browser_use/mcp/client.py
@@ -7,7 +7,7 @@ Example usage:
from browser_use import Tools
from browser_use.mcp.client import MCPClient
- controller = Tools()
+ tools = Tools()
# Connect to an MCP server
mcp_client = MCPClient(
@@ -17,7 +17,7 @@ Example usage:
)
# Register all MCP tools as browser-use actions
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
# Now use with Agent as normal - MCP tools are available as actions
"""
@@ -207,23 +207,23 @@ class MCPClient:
)
self._telemetry.flush()
- async def register_to_controller(
+ async def register_to_tools(
self,
- controller: Tools,
+ tools: Tools,
tool_filter: list[str] | None = None,
prefix: str | None = None,
) -> None:
- """Register MCP tools as actions in the browser-use controller.
+ """Register MCP tools as actions in the browser-use tools.
Args:
- controller: Browser-use controller to register actions to
+ tools: Browser-use tools to register actions to
tool_filter: Optional list of tool names to register (None = all tools)
prefix: Optional prefix to add to action names (e.g., "playwright_")
"""
if not self._connected:
await self.connect()
- registry = controller.registry
+ registry = tools.registry
for tool_name, tool in self._tools.items():
# Skip if not in filter
diff --git a/browser_use/mcp/controller.py b/browser_use/mcp/controller.py
index 6b792719c..11c06e8e0 100644
--- a/browser_use/mcp/controller.py
+++ b/browser_use/mcp/controller.py
@@ -249,12 +249,12 @@ async def register_mcp_tools(registry: Registry, mcp_command: str, mcp_args: lis
Example:
```python
from browser_use import Tools
- from browser_use.mcp.controller import register_mcp_tools
+ from browser_use.mcp.tools import register_mcp_tools
- controller = Tools()
+ tools = Tools()
# Register Playwright MCP tools
- mcp = await register_mcp_tools(controller.registry, 'npx', ['@playwright/mcp@latest', '--headless'])
+ mcp = await register_mcp_tools(tools.registry, 'npx', ['@playwright/mcp@latest', '--headless'])
# Now all MCP tools are available as browser-use actions
```
diff --git a/browser_use/mcp/server.py b/browser_use/mcp/server.py
index 0af805751..a736dceb0 100644
--- a/browser_use/mcp/server.py
+++ b/browser_use/mcp/server.py
@@ -186,7 +186,7 @@ class BrowserUseServer:
self.config = load_browser_use_config()
self.agent: Agent | None = None
self.browser_session: BrowserSession | None = None
- self.controller: Tools | None = None
+ self.tools: Tools | None = None
self.llm: ChatOpenAI | None = None
self.file_system: FileSystem | None = None
self._telemetry = ProductTelemetry()
@@ -487,8 +487,8 @@ class BrowserUseServer:
self.browser_session = BrowserSession(browser_profile=profile)
await self.browser_session.start()
- # Create controller for direct actions
- self.controller = Tools()
+ # Create tools for direct actions
+ self.tools = Tools()
# Initialize LLM from config
llm_config = get_default_llm(self.config)
@@ -710,13 +710,13 @@ class BrowserUseServer:
if not self.browser_session:
return 'Error: No browser session active'
- if not self.controller:
+ if not self.tools:
return 'Error: Tools not initialized'
state = await self.browser_session.get_browser_state_summary()
# Use the extract_structured_data action
- # Create a dynamic action model that matches the controller's expectations
+ # Create a dynamic action model that matches the tools's expectations
from pydantic import create_model
# Create action model dynamically
@@ -727,7 +727,7 @@ class BrowserUseServer:
)
action = ExtractAction()
- action_result = await self.controller.act(
+ action_result = await self.tools.act(
action=action,
browser_session=self.browser_session,
page_extraction_llm=self.llm,
@@ -772,7 +772,7 @@ class BrowserUseServer:
event = self.browser_session.event_bus.dispatch(BrowserStopEvent())
await event
self.browser_session = None
- self.controller = None
+ self.tools = None
return 'Browser closed'
return 'No browser session to close'
diff --git a/browser_use/tools/registry/service.py b/browser_use/tools/registry/service.py
index c14b82104..43333cc2d 100644
--- a/browser_use/tools/registry/service.py
+++ b/browser_use/tools/registry/service.py
@@ -121,7 +121,7 @@ class Registry(Generic[Context]):
param_type_name = getattr(param_type, '__name__', str(param_type))
raise ValueError(
f"Action '{func.__name__}' parameter '{param.name}: {param_type_name}' "
- f"conflicts with special argument injected by controller: '{param.name}: {expected_type_name}'"
+ f"conflicts with special argument injected by tools: '{param.name}: {expected_type_name}'"
)
special_params.append(param)
else:
diff --git a/docs/customize/agent/all-parameters.mdx b/docs/customize/agent/all-parameters.mdx
index 58b794e0d..7f0276cb0 100644
--- a/docs/customize/agent/all-parameters.mdx
+++ b/docs/customize/agent/all-parameters.mdx
@@ -8,7 +8,7 @@ mode: "wide"
## Available Parameters
### Core Settings
-- `controller`: Registry of [our tools](https://github.com/browser-use/browser-use/blob/main/browser_use/controller/service.py
+- `tools`: Registry of [our tools](https://github.com/browser-use/browser-use/blob/main/browser_use/tools/service.py
) the agent can call. [Example for custom tools](https://github.com/browser-use/browser-use/tree/main/examples/custom-functions)
- `browser`: Browser object where you can specify the browser settings.
- `output_model_schema`: Pydantic model class for structured output validation. [Example](https://github.com/browser-use/browser-use/blob/main/examples/features/custom_output.py)
@@ -48,3 +48,7 @@ mode: "wide"
### Advanced Options
- `calculate_cost` (default: `False`): Calculate and track API costs
- `display_files_in_done_text` (default: `True`): Show file information in completion messages
+
+### Backwards Compatibility
+- `controller`: Alias for `tools` for backwards compatibility.
+- `browser_session`: Alias for `browser` for backwards compatibility.
\ No newline at end of file
diff --git a/docs/customize/hooks.mdx b/docs/customize/hooks.mdx
index 0b9260f25..a56cf66b8 100644
--- a/docs/customize/hooks.mdx
+++ b/docs/customize/hooks.mdx
@@ -33,7 +33,7 @@ from browser_use import Agent, ChatOpenAI
async def my_step_hook(agent: Agent):
# inside a hook you can access all the state and methods under the Agent object:
# agent.settings, agent.state, agent.task
- # agent.controller, agent.llm, agent.browser_session
+ # agent.tools, agent.llm, agent.browser_session
# agent.pause(), agent.resume(), agent.add_new_task(...), etc.
# You also have direct access to the browser state
@@ -83,8 +83,8 @@ await agent.run(
When working with agent hooks, you have access to the entire `Agent` instance. Here are some useful data points you can access:
- `agent.task` lets you see what the main task is, `agent.add_new_task(...)` lets you queue up a new one
-- `agent.controller` give access to the `Tools()` object and `Registry()` containing the available actions
- - `agent.controller.registry.execute_action('click_element_by_index', {'index': 123}, browser_session=agent.browser_session)`
+- `agent.tools` give access to the `Tools()` object and `Registry()` containing the available actions
+ - `agent.tools.registry.execute_action('click_element_by_index', {'index': 123}, browser_session=agent.browser_session)`
- `agent.context` lets you access any user-provided context object passed in to `Agent(context=...)`
- `agent.sensitive_data` contains the sensitive data dict, which can be updated in-place to add/remove/modify items
- `agent.settings` contains all the configuration options passed to the `Agent(...)` at init time
diff --git a/docs/customize/mcp-client.mdx b/docs/customize/mcp-client.mdx
index 2710e3e96..e3299c79b 100644
--- a/docs/customize/mcp-client.mdx
+++ b/docs/customize/mcp-client.mdx
@@ -28,8 +28,8 @@ import os
from browser_use import Agent, Tools
from browser_use.mcp.client import MCPClient
-# Create controller
-controller = Tools()
+# Create tools
+tools = Tools()
# Connect to MCP server
mcp_client = MCPClient(
@@ -40,12 +40,12 @@ mcp_client = MCPClient(
# Connect and register
await mcp_client.connect()
-await mcp_client.register_to_controller(controller)
+await mcp_client.register_to_tools(tools)
# Agent can now use filesystem tools
agent = Agent(
task="Read the README.md file",
- controller=controller
+ tools=tools
)
await agent.run()
@@ -80,9 +80,9 @@ class MCPClient:
# Connect to server
await mcp_client.connect()
-# Register tools to controller
-await mcp_client.register_to_controller(
- controller,
+# Register tools to tools
+await mcp_client.register_to_tools(
+ tools,
tool_filter=['read_file', 'write_file'], # Optional
prefix='fs_' # Optional prefix
)
@@ -100,7 +100,7 @@ async with MCPClient(
args=["@modelcontextprotocol/server-github"],
env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")}
) as client:
- await client.register_to_controller(controller)
+ await client.register_to_tools(tools)
await agent.run()
# Automatically disconnected
```
@@ -147,7 +147,7 @@ fs_client = MCPClient(
args=["@modelcontextprotocol/server-filesystem", "."]
)
await fs_client.connect()
-await fs_client.register_to_controller(controller, prefix="fs_")
+await fs_client.register_to_tools(tools, prefix="fs_")
# GitHub server
gh_client = MCPClient(
@@ -157,12 +157,12 @@ gh_client = MCPClient(
env={"GITHUB_TOKEN": os.getenv("GITHUB_TOKEN")}
)
await gh_client.connect()
-await gh_client.register_to_controller(controller, prefix="gh_")
+await gh_client.register_to_tools(tools, prefix="gh_")
# Agent can use both
agent = Agent(
task="Read README.md and create a GitHub issue",
- controller=controller
+ tools=tools
)
await agent.run()
@@ -176,8 +176,8 @@ await gh_client.disconnect()
Register only specific tools:
```python
-await mcp_client.register_to_controller(
- controller,
+await mcp_client.register_to_tools(
+ tools,
tool_filter=['read_file', 'list_directory']
)
```
diff --git a/docs/customize/tools/add.mdx b/docs/customize/tools/add.mdx
index 0a038dfee..eb88ad127 100644
--- a/docs/customize/tools/add.mdx
+++ b/docs/customize/tools/add.mdx
@@ -17,21 +17,21 @@ Examples:
- send emails
- ...
-Simply add `@controller.action(...)` to your function.
+Simply add `@tools.action(...)` to your function.
```python
from browser_use import Tools, Agent
-controller = Tools()
+tools = Tools()
[email protected](description='Ask human for help with a question')
[email protected](description='Ask human for help with a question')
def ask_human(question: str) -> ActionResult:
answer = input(f'{question} > ')
return f'The human responded with: {answer}'
```
```python
-agent = Agent(task='...', llm=llm, controller=controller)
+agent = Agent(task='...', llm=llm, tools=tools)
```
- **`description`** *(required)* - What the tool does, the LLM uses this to decide when to call it.
@@ -62,7 +62,7 @@ class Cars(BaseModel):
name: str = Field(description='The name of the car, e.g. "Toyota Camry"')
price: int = Field(description='The price of the car as int in USD, e.g. 25000')
[email protected](description='Save cars to file')
[email protected](description='Save cars to file')
def save_cars(cars: list[Cars]) -> str:
with open('cars.json', 'w') as f:
json.dump(cars, f)
@@ -75,7 +75,7 @@ task = "find cars and save them to file"
Limit tools to specific domains:
```python
description='Fill out banking forms',
allowed_domains=['https://mybank.com']
)
diff --git a/docs/customize/tools/available.mdx b/docs/customize/tools/available.mdx
index 7c6a37150..2ac63876d 100644
--- a/docs/customize/tools/available.mdx
+++ b/docs/customize/tools/available.mdx
@@ -1,6 +1,6 @@
---
title: "Available Tools"
-description: "Here is the [source code](https://github.com/browser-use/browser-use/blob/main/browser_use/controller/service.py) for the default tools:"
+description: "Here is the [source code](https://github.com/browser-use/browser-use/blob/main/browser_use/tools/service.py) for the default tools:"
icon: "list"
mode: "wide"
---
diff --git a/docs/customize/tools/basics.mdx b/docs/customize/tools/basics.mdx
index e7edf7ac7..bb1f036b8 100644
--- a/docs/customize/tools/basics.mdx
+++ b/docs/customize/tools/basics.mdx
@@ -12,9 +12,9 @@ mode: "wide"
```python
from browser_use import Tools, ActionResult
-controller = Tools()
+tools = Tools()
[email protected]('Ask human for help with a question')
[email protected]('Ask human for help with a question')
def ask_human(question: str) -> ActionResult:
answer = input(f'{question} > ')
return f'The human responded with: {answer}'
@@ -22,7 +22,7 @@ def ask_human(question: str) -> ActionResult:
agent = Agent(
task='Ask human for help',
llm=llm,
- controller=controller,
+ tools=tools,
)
```
diff --git a/docs/customize/tools/remove.mdx b/docs/customize/tools/remove.mdx
index 98a59611a..b9845cc3b 100644
--- a/docs/customize/tools/remove.mdx
+++ b/docs/customize/tools/remove.mdx
@@ -1,6 +1,6 @@
---
title: "Remove Tools"
-description: "You can exclude default tools when creating a controller:"
+description: "You can exclude default tools when creating a tools:"
icon: "minus"
mode: "wide"
---
@@ -9,7 +9,7 @@ mode: "wide"
```python
from browser_use import Tools
-controller = Tools(exclude_actions=['search_google', 'wait'])
-agent = Agent(task='...', llm=llm, controller=controller)
+tools = Tools(exclude_actions=['search_google', 'wait'])
+agent = Agent(task='...', llm=llm, tools=tools)
```
diff --git a/docs/customize/tools/response.mdx b/docs/customize/tools/response.mdx
index a0185b83d..4fa546ac0 100644
--- a/docs/customize/tools/response.mdx
+++ b/docs/customize/tools/response.mdx
@@ -10,11 +10,11 @@ Tools return results using `ActionResult` or simple strings.
## Return Types
```python
def my_tool() -> str:
return "Task completed successfully"
[email protected]('Advanced tool')
[email protected]('Advanced tool')
def advanced_tool() -> ActionResult:
return ActionResult(
extracted_content="Main result",
@@ -69,7 +69,7 @@ return ActionResult(
Set `is_done=True` to stop the agent completely. Use when your tool finishes the entire task:
```python
[email protected](description='Complete the task')
[email protected](description='Complete the task')
def finish_task() -> ActionResult:
return ActionResult(
extracted_content="Task completed!",
diff --git a/docs/development/local-setup.mdx b/docs/development/local-setup.mdx
index 44827401e..43f4f349f 100644
--- a/docs/development/local-setup.mdx
+++ b/docs/development/local-setup.mdx
@@ -131,7 +131,7 @@ uv run type
# Run specific tests
uv run pytest # run everything
-uv run pytest tests/test_controller.py # run a specific test file
+uv run pytest tests/test_tools.py # run a specific test file
uv run pytest tests/test_sensitive_data.py tests/test_tab_management.py # run two test files
uv run pytest tests/test_tab_management.py::TestTabManagement::test_user_changes_tab # run a single test
```
diff --git a/examples/browser/using_cdp.py b/examples/browser/using_cdp.py
index 916dfb73c..4fc0c4553 100644
--- a/examples/browser/using_cdp.py
+++ b/examples/browser/using_cdp.py
@@ -32,14 +32,14 @@ browser_session = BrowserSession(
cdp_url='http://localhost:9222',
is_local=True, # set to False if you want to use a remote browser
)
-controller = Tools()
+tools = Tools()
async def main():
agent = Agent(
task='Visit https://duckduckgo.com and search for "browser-use founders"',
lllm=ChatOpenAI(model='gpt-4.1-mini'),
- controller=controller,
+ tools=tools,
browser_session=browser_session,
)
diff --git a/examples/custom-functions/2fa.py b/examples/custom-functions/2fa.py
index 0f0622c24..c9a41dfaa 100644
--- a/examples/custom-functions/2fa.py
+++ b/examples/custom-functions/2fa.py
@@ -18,10 +18,10 @@ logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
-controller = Tools()
+tools = Tools()
[email protected]('Get 2FA code from when OTP is required')
[email protected]('Get 2FA code from when OTP is required')
async def get_otp_2fa() -> ActionResult:
"""
Custom action to retrieve 2FA/MFA code from OTP secret key using pyotp.
@@ -56,7 +56,7 @@ async def main():
"""
model = ChatOpenAI(model='gpt-4.1-mini')
- agent = Agent(task=task, llm=model, controller=controller)
+ agent = Agent(task=task, llm=model, tools=tools)
result = await agent.run()
print(f'Task completed with result: {result}')
diff --git a/examples/custom-functions/action_filters.py b/examples/custom-functions/action_filters.py
index b4e1d865c..e90cb7b2f 100644
--- a/examples/custom-functions/action_filters.py
+++ b/examples/custom-functions/action_filters.py
@@ -31,9 +31,9 @@ from browser_use import ChatOpenAI
from browser_use.agent.service import Agent, Tools
from browser_use.browser import BrowserSession
-# Initialize controller and registry
-controller = Tools()
-registry = controller.registry
+# Initialize tools and registry
+tools = Tools()
+registry = tools.registry
# Action will only be available to Agent on Google domains because of the domain filter
@@ -106,7 +106,7 @@ async def main():
""",
llm=llm,
browser_session=browser_session,
- controller=controller,
+ tools=tools,
)
# Run the agent
diff --git a/examples/custom-functions/advanced_search.py b/examples/custom-functions/advanced_search.py
index 455356418..cd38395ff 100644
--- a/examples/custom-functions/advanced_search.py
+++ b/examples/custom-functions/advanced_search.py
@@ -33,10 +33,10 @@ SERP_API_KEY = os.getenv('SERPER_API_KEY')
if not SERP_API_KEY:
raise ValueError('SERPER_API_KEY is not set')
-controller = Tools(exclude_actions=['search_google'], output_model=PersonList)
+tools = Tools(exclude_actions=['search_google'], output_model=PersonList)
[email protected]('Search the web for a specific query. Returns a short description and links of the results.')
[email protected]('Search the web for a specific query. Returns a short description and links of the results.')
async def search_web(query: str):
# do a serp search for the query
conn = http.client.HTTPSConnection('google.serper.dev')
@@ -94,7 +94,7 @@ async def main():
task += '\n' + '\n'.join(names)
model = ChatOpenAI(model='gpt-4.1-mini')
browser_profile = BrowserProfile()
- agent = Agent(task=task, llm=model, controller=controller, browser_profile=browser_profile)
+ agent = Agent(task=task, llm=model, tools=tools, browser_profile=browser_profile)
history = await agent.run()
diff --git a/examples/custom-functions/cua.py b/examples/custom-functions/cua.py
index f41f2c300..5b07d9bdc 100644
--- a/examples/custom-functions/cua.py
+++ b/examples/custom-functions/cua.py
@@ -177,10 +177,10 @@ async def handle_model_action(browser_session: BrowserSession, action) -> Action
return ActionResult(error=ERROR_MSG)
-controller = Tools()
+tools = Tools()
'Use OpenAI Computer Use Assistant (CUA) as a fallback when standard browser actions cannot achieve the desired goal. This action sends a screenshot and description to OpenAI CUA and executes the returned computer use actions.',
param_model=OpenAICUAAction,
)
@@ -294,11 +294,11 @@ async def main():
Use the OpenAI CUA fallback to click on "Tree is open..." link.
"""
- # Create agent with our custom controller that includes CUA fallback
+ # Create agent with our custom tools that includes CUA fallback
agent = Agent(
task=task,
llm=llm,
- controller=controller,
+ tools=tools,
browser_session=browser_session,
)
diff --git a/examples/custom-functions/file_upload.py b/examples/custom-functions/file_upload.py
index 9f856eaad..5ef3af752 100644
--- a/examples/custom-functions/file_upload.py
+++ b/examples/custom-functions/file_upload.py
@@ -25,11 +25,11 @@ from browser_use.browser.events import UploadFileEvent
logger = logging.getLogger(__name__)
-# Initialize controller
-controller = Tools()
+# Initialize tools
+tools = Tools()
[email protected]('Upload file to interactive element with file path')
[email protected]('Upload file to interactive element with file path')
async def upload_file(index: int, path: str, browser_session: BrowserSession, available_file_paths: list[str]):
if path not in available_file_paths:
return ActionResult(error=f'File path {path} is not available')
@@ -93,8 +93,8 @@ async def main():
""",
llm=llm,
browser_session=browser_session,
- controller=controller,
- # Pass the available file paths to the controller context
+ tools=tools,
+ # Pass the available file paths to the tools context
custom_context={'available_file_paths': available_file_paths},
)
diff --git a/examples/custom-functions/notification.py b/examples/custom-functions/notification.py
index efb423129..0892eedf7 100644
--- a/examples/custom-functions/notification.py
+++ b/examples/custom-functions/notification.py
@@ -10,10 +10,10 @@ load_dotenv()
from browser_use import ActionResult, Agent, ChatOpenAI, Tools
-controller = Tools()
+tools = Tools()
[email protected]('Done with task ')
[email protected]('Done with task ')
async def done(text: str):
import yagmail # type: ignore
@@ -34,7 +34,7 @@ async def done(text: str):
async def main():
task = 'go to brower-use.com and then done'
model = ChatOpenAI(model='gpt-4.1-mini')
- agent = Agent(task=task, llm=model, controller=controller)
+ agent = Agent(task=task, llm=model, tools=tools)
await agent.run()
diff --git a/examples/custom-functions/onepassword_2fa.py b/examples/custom-functions/onepassword_2fa.py
index db0955359..e21a72590 100644
--- a/examples/custom-functions/onepassword_2fa.py
+++ b/examples/custom-functions/onepassword_2fa.py
@@ -21,10 +21,10 @@ OP_SERVICE_ACCOUNT_TOKEN = os.getenv('OP_SERVICE_ACCOUNT_TOKEN')
OP_ITEM_ID = os.getenv('OP_ITEM_ID') # Go to 1Password, right click on the item, click "Copy Secret Reference"
-controller = Tools()
+tools = Tools()
[email protected]('Get 2FA code from 1Password for Google Account', domains=['*.google.com', 'google.com'])
[email protected]('Get 2FA code from 1Password for Google Account', domains=['*.google.com', 'google.com'])
async def get_1password_2fa() -> ActionResult:
"""
Custom action to retrieve 2FA/MFA code from 1Password using onepassword.client SDK.
@@ -46,7 +46,7 @@ async def main():
task = 'Go to account.google.com, enter username and password, then if prompted for 2FA code, get 2FA code from 1Password for and enter it'
model = ChatOpenAI(model='gpt-4.1-mini')
- agent = Agent(task=task, llm=model, controller=controller)
+ agent = Agent(task=task, llm=model, tools=tools)
result = await agent.run()
print(f'Task completed with result: {result}')
diff --git a/examples/custom-functions/save_to_file_hugging_face.py b/examples/custom-functions/save_to_file_hugging_face.py
index 3283a0f9f..4099199f1 100644
--- a/examples/custom-functions/save_to_file_hugging_face.py
+++ b/examples/custom-functions/save_to_file_hugging_face.py
@@ -14,8 +14,8 @@ from browser_use import ChatOpenAI
from browser_use.agent.service import Agent
from browser_use.tools.service import Tools
-# Initialize controller first
-controller = Tools()
+# Initialize tools first
+tools = Tools()
class Model(BaseModel):
@@ -29,7 +29,7 @@ class Models(BaseModel):
models: list[Model]
[email protected]('Save models', param_model=Models)
[email protected]('Save models', param_model=Models)
def save_models(params: Models):
with open('models.txt', 'a') as f:
for model in params.models:
@@ -41,7 +41,7 @@ async def main():
task = 'Look up models with a license of cc-by-sa-4.0 and sort by most likes on Hugging face, save top 5 to file.'
model = ChatOpenAI(model='gpt-4.1-mini')
- agent = Agent(task=task, llm=model, controller=controller)
+ agent = Agent(task=task, llm=model, tools=tools)
await agent.run()
diff --git a/examples/integrations/gmail_2fa_integration.py b/examples/integrations/gmail_2fa_integration.py
index ab0e288bd..5add30041 100644
--- a/examples/integrations/gmail_2fa_integration.py
+++ b/examples/integrations/gmail_2fa_integration.py
@@ -241,13 +241,13 @@ async def main():
print('❌ Failed to recover Gmail authentication. Please check your setup.')
return
- # Step 3: Initialize controller with authenticated service
+ # Step 3: Initialize tools with authenticated service
print('\n🔍 Step 3: Registering Gmail actions...')
- controller = Tools()
- register_gmail_actions(controller, gmail_service=gmail_service)
+ tools = Tools()
+ register_gmail_actions(tools, gmail_service=gmail_service)
- print('✅ Gmail actions registered with controller')
+ print('✅ Gmail actions registered with tools')
print('Available Gmail actions:')
print('- get_recent_emails: Get recent emails with filtering')
print()
@@ -258,7 +258,7 @@ async def main():
# Step 4: Test Gmail functionality
print('🔍 Step 4: Testing Gmail email retrieval...')
- agent = Agent(task='Get recent emails from Gmail to test the integration is working properly', llm=llm, controller=controller)
+ agent = Agent(task='Get recent emails from Gmail to test the integration is working properly', llm=llm, tools=tools)
try:
history = await agent.run()
@@ -283,7 +283,7 @@ async def main():
agent2 = Agent(
task='Search for any 2FA verification codes or OTP codes in recent Gmail emails from the last 30 minutes',
llm=llm,
- controller=controller,
+ tools=tools,
)
history2 = await agent2.run()
@@ -307,7 +307,7 @@ async def main():
3. Show what types of emails and codes can be detected
""",
llm=llm,
- controller=controller,
+ tools=tools,
)
history3 = await agent3.run()
diff --git a/examples/mcp/advanced_client.py b/examples/mcp/advanced_client.py
index 9100307ea..a9d175316 100644
--- a/examples/mcp/advanced_client.py
+++ b/examples/mcp/advanced_client.py
@@ -20,8 +20,8 @@ from browser_use.mcp.client import MCPClient
async def main():
"""Sign up for account, save details, and verify via Gmail."""
- # Initialize controller
- controller = Tools()
+ # Initialize tools
+ tools = Tools()
# Connect to Gmail MCP Server
# Requires Gmail API credentials - see: https://github.com/GongRzhe/Gmail-MCP-Server#setup
@@ -45,17 +45,17 @@ async def main():
# Connect and register tools from both servers
print('Connecting to Gmail MCP server...')
await gmail_client.connect()
- await gmail_client.register_to_controller(controller)
+ await gmail_client.register_to_tools(tools)
print('Connecting to Filesystem MCP server...')
await filesystem_client.connect()
- await filesystem_client.register_to_controller(controller)
+ await filesystem_client.register_to_tools(tools)
# Create agent with extended system prompt for using multiple MCP servers
agent = Agent(
task='Sign up for a new Anthropic account using the email [email protected], save the registration details to a file',
llm=ChatOpenAI(model='gpt-4.1-mini'),
- controller=controller,
+ tools=tools,
extend_system_message="""
You have access to both Gmail and Filesystem tools through MCP servers. When signing up for accounts:
diff --git a/examples/mcp/simple_client.py b/examples/mcp/simple_client.py
index 0b79faaeb..1e65a8c44 100644
--- a/examples/mcp/simple_client.py
+++ b/examples/mcp/simple_client.py
@@ -13,8 +13,8 @@ from browser_use.mcp.client import MCPClient
async def main():
- # Initialize controller
- controller = Tools()
+ # Initialize tools
+ tools = Tools()
# Connect to a filesystem MCP server
# This server provides tools to read/write files in a directory
@@ -24,13 +24,13 @@ async def main():
# Connect and register MCP tools
await mcp_client.connect()
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
- # Create agent with MCP-enabled controller
+ # Create agent with MCP-enabled tools
agent = Agent(
task='List all files on the Desktop and read the content of any .txt files you find',
llm=ChatOpenAI(model='gpt-4.1-mini'),
- controller=controller,
+ tools=tools,
)
# Run the agent - it now has access to filesystem tools
diff --git a/examples/ui/command_line.py b/examples/ui/command_line.py
index d9291cfed..5600f5856 100644
--- a/examples/ui/command_line.py
+++ b/examples/ui/command_line.py
@@ -70,13 +70,13 @@ def parse_arguments():
def initialize_agent(query: str, provider: str):
"""Initialize the browser agent with the given query and provider."""
llm = get_llm(provider)
- controller = Tools()
+ tools = Tools()
browser_session = BrowserSession()
return Agent(
task=query,
llm=llm,
- controller=controller,
+ tools=tools,
browser_session=browser_session,
use_vision=True,
max_actions_per_step=1,
diff --git a/examples/ui/streamlit_demo.py b/examples/ui/streamlit_demo.py
index f9d3927b2..efa7c9651 100644
--- a/examples/ui/streamlit_demo.py
+++ b/examples/ui/streamlit_demo.py
@@ -54,13 +54,13 @@ def get_llm(provider: str):
# Function to initialize the agent
def initialize_agent(query: str, provider: str):
llm = get_llm(provider)
- controller = Tools()
+ tools = Tools()
browser_session = BrowserSession()
return Agent(
task=query,
llm=llm, # type: ignore
- controller=controller,
+ tools=tools,
browser_session=browser_session,
use_vision=True,
max_actions_per_step=1,
diff --git a/examples/use-cases/check_appointment.py b/examples/use-cases/check_appointment.py
index a9c5e050f..ffd5a42f5 100644
--- a/examples/use-cases/check_appointment.py
+++ b/examples/use-cases/check_appointment.py
@@ -19,7 +19,7 @@ from browser_use.tools.service import Tools
if not os.getenv('OPENAI_API_KEY'):
raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')
-controller = Tools()
+tools = Tools()
class WebpageInfo(BaseModel):
@@ -28,7 +28,7 @@ class WebpageInfo(BaseModel):
link: str = 'https://appointment.mfa.gr/en/reservations/aero/ireland-grcon-dub/'
[email protected]('Go to the webpage', param_model=WebpageInfo)
[email protected]('Go to the webpage', param_model=WebpageInfo)
def go_to_webpage(webpage_info: WebpageInfo):
"""Returns the webpage link."""
return webpage_info.link
@@ -43,7 +43,7 @@ async def main():
)
model = ChatOpenAI(model='gpt-4.1-mini')
- agent = Agent(task, model, controller=controller, use_vision=True)
+ agent = Agent(task, model, tools=tools, use_vision=True)
await agent.run()
diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.py
index 4e6b5e06a..da302ae65 100644
--- a/examples/use-cases/find_and_apply_to_jobs.py
+++ b/examples/use-cases/find_and_apply_to_jobs.py
@@ -31,7 +31,7 @@ for var in required_env_vars:
logger = logging.getLogger(__name__)
# full screen mode
-controller = Tools()
+tools = Tools()
# NOTE: This is the path to your cv file
# create a dummy cv
@@ -51,7 +51,7 @@ class Job(BaseModel):
salary: str | None = None
[email protected]('Save jobs to file - with a score how well it fits to my profile', param_model=Job)
[email protected]('Save jobs to file - with a score how well it fits to my profile', param_model=Job)
def save_jobs(job: Job):
with open('jobs.csv', 'a', newline='') as f:
writer = csv.writer(f)
@@ -60,13 +60,13 @@ def save_jobs(job: Job):
return 'Saved job to file'
[email protected]('Read jobs from file')
[email protected]('Read jobs from file')
def read_jobs():
with open('jobs.csv') as f:
return f.read()
[email protected]('Read my cv for context to fill forms')
[email protected]('Read my cv for context to fill forms')
def read_cv():
pdf = PdfReader(CV)
text = ''
@@ -76,7 +76,7 @@ def read_cv():
return ActionResult(extracted_content=text, include_in_memory=True)
'Upload cv to element - call this function to upload if element is not found, try with different index of the same upload element',
)
async def upload_cv(index: int, browser_session: BrowserSession):
@@ -147,7 +147,7 @@ async def main():
agents = []
for task in tasks:
- agent = Agent(task=task, llm=model, controller=controller, browser_session=browser_session)
+ agent = Agent(task=task, llm=model, tools=tools, browser_session=browser_session)
agents.append(agent)
await asyncio.gather(*[agent.run() for agent in agents])
diff --git a/examples/use-cases/find_influencer_profiles.py b/examples/use-cases/find_influencer_profiles.py
index 42ec28541..1f90bf16a 100644
--- a/examples/use-cases/find_influencer_profiles.py
+++ b/examples/use-cases/find_influencer_profiles.py
@@ -31,7 +31,7 @@ class Profiles(BaseModel):
profiles: list[Profile]
-controller = Tools(exclude_actions=['search_google'], output_model=Profiles)
+tools = Tools(exclude_actions=['search_google'], output_model=Profiles)
BEARER_TOKEN = os.getenv('BEARER_TOKEN')
if not BEARER_TOKEN:
@@ -40,7 +40,7 @@ if not BEARER_TOKEN:
raise ValueError('BEARER_TOKEN is not set - go to https://www.heytessa.ai/ and create an api key')
[email protected]('Search the web for a specific query')
[email protected]('Search the web for a specific query')
async def search_web(query: str):
keys_to_use = ['url', 'title', 'content', 'author', 'score']
headers = {'Authorization': f'Bearer {BEARER_TOKEN}'}
@@ -68,7 +68,7 @@ async def main():
' https://www.tiktokv.com/share/video/7470981717659110678/ '
)
model = ChatOpenAI(model='gpt-4.1-mini')
- agent = Agent(task=task, llm=model, controller=controller)
+ agent = Agent(task=task, llm=model, tools=tools)
history = await agent.run()
diff --git a/tests/ci/conftest.py b/tests/ci/conftest.py
index ca41e9665..e84d8a63f 100644
--- a/tests/ci/conftest.py
+++ b/tests/ci/conftest.py
@@ -84,8 +84,8 @@ def create_mock_llm(actions: list[str] | None = None) -> BaseChatModel:
Returns:
Mock LLM that will return the actions in order, or just a done action if no actions provided.
"""
- controller = Tools()
- ActionModel = controller.registry.create_action_model()
+ tools = Tools()
+ ActionModel = tools.registry.create_action_model()
AgentOutputWithActions = AgentOutput.type_with_custom_actions(ActionModel)
llm = AsyncMock(spec=BaseChatModel)
diff --git a/tests/ci/test_browser_event_ClickElementEvent.py b/tests/ci/test_browser_event_ClickElementEvent.py
index e95b3a5f4..263b15954 100644
--- a/tests/ci/test_browser_event_ClickElementEvent.py
+++ b/tests/ci/test_browser_event_ClickElementEvent.py
@@ -64,7 +64,7 @@ async def browser_session():
@pytest.fixture(scope='function')
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -72,7 +72,7 @@ def controller():
class TestClickElementEvent:
"""Test cases for ClickElementEvent and click_element_by_index action."""
- async def test_error_handling(self, controller, browser_session):
+ async def test_error_handling(self, tools, browser_session):
"""Test error handling when an action fails."""
# Create an action with an invalid index
invalid_action = {'click_element_by_index': ClickElementAction(index=999)} # doesn't exist on page
@@ -83,11 +83,11 @@ class TestClickElementEvent:
click_element_by_index: ClickElementAction | None = None
# This should fail since the element doesn't exist
- result: ActionResult = await controller.act(ClickActionModel(**invalid_action), browser_session)
+ result: ActionResult = await tools.act(ClickActionModel(**invalid_action), browser_session)
assert result.error is not None
- async def test_click_element_by_index(self, controller, browser_session, base_url, http_server):
+ async def test_click_element_by_index(self, tools, browser_session, base_url, http_server):
"""Test that click_element_by_index correctly clicks an element and handles different outcomes."""
# Add route for clickable elements test page
http_server.expect_request('/clickable').respond_with_data(
@@ -137,7 +137,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for the page to load
await asyncio.sleep(0.5) # Give page time to load
@@ -178,7 +178,7 @@ class TestClickElementEvent:
click_element_by_index: ClickElementAction | None = None
# Execute the action with the button index
- result = await controller.act(
+ result = await tools.act(
ClickElementActionModel(click_element_by_index=ClickElementAction(index=button_index)), browser_session
)
@@ -202,7 +202,7 @@ class TestClickElementEvent:
result_text = result_js.get('result', {}).get('value', '')
assert result_text == expected_result_text, f"Expected result text '{expected_result_text}', got '{result_text}'"
- async def test_click_element_new_tab(self, controller, browser_session, base_url, http_server):
+ async def test_click_element_new_tab(self, tools, browser_session, base_url, http_server):
"""Test that click_element_by_index with while_holding_ctrl=True opens links in new tabs."""
# Add route for new tab test page
http_server.expect_request('/newTab').respond_with_data(
@@ -229,7 +229,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(1) # Wait for page to load
# Count initial tabs
@@ -255,7 +255,7 @@ class TestClickElementEvent:
class ClickActionModel(ActionModel):
click_element_by_index: ClickElementAction | None = None
- result = await controller.act(ClickActionModel(**click_action), browser_session)
+ result = await tools.act(ClickActionModel(**click_action), browser_session)
await asyncio.sleep(1) # Wait for new tab to open
# Verify the result
@@ -284,7 +284,7 @@ class TestClickElementEvent:
# Verify the new tab has the correct URL
assert f'{base_url}/page1' in new_tab.url, f'New tab should have page1 URL, but got {new_tab.url}'
- async def test_click_element_normal_vs_new_tab(self, controller, browser_session, base_url, http_server):
+ async def test_click_element_normal_vs_new_tab(self, tools, browser_session, base_url, http_server):
"""Test that click_element_by_index behaves differently with while_holding_ctrl=False vs while_holding_ctrl=True."""
# Add route for comparison test page
http_server.expect_request('/comparison').respond_with_data(
@@ -312,7 +312,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(1)
tabs = await browser_session.get_tabs()
@@ -333,7 +333,7 @@ class TestClickElementEvent:
class ClickActionModel(ActionModel):
click_element_by_index: ClickElementAction | None = None
- result = await controller.act(ClickActionModel(**click_action_normal), browser_session)
+ result = await tools.act(ClickActionModel(**click_action_normal), browser_session)
await asyncio.sleep(1)
# Should still have same number of tabs
@@ -341,19 +341,19 @@ class TestClickElementEvent:
assert len(tabs) == initial_tab_count
# Navigate back to comparison page for second test
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(1)
# Test new tab click (while_holding_ctrl=True) - should open in new background tab
click_action_new_tab = {'click_element_by_index': ClickElementAction(index=link_indices[1], while_holding_ctrl=True)}
- result = await controller.act(ClickActionModel(**click_action_new_tab), browser_session)
+ result = await tools.act(ClickActionModel(**click_action_new_tab), browser_session)
await asyncio.sleep(1)
# Should have one more tab
tabs = await browser_session.get_tabs()
assert len(tabs) == initial_tab_count + 1
- async def test_inline_element_mostly_offscreen(self, controller, browser_session, base_url, http_server):
+ async def test_inline_element_mostly_offscreen(self, tools, browser_session, base_url, http_server):
"""Test clicking an inline element that's mostly outside the viewport."""
# Add route for test page with inline element extending beyond viewport
http_server.expect_request('/inline_offscreen').respond_with_data(
@@ -399,7 +399,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(0.5)
# Get the clickable elements
@@ -419,9 +419,7 @@ class TestClickElementEvent:
class ClickActionModel(ActionModel):
click_element_by_index: ClickElementAction | None = None
- result = await controller.act(
- ClickActionModel(click_element_by_index=ClickElementAction(index=inline_index)), browser_session
- )
+ result = await tools.act(ClickActionModel(click_element_by_index=ClickElementAction(index=inline_index)), browser_session)
assert result.error is None, f'Click failed: {result.error}'
@@ -433,7 +431,7 @@ class TestClickElementEvent:
)
assert result_js.get('result', {}).get('value') == 'Inline clicked'
- async def test_block_inside_inline_multiline(self, controller, browser_session, base_url, http_server):
+ async def test_block_inside_inline_multiline(self, tools, browser_session, base_url, http_server):
"""Test clicking a block element inside an inline element that spans multiple lines."""
# Add route for complex nested layout
http_server.expect_request('/block_in_inline').respond_with_data(
@@ -483,7 +481,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(0.5)
# Get the clickable elements
@@ -503,9 +501,7 @@ class TestClickElementEvent:
class ClickActionModel(ActionModel):
click_element_by_index: ClickElementAction | None = None
- result = await controller.act(
- ClickActionModel(click_element_by_index=ClickElementAction(index=block_index)), browser_session
- )
+ result = await tools.act(ClickActionModel(click_element_by_index=ClickElementAction(index=block_index)), browser_session)
assert result.error is None, f'Click failed: {result.error}'
@@ -517,7 +513,7 @@ class TestClickElementEvent:
)
assert result_js.get('result', {}).get('value') == 'Block clicked'
- async def test_element_covered_by_overlay(self, controller, browser_session, base_url, http_server):
+ async def test_element_covered_by_overlay(self, tools, browser_session, base_url, http_server):
"""Test clicking an element that's mostly covered by another element."""
# Add route for overlapping elements
http_server.expect_request('/covered_element').respond_with_data(
@@ -573,7 +569,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(0.5)
# Get the clickable elements
@@ -593,9 +589,7 @@ class TestClickElementEvent:
class ClickActionModel(ActionModel):
click_element_by_index: ClickElementAction | None = None
- result = await controller.act(
- ClickActionModel(click_element_by_index=ClickElementAction(index=target_index)), browser_session
- )
+ result = await tools.act(ClickActionModel(click_element_by_index=ClickElementAction(index=target_index)), browser_session)
assert result.error is None, f'Click failed: {result.error}'
@@ -607,7 +601,7 @@ class TestClickElementEvent:
)
assert result_js.get('result', {}).get('value') == 'Target clicked'
- async def test_file_input_click_prevention(self, controller, browser_session, base_url, http_server):
+ async def test_file_input_click_prevention(self, tools, browser_session, base_url, http_server):
"""Test that clicking a file input element raises an exception."""
# Add route with file input
http_server.expect_request('/file_input').respond_with_data(
@@ -635,7 +629,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(0.5)
# Get the clickable elements
@@ -656,7 +650,7 @@ class TestClickElementEvent:
class ClickActionModel(ActionModel):
click_element_by_index: ClickElementAction | None = None
- result = await controller.act(
+ result = await tools.act(
ClickActionModel(click_element_by_index=ClickElementAction(index=file_input_index)), browser_session
)
@@ -666,7 +660,7 @@ class TestClickElementEvent:
f'Error message should mention file input, got: {result.error}'
)
- async def test_select_dropdown_click_prevention(self, controller, browser_session, base_url, http_server):
+ async def test_select_dropdown_click_prevention(self, tools, browser_session, base_url, http_server):
"""Test that clicking a select dropdown element raises an exception."""
# Add route with select dropdown
http_server.expect_request('/select_dropdown').respond_with_data(
@@ -698,7 +692,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(0.5)
# Get the clickable elements
@@ -718,9 +712,7 @@ class TestClickElementEvent:
class ClickActionModel(ActionModel):
click_element_by_index: ClickElementAction | None = None
- result = await controller.act(
- ClickActionModel(click_element_by_index=ClickElementAction(index=select_index)), browser_session
- )
+ result = await tools.act(ClickActionModel(click_element_by_index=ClickElementAction(index=select_index)), browser_session)
# Should have an error about select elements
assert result.error is not None, 'Expected error for select element click'
@@ -1009,7 +1001,7 @@ class TestClickElementEvent:
f'Navigation should have succeeded after beforeunload was accepted, current URL: {current_url}'
)
- async def test_file_upload_click_and_verify(self, controller, browser_session, base_url, http_server):
+ async def test_file_upload_click_and_verify(self, tools, browser_session, base_url, http_server):
"""Test that clicking a file upload element and uploading a file works correctly."""
# Create a temporary test file
import tempfile as temp_module
@@ -1096,7 +1088,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for the page to load
await asyncio.sleep(0.5)
@@ -1129,7 +1121,7 @@ class TestClickElementEvent:
file_system = FileSystem(base_dir=temp_dir)
# Upload the file using the label index (should find the associated file input)
- result = await controller.act(
+ result = await tools.act(
UploadFileActionModel(upload_file_to_element=UploadFileAction(index=label_index, path=temp_file_path)),
browser_session,
available_file_paths=[temp_file_path], # Pass the file path as available
@@ -1207,7 +1199,7 @@ class TestClickElementEvent:
# Clean up the temporary file
Path(temp_file_path).unlink(missing_ok=True)
- async def test_file_upload_path_validation(self, controller, browser_session, base_url, http_server):
+ async def test_file_upload_path_validation(self, tools, browser_session, base_url, http_server):
"""Test that file upload validates paths correctly with available_file_paths, downloaded_files, and FileSystem."""
from pathlib import Path
@@ -1241,7 +1233,7 @@ class TestClickElementEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(0.5)
# Get browser state to populate selector map
@@ -1262,7 +1254,7 @@ class TestClickElementEvent:
try:
# This should fail because the file is not in available_file_paths
- result = await controller.act(
+ result = await tools.act(
upload_action,
browser_session,
available_file_paths=[], # Empty available_file_paths
@@ -1274,7 +1266,7 @@ class TestClickElementEvent:
assert 'not available' in str(e), f'Error should mention file not available: {e}'
# Test 2: Add file to available_file_paths - should succeed
- result = await controller.act(
+ result = await tools.act(
upload_action,
browser_session,
available_file_paths=[test_file_path], # File is now in available_file_paths
@@ -1289,7 +1281,7 @@ class TestClickElementEvent:
# Try to upload using just the filename (should check FileSystem)
upload_action_fs = UploadActionModel(upload_file_to_element=UploadFileAction(index=1, path='test.txt'))
- result = await controller.act(
+ result = await tools.act(
upload_action_fs,
browser_session,
available_file_paths=[], # Empty available_file_paths
@@ -1302,7 +1294,7 @@ class TestClickElementEvent:
browser_session._downloaded_files.append(test_file_path)
# Try uploading with the file only in downloaded_files
- result = await controller.act(
+ result = await tools.act(
upload_action,
browser_session,
available_file_paths=[], # Empty available_file_paths, but file is in downloaded_files
diff --git a/tests/ci/test_browser_event_GetDropdownOptionsEvent.py b/tests/ci/test_browser_event_GetDropdownOptionsEvent.py
index 124874320..1c3bbf1ac 100644
--- a/tests/ci/test_browser_event_GetDropdownOptionsEvent.py
+++ b/tests/ci/test_browser_event_GetDropdownOptionsEvent.py
@@ -266,7 +266,7 @@ async def browser_session():
@pytest.fixture(scope='function')
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -274,7 +274,7 @@ def controller():
class TestGetDropdownOptionsEvent:
"""Test GetDropdownOptionsEvent functionality for various dropdown types."""
- async def test_native_select_dropdown(self, controller, browser_session: BrowserSession, base_url):
+ async def test_native_select_dropdown(self, tools, browser_session: BrowserSession, base_url):
"""Test get_dropdown_options with native HTML select element."""
# Navigate to the native dropdown test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/native-dropdown', new_tab=False)}
@@ -282,7 +282,7 @@ class TestGetDropdownOptionsEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Initialize the DOM state to populate the selector map
await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=True)
@@ -299,11 +299,11 @@ class TestGetDropdownOptionsEvent:
f'Could not find select element in selector map. Available elements: {[f"{idx}: {element.tag_name}" for idx, element in selector_map.items()]}'
)
- # Test via controller action
+ # Test via tools action
class GetDropdownOptionsModel(ActionModel):
get_dropdown_options: dict[str, int]
- result = await controller.act(
+ result = await tools.act(
action=GetDropdownOptionsModel(get_dropdown_options={'index': dropdown_index}),
browser_session=browser_session,
)
@@ -331,7 +331,7 @@ class TestGetDropdownOptionsEvent:
assert 'type' in dropdown_data
assert dropdown_data['type'] == 'select'
- async def test_aria_menu_dropdown(self, controller, browser_session: BrowserSession, base_url):
+ async def test_aria_menu_dropdown(self, tools, browser_session: BrowserSession, base_url):
"""Test get_dropdown_options with ARIA role='menu' element."""
# Navigate to the ARIA menu test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/aria-menu', new_tab=False)}
@@ -339,7 +339,7 @@ class TestGetDropdownOptionsEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Initialize the DOM state
await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=True)
@@ -360,11 +360,11 @@ class TestGetDropdownOptionsEvent:
f'Could not find ARIA menu element in selector map. Available elements: {[f"{idx}: {element.tag_name} role={element.attributes.get('role', 'None')}" for idx, element in selector_map.items()]}'
)
- # Test via controller action
+ # Test via tools action
class GetDropdownOptionsModel(ActionModel):
get_dropdown_options: dict[str, int]
- result = await controller.act(
+ result = await tools.act(
action=GetDropdownOptionsModel(get_dropdown_options={'index': menu_index}),
browser_session=browser_session,
)
@@ -389,7 +389,7 @@ class TestGetDropdownOptionsEvent:
assert 'type' in dropdown_data
assert dropdown_data['type'] == 'aria'
- async def test_custom_dropdown(self, controller, browser_session: BrowserSession, base_url):
+ async def test_custom_dropdown(self, tools, browser_session: BrowserSession, base_url):
"""Test get_dropdown_options with custom dropdown implementation."""
# Navigate to the custom dropdown test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/custom-dropdown', new_tab=False)}
@@ -397,7 +397,7 @@ class TestGetDropdownOptionsEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Initialize the DOM state
await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=True)
@@ -414,11 +414,11 @@ class TestGetDropdownOptionsEvent:
f'Could not find custom dropdown element in selector map. Available elements: {[f"{idx}: {element.tag_name} id={element.attributes.get('id', 'None')}" for idx, element in selector_map.items()]}'
)
- # Test via controller action
+ # Test via tools action
class GetDropdownOptionsModel(ActionModel):
get_dropdown_options: dict[str, int]
- result = await controller.act(
+ result = await tools.act(
action=GetDropdownOptionsModel(get_dropdown_options={'index': dropdown_index}),
browser_session=browser_session,
)
@@ -443,7 +443,7 @@ class TestGetDropdownOptionsEvent:
assert 'type' in dropdown_data
assert dropdown_data['type'] == 'custom'
- async def test_element_not_found_error(self, controller, browser_session: BrowserSession, base_url):
+ async def test_element_not_found_error(self, tools, browser_session: BrowserSession, base_url):
"""Test get_dropdown_options with invalid element index."""
# Navigate to any test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/native-dropdown', new_tab=False)}
@@ -451,14 +451,14 @@ class TestGetDropdownOptionsEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await browser_session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)
# Try to get dropdown options with invalid index
class GetDropdownOptionsModel(ActionModel):
get_dropdown_options: dict[str, int]
- result = await controller.act(
+ result = await tools.act(
action=GetDropdownOptionsModel(get_dropdown_options={'index': 99999}),
browser_session=browser_session,
)
@@ -472,7 +472,7 @@ class TestGetDropdownOptionsEvent:
class TestSelectDropdownOptionEvent:
"""Test SelectDropdownOptionEvent functionality for various dropdown types."""
- async def test_select_native_dropdown_option(self, controller, browser_session: BrowserSession, base_url):
+ async def test_select_native_dropdown_option(self, tools, browser_session: BrowserSession, base_url):
"""Test select_dropdown_option with native HTML select element."""
# Navigate to the native dropdown test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/native-dropdown', new_tab=False)}
@@ -480,7 +480,7 @@ class TestSelectDropdownOptionEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await browser_session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)
# Initialize the DOM state
@@ -496,11 +496,11 @@ class TestSelectDropdownOptionEvent:
assert dropdown_index is not None
- # Test via controller action
+ # Test via tools action
class SelectDropdownOptionModel(ActionModel):
select_dropdown_option: dict
- result = await controller.act(
+ result = await tools.act(
SelectDropdownOptionModel(select_dropdown_option={'index': dropdown_index, 'text': 'Second Option'}),
browser_session,
)
@@ -519,7 +519,7 @@ class TestSelectDropdownOptionEvent:
selected_index = result.get('result', {}).get('value', -1)
assert selected_index == 2, f'Expected selected index 2, got {selected_index}'
- async def test_select_aria_menu_option(self, controller, browser_session: BrowserSession, base_url):
+ async def test_select_aria_menu_option(self, tools, browser_session: BrowserSession, base_url):
"""Test select_dropdown_option with ARIA menu."""
# Navigate to the ARIA menu test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/aria-menu', new_tab=False)}
@@ -527,7 +527,7 @@ class TestSelectDropdownOptionEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await browser_session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)
# Initialize the DOM state
@@ -547,11 +547,11 @@ class TestSelectDropdownOptionEvent:
assert menu_index is not None
- # Test via controller action
+ # Test via tools action
class SelectDropdownOptionModel(ActionModel):
select_dropdown_option: dict
- result = await controller.act(
+ result = await tools.act(
SelectDropdownOptionModel(select_dropdown_option={'index': menu_index, 'text': 'Filter'}),
browser_session,
)
@@ -570,7 +570,7 @@ class TestSelectDropdownOptionEvent:
result_text = result.get('result', {}).get('value', '')
assert 'Filter' in result_text, f"Expected 'Filter' in result text, got '{result_text}'"
- async def test_select_custom_dropdown_option(self, controller, browser_session: BrowserSession, base_url):
+ async def test_select_custom_dropdown_option(self, tools, browser_session: BrowserSession, base_url):
"""Test select_dropdown_option with custom dropdown."""
# Navigate to the custom dropdown test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/custom-dropdown', new_tab=False)}
@@ -578,7 +578,7 @@ class TestSelectDropdownOptionEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await browser_session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)
# Initialize the DOM state
@@ -594,11 +594,11 @@ class TestSelectDropdownOptionEvent:
assert dropdown_index is not None
- # Test via controller action
+ # Test via tools action
class SelectDropdownOptionModel(ActionModel):
select_dropdown_option: dict
- result = await controller.act(
+ result = await tools.act(
SelectDropdownOptionModel(select_dropdown_option={'index': dropdown_index, 'text': 'Blue'}),
browser_session,
)
@@ -617,7 +617,7 @@ class TestSelectDropdownOptionEvent:
result_text = result.get('result', {}).get('value', '')
assert 'Blue' in result_text, f"Expected 'Blue' in result text, got '{result_text}'"
- async def test_select_invalid_option_error(self, controller, browser_session: BrowserSession, base_url):
+ async def test_select_invalid_option_error(self, tools, browser_session: BrowserSession, base_url):
"""Test select_dropdown_option with non-existent option text."""
# Navigate to the native dropdown test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/native-dropdown', new_tab=False)}
@@ -625,7 +625,7 @@ class TestSelectDropdownOptionEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await browser_session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)
# Initialize the DOM state
diff --git a/tests/ci/test_browser_event_GetDropdownOptionsEvent_aria_menus.py b/tests/ci/test_browser_event_GetDropdownOptionsEvent_aria_menus.py
index bc84beb1a..eddf4cb1a 100644
--- a/tests/ci/test_browser_event_GetDropdownOptionsEvent_aria_menus.py
+++ b/tests/ci/test_browser_event_GetDropdownOptionsEvent_aria_menus.py
@@ -140,7 +140,7 @@ async def browser_session():
@pytest.fixture(scope='function')
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -149,7 +149,7 @@ class TestARIAMenuDropdown:
"""Test ARIA menu support for get_dropdown_options and select_dropdown_option."""
@pytest.mark.skip(reason='TODO: fix')
- async def test_get_dropdown_options_with_aria_menu(self, controller, browser_session: BrowserSession, base_url):
+ async def test_get_dropdown_options_with_aria_menu(self, tools, browser_session: BrowserSession, base_url):
"""Test that get_dropdown_options can retrieve options from ARIA menus."""
# Navigate to the ARIA menu test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/aria-menu', new_tab=False)}
@@ -157,7 +157,7 @@ class TestARIAMenuDropdown:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for the page to load
from browser_use.browser.events import NavigationCompleteEvent
@@ -196,7 +196,7 @@ class TestARIAMenuDropdown:
get_dropdown_options: dict[str, int]
# Execute the action with the menu index
- result = await controller.act(
+ result = await tools.act(
action=GetDropdownOptionsModel(get_dropdown_options={'index': menu_index}),
browser_session=browser_session,
)
@@ -216,7 +216,7 @@ class TestARIAMenuDropdown:
assert 'Use the exact text string in select_dropdown_option' in result.extracted_content
@pytest.mark.skip(reason='TODO: fix')
- async def test_select_dropdown_option_with_aria_menu(self, controller, browser_session: BrowserSession, base_url):
+ async def test_select_dropdown_option_with_aria_menu(self, tools, browser_session: BrowserSession, base_url):
"""Test that select_dropdown_option can select an option from ARIA menus."""
# Navigate to the ARIA menu test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/aria-menu', new_tab=False)}
@@ -224,7 +224,7 @@ class TestARIAMenuDropdown:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for the page to load
from browser_use.browser.events import NavigationCompleteEvent
@@ -263,7 +263,7 @@ class TestARIAMenuDropdown:
select_dropdown_option: dict
# Execute the action with the menu index to select "Filter"
- result = await controller.act(
+ result = await tools.act(
SelectDropdownOptionModel(select_dropdown_option={'index': menu_index, 'text': 'Filter'}),
browser_session,
)
@@ -286,7 +286,7 @@ class TestARIAMenuDropdown:
assert 'Filter' in result_text, f"Expected 'Filter' in result text, got '{result_text}'"
@pytest.mark.skip(reason='TODO: fix')
- async def test_get_dropdown_options_with_nested_aria_menu(self, controller, browser_session: BrowserSession, base_url):
+ async def test_get_dropdown_options_with_nested_aria_menu(self, tools, browser_session: BrowserSession, base_url):
"""Test that get_dropdown_options can handle nested ARIA menus (like Sort submenu)."""
# Navigate to the ARIA menu test page
goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/aria-menu', new_tab=False)}
@@ -294,7 +294,7 @@ class TestARIAMenuDropdown:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for the page to load
from browser_use.browser.events import NavigationCompleteEvent
@@ -337,7 +337,7 @@ class TestARIAMenuDropdown:
get_dropdown_options: dict[str, int]
# Execute the action with the menu index
- result = await controller.act(
+ result = await tools.act(
action=GetDropdownOptionsModel(get_dropdown_options={'index': nested_menu_index}),
browser_session=browser_session,
)
diff --git a/tests/ci/test_browser_event_NavigateToUrlEvent.py b/tests/ci/test_browser_event_NavigateToUrlEvent.py
index dd97952e9..ec18ccadf 100644
--- a/tests/ci/test_browser_event_NavigateToUrlEvent.py
+++ b/tests/ci/test_browser_event_NavigateToUrlEvent.py
@@ -53,7 +53,7 @@ async def browser_session():
@pytest.fixture
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -61,7 +61,7 @@ def controller():
class TestNavigateToUrlEvent:
"""Test NavigateToUrlEvent and go_to_url action functionality."""
- async def test_go_to_url_action(self, controller, browser_session: BrowserSession, base_url):
+ async def test_go_to_url_action(self, tools, browser_session: BrowserSession, base_url):
"""Test that GoToUrlAction navigates to the specified URL and test both state summary methods."""
# Test successful navigation to a valid page
action_data = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1', new_tab=False)}
@@ -70,14 +70,14 @@ class TestNavigateToUrlEvent:
go_to_url: GoToUrlAction | None = None
action_model = GoToUrlActionModel(**action_data)
- result = await controller.act(action_model, browser_session)
+ result = await tools.act(action_model, browser_session)
# Verify the successful navigation result
assert isinstance(result, ActionResult)
assert result.extracted_content is not None
assert f'Navigated to {base_url}' in result.extracted_content
- async def test_go_to_url_network_error(self, controller, browser_session: BrowserSession):
+ async def test_go_to_url_network_error(self, tools, browser_session: BrowserSession):
"""Test that go_to_url handles network errors gracefully instead of throwing hard errors."""
# Create action model for go_to_url with an invalid domain
action_data = {'go_to_url': GoToUrlAction(url='https://www.nonexistentdndbeyond.com/', new_tab=False)}
@@ -89,7 +89,7 @@ class TestNavigateToUrlEvent:
action_model = GoToUrlActionModel(**action_data)
# Execute the action - should return soft error instead of throwing
- result = await controller.act(action_model, browser_session)
+ result = await tools.act(action_model, browser_session)
# Verify the result
assert isinstance(result, ActionResult)
@@ -123,7 +123,7 @@ class TestNavigateToUrlEvent:
current_url = await browser_session.get_current_page_url()
assert f'{base_url}/page1' in current_url
- async def test_go_to_url_new_tab(self, controller, browser_session, base_url):
+ async def test_go_to_url_new_tab(self, tools, browser_session, base_url):
"""Test that GoToUrlAction with new_tab=True opens URL in a new tab."""
# Get initial tab count
initial_tab_count = len(browser_session.tabs)
@@ -134,7 +134,7 @@ class TestNavigateToUrlEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- result = await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ result = await tools.act(GoToUrlActionModel(**action_data), browser_session)
await asyncio.sleep(0.5)
# Verify result
@@ -150,7 +150,7 @@ class TestNavigateToUrlEvent:
current_url = await browser_session.get_current_page_url()
assert f'{base_url}/page2' in current_url
- async def test_navigate_relative_url(self, controller, browser_session, base_url):
+ async def test_navigate_relative_url(self, tools, browser_session, base_url):
"""Test navigating using relative URLs."""
# First navigate to base URL
action_data = {'go_to_url': GoToUrlAction(url=base_url, new_tab=False)}
@@ -158,11 +158,11 @@ class TestNavigateToUrlEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ await tools.act(GoToUrlActionModel(**action_data), browser_session)
# Now navigate using relative URL
relative_action = {'go_to_url': GoToUrlAction(url='/page1', new_tab=False)}
- result = await controller.act(GoToUrlActionModel(**relative_action), browser_session)
+ result = await tools.act(GoToUrlActionModel(**relative_action), browser_session)
# Verify navigation worked
assert isinstance(result, ActionResult)
@@ -172,7 +172,7 @@ class TestNavigateToUrlEvent:
current_url = await browser_session.get_current_page_url()
assert f'{base_url}/page1' in current_url
- async def test_navigate_javascript_url(self, controller, browser_session, base_url):
+ async def test_navigate_javascript_url(self, tools, browser_session, base_url):
"""Test that javascript: URLs are handled appropriately."""
# Navigate to a normal page first
action_data = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1', new_tab=False)}
@@ -180,16 +180,16 @@ class TestNavigateToUrlEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ await tools.act(GoToUrlActionModel(**action_data), browser_session)
# Try to navigate to javascript: URL (should be handled gracefully)
js_action = {'go_to_url': GoToUrlAction(url='javascript:alert("test")', new_tab=False)}
- result = await controller.act(GoToUrlActionModel(**js_action), browser_session)
+ result = await tools.act(GoToUrlActionModel(**js_action), browser_session)
# Should either succeed or fail gracefully
assert isinstance(result, ActionResult)
- async def test_navigate_data_url(self, controller, browser_session):
+ async def test_navigate_data_url(self, tools, browser_session):
"""Test navigating to a data: URL."""
# Create a simple data URL
data_url = 'data:text/html,<html><head><title>Data URL Test</title></head><body><h1>Data URL Content</h1></body></html>'
@@ -199,7 +199,7 @@ class TestNavigateToUrlEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- result = await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ result = await tools.act(GoToUrlActionModel(**action_data), browser_session)
# Verify navigation
assert isinstance(result, ActionResult)
@@ -210,7 +210,7 @@ class TestNavigateToUrlEvent:
title = await page.title()
assert title == 'Data URL Test'
- async def test_navigate_with_hash(self, controller, browser_session, base_url, http_server):
+ async def test_navigate_with_hash(self, tools, browser_session, base_url, http_server):
"""Test navigating to URLs with hash fragments."""
# Add a page with anchors
http_server.expect_request('/page-with-anchors').respond_with_data(
@@ -236,7 +236,7 @@ class TestNavigateToUrlEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- result = await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ result = await tools.act(GoToUrlActionModel(**action_data), browser_session)
# Verify navigation
assert isinstance(result, ActionResult)
@@ -246,7 +246,7 @@ class TestNavigateToUrlEvent:
current_url = await browser_session.get_current_page_url()
assert '#section1' in current_url
- async def test_navigate_with_query_params(self, controller, browser_session, base_url, http_server):
+ async def test_navigate_with_query_params(self, tools, browser_session, base_url, http_server):
"""Test navigating to URLs with query parameters."""
# Add a page that shows query params
http_server.expect_request('/search').respond_with_data(
@@ -273,7 +273,7 @@ class TestNavigateToUrlEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- result = await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ result = await tools.act(GoToUrlActionModel(**action_data), browser_session)
# Verify navigation
assert isinstance(result, ActionResult)
@@ -284,7 +284,7 @@ class TestNavigateToUrlEvent:
assert 'q=test+query' in current_url or 'q=test%20query' in current_url
assert 'page=1' in current_url
- async def test_navigate_multiple_tabs(self, controller, browser_session, base_url):
+ async def test_navigate_multiple_tabs(self, tools, browser_session, base_url):
"""Test navigating in multiple tabs sequentially."""
# Navigate to first page in current tab
action1 = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1', new_tab=False)}
@@ -292,15 +292,15 @@ class TestNavigateToUrlEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**action1), browser_session)
+ await tools.act(GoToUrlActionModel(**action1), browser_session)
# Open second page in new tab
action2 = {'go_to_url': GoToUrlAction(url=f'{base_url}/page2', new_tab=True)}
- await controller.act(GoToUrlActionModel(**action2), browser_session)
+ await tools.act(GoToUrlActionModel(**action2), browser_session)
# Open home page in yet another new tab
action3 = {'go_to_url': GoToUrlAction(url=base_url, new_tab=True)}
- await controller.act(GoToUrlActionModel(**action3), browser_session)
+ await tools.act(GoToUrlActionModel(**action3), browser_session)
# Should have 3 tabs now
assert len(browser_session.tabs) == 3
@@ -309,7 +309,7 @@ class TestNavigateToUrlEvent:
current_url = await browser_session.get_current_page_url()
assert base_url in current_url and '/page' not in current_url
- async def test_navigate_timeout_handling(self, controller, browser_session):
+ async def test_navigate_timeout_handling(self, tools, browser_session):
"""Test that navigation timeouts are handled gracefully."""
# Try to navigate to a URL that will likely timeout
# Using a private IP that's unlikely to respond
@@ -321,12 +321,12 @@ class TestNavigateToUrlEvent:
go_to_url: GoToUrlAction | None = None
# This should complete without hanging indefinitely
- result = await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ result = await tools.act(GoToUrlActionModel(**action_data), browser_session)
# Should get a result (possibly with error)
assert isinstance(result, ActionResult)
- async def test_navigate_redirect(self, controller, browser_session, base_url, http_server):
+ async def test_navigate_redirect(self, tools, browser_session, base_url, http_server):
"""Test navigating to a URL that redirects."""
# Add a redirect endpoint
http_server.expect_request('/redirect').respond_with_data(
@@ -341,7 +341,7 @@ class TestNavigateToUrlEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- result = await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ result = await tools.act(GoToUrlActionModel(**action_data), browser_session)
# Verify navigation succeeded
assert isinstance(result, ActionResult)
diff --git a/tests/ci/test_browser_event_ScrollEvent.py b/tests/ci/test_browser_event_ScrollEvent.py
index 23c886ba1..fe2a1efc7 100644
--- a/tests/ci/test_browser_event_ScrollEvent.py
+++ b/tests/ci/test_browser_event_ScrollEvent.py
@@ -71,7 +71,7 @@ async def browser_session():
@pytest.fixture
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -79,7 +79,7 @@ def controller():
class TestScrollActions:
"""Test scroll-related actions and events."""
- async def test_scroll_actions(self, controller, browser_session, base_url, http_server):
+ async def test_scroll_actions(self, tools, browser_session, base_url, http_server):
"""Test basic scroll action functionality."""
# Navigate to scrollable page
@@ -88,7 +88,7 @@ class TestScrollActions:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Test 1: Basic page scroll down
scroll_action = {'scroll': ScrollAction(down=True, num_pages=1.0)}
@@ -96,7 +96,7 @@ class TestScrollActions:
class ScrollActionModel(ActionModel):
scroll: ScrollAction | None = None
- result = await controller.act(ScrollActionModel(**scroll_action), browser_session)
+ result = await tools.act(ScrollActionModel(**scroll_action), browser_session)
# Verify scroll down succeeded
assert isinstance(result, ActionResult)
@@ -108,7 +108,7 @@ class TestScrollActions:
# Test 2: Basic page scroll up
scroll_up_action = {'scroll': ScrollAction(down=False, num_pages=0.5)}
- result = await controller.act(ScrollActionModel(**scroll_up_action), browser_session)
+ result = await tools.act(ScrollActionModel(**scroll_up_action), browser_session)
assert isinstance(result, ActionResult)
assert result.error is None, f'Scroll up failed: {result.error}'
@@ -118,7 +118,7 @@ class TestScrollActions:
# Test 3: Test with invalid element index (should error)
invalid_scroll_action = {'scroll': ScrollAction(down=True, num_pages=1.0, frame_element_index=999)}
- result = await controller.act(ScrollActionModel(**invalid_scroll_action), browser_session)
+ result = await tools.act(ScrollActionModel(**invalid_scroll_action), browser_session)
# This should fail with error about element not found
assert isinstance(result, ActionResult)
diff --git a/tests/ci/test_browser_event_TypeTextEvent.py b/tests/ci/test_browser_event_TypeTextEvent.py
index fa3a952d6..67b3a1cb7 100644
--- a/tests/ci/test_browser_event_TypeTextEvent.py
+++ b/tests/ci/test_browser_event_TypeTextEvent.py
@@ -68,7 +68,7 @@ async def browser_session():
@pytest.fixture
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -76,7 +76,7 @@ def controller():
class TestTypeTextEvent:
"""Test TypeTextEvent and input_text action functionality."""
- async def test_input_text_action(self, controller, browser_session, base_url, http_server):
+ async def test_input_text_action(self, tools, browser_session, base_url, http_server):
"""Test that InputTextAction correctly inputs text into form fields."""
# Set up search form endpoint for this test
http_server.expect_request('/searchform').respond_with_data(
@@ -101,7 +101,7 @@ class TestTypeTextEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for page to load
await asyncio.sleep(0.5)
@@ -114,7 +114,7 @@ class TestTypeTextEvent:
# In a real test, you would get the actual index from the selector map
# For demonstration, we'll just use a hard-coded mock value
- # and check that the controller processes the action correctly
+ # and check that the tools processes the action correctly
mock_input_index = 1 # This would normally be determined dynamically
# Create input text action
@@ -124,8 +124,8 @@ class TestTypeTextEvent:
input_text: InputTextAction | None = None
# The actual input might fail if the page structure changes or in headless mode
- # So we'll just verify the controller correctly processes the action
- result = await controller.act(InputTextActionModel(**input_action), browser_session)
+ # So we'll just verify the tools correctly processes the action
+ result = await tools.act(InputTextActionModel(**input_action), browser_session)
# Verify the result is an ActionResult
assert isinstance(result, ActionResult)
diff --git a/tests/ci/test_browser_event_TypeTextEvent2.py b/tests/ci/test_browser_event_TypeTextEvent2.py
index fa3a952d6..67b3a1cb7 100644
--- a/tests/ci/test_browser_event_TypeTextEvent2.py
+++ b/tests/ci/test_browser_event_TypeTextEvent2.py
@@ -68,7 +68,7 @@ async def browser_session():
@pytest.fixture
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -76,7 +76,7 @@ def controller():
class TestTypeTextEvent:
"""Test TypeTextEvent and input_text action functionality."""
- async def test_input_text_action(self, controller, browser_session, base_url, http_server):
+ async def test_input_text_action(self, tools, browser_session, base_url, http_server):
"""Test that InputTextAction correctly inputs text into form fields."""
# Set up search form endpoint for this test
http_server.expect_request('/searchform').respond_with_data(
@@ -101,7 +101,7 @@ class TestTypeTextEvent:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for page to load
await asyncio.sleep(0.5)
@@ -114,7 +114,7 @@ class TestTypeTextEvent:
# In a real test, you would get the actual index from the selector map
# For demonstration, we'll just use a hard-coded mock value
- # and check that the controller processes the action correctly
+ # and check that the tools processes the action correctly
mock_input_index = 1 # This would normally be determined dynamically
# Create input text action
@@ -124,8 +124,8 @@ class TestTypeTextEvent:
input_text: InputTextAction | None = None
# The actual input might fail if the page structure changes or in headless mode
- # So we'll just verify the controller correctly processes the action
- result = await controller.act(InputTextActionModel(**input_action), browser_session)
+ # So we'll just verify the tools correctly processes the action
+ result = await tools.act(InputTextActionModel(**input_action), browser_session)
# Verify the result is an ActionResult
assert isinstance(result, ActionResult)
diff --git a/tests/ci/test_browser_session_element_cache.py b/tests/ci/test_browser_session_element_cache.py
index 0557ecb9d..c078c0f6a 100644
--- a/tests/ci/test_browser_session_element_cache.py
+++ b/tests/ci/test_browser_session_element_cache.py
@@ -74,8 +74,8 @@ async def browser_session():
@pytest.fixture
-def controller():
- """Create a controller instance."""
+def tools():
+ """Create a tools instance."""
return Tools()
@@ -125,7 +125,7 @@ async def test_assumption_2_cached_selector_map_persists(browser_session, httpse
@pytest.mark.asyncio
-async def test_assumption_3_action_gets_same_selector_map(browser_session, controller, httpserver):
+async def test_assumption_3_action_gets_same_selector_map(browser_session, tools, httpserver):
"""Test assumption 3: Action gets the same selector map as cached."""
# Go to a simple page
page = await browser_session.get_current_page()
@@ -141,7 +141,7 @@ async def test_assumption_3_action_gets_same_selector_map(browser_session, contr
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')
+ @tools.registry.action('Test: Check selector map')
async def test_check_selector_map(browser_session: BrowserSession):
from browser_use import ActionResult
@@ -152,7 +152,7 @@ async def test_assumption_3_action_gets_same_selector_map(browser_session, contr
)
# Execute the test action
- result = await controller.registry.execute_action('test_check_selector_map', {}, browser_session=browser_session)
+ result = await tools.registry.execute_action('test_check_selector_map', {}, browser_session=browser_session)
print(f'Action result: {result.extracted_content}')
@@ -161,7 +161,7 @@ async def test_assumption_3_action_gets_same_selector_map(browser_session, contr
@pytest.mark.asyncio
-async def test_assumption_4_click_action_specific_issue(browser_session, controller, httpserver):
+async def test_assumption_4_click_action_specific_issue(browser_session, tools, httpserver):
"""Test assumption 4: Specific issue with click_element_by_index action."""
# Go to a simple page
page = await browser_session.get_current_page()
@@ -177,7 +177,7 @@ async def test_assumption_4_click_action_specific_issue(browser_session, control
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')
+ @tools.registry.action('Test: Debug click logic')
async def test_debug_click_logic(index: int, browser_session: BrowserSession):
from browser_use import ActionResult
@@ -199,7 +199,7 @@ async def test_assumption_4_click_action_specific_issue(browser_session, control
)
# Test with index 0
- result = await controller.registry.execute_action('test_debug_click_logic', {'index': 0}, browser_session=browser_session)
+ result = await tools.registry.execute_action('test_debug_click_logic', {'index': 0}, browser_session=browser_session)
print(f'Debug click result: {result.extracted_content or result.error}')
@@ -273,7 +273,7 @@ async def test_assumption_6_page_changes_affect_selector_map(browser_session, ht
@pytest.mark.asyncio
-async def test_assumption_8_same_browser_session_instance(browser_session, controller, httpserver):
+async def test_assumption_8_same_browser_session_instance(browser_session, tools, httpserver):
"""Test assumption 8: Action gets the same browser_session instance."""
# Go to a simple page
page = await browser_session.get_current_page()
@@ -291,7 +291,7 @@ async def test_assumption_8_same_browser_session_instance(browser_session, contr
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')
+ @tools.registry.action('Test: Check browser session identity')
async def test_check_session_identity(browser_session: BrowserSession):
from browser_use import ActionResult
@@ -302,7 +302,7 @@ async def test_assumption_8_same_browser_session_instance(browser_session, contr
)
# Execute action
- result = await controller.registry.execute_action('test_check_session_identity', {}, browser_session=browser_session)
+ result = await tools.registry.execute_action('test_check_session_identity', {}, browser_session=browser_session)
print(f'3. Action result: {result.extracted_content}')
@@ -318,7 +318,7 @@ async def test_assumption_8_same_browser_session_instance(browser_session, contr
@pytest.mark.asyncio
-async def test_assumption_9_pydantic_private_attrs(browser_session, controller, httpserver):
+async def test_assumption_9_pydantic_private_attrs(browser_session, tools, httpserver):
"""Test assumption 9: Pydantic model validation affects private attributes."""
# Go to a simple page
page = await browser_session.get_current_page()
@@ -380,7 +380,7 @@ async def test_assumption_9_pydantic_private_attrs(browser_session, controller,
@pytest.mark.asyncio
-async def test_assumption_7_cache_gets_cleared(browser_session, controller, httpserver):
+async def test_assumption_7_cache_gets_cleared(browser_session, tools, httpserver):
"""Test assumption 7: Check if _cached_browser_state_summary gets cleared."""
# Go to a simple page
page = await browser_session.get_current_page()
@@ -401,7 +401,7 @@ async def test_assumption_7_cache_gets_cleared(browser_session, controller, http
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')
+ @tools.registry.action('Test: Check cache state no page')
async def test_check_cache_state_no_page(browser_session: BrowserSession):
from browser_use import ActionResult
@@ -415,7 +415,7 @@ async def test_assumption_7_cache_gets_cleared(browser_session, controller, http
)
# Create action that checks cache state (WITH page parameter)
- @controller.registry.action('Test: Check cache state with page')
+ @tools.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
@@ -429,14 +429,12 @@ async def test_assumption_7_cache_gets_cleared(browser_session, controller, http
)
# Test action WITHOUT page parameter
- result_no_page = await controller.registry.execute_action(
- 'test_check_cache_state_no_page', {}, browser_session=browser_session
- )
+ result_no_page = await tools.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(
+ result_with_page = await tools.registry.execute_action(
'test_check_cache_state_with_page', {}, browser_session=browser_session
)
@@ -447,7 +445,7 @@ async def test_assumption_7_cache_gets_cleared(browser_session, controller, http
@pytest.mark.asyncio
-async def test_final_real_click_with_debug(browser_session, controller, httpserver):
+async def test_final_real_click_with_debug(browser_session, tools, httpserver):
"""Final test: Try actual click with maximum debugging."""
# Go to a simple page
page = await browser_session.get_current_page()
@@ -469,9 +467,7 @@ async def test_final_real_click_with_debug(browser_session, controller, httpserv
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
- )
+ result = await tools.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}')
diff --git a/tests/ci/test_browser_session_tab_management.py b/tests/ci/test_browser_session_tab_management.py
index e7c45545a..5fef02050 100644
--- a/tests/ci/test_browser_session_tab_management.py
+++ b/tests/ci/test_browser_session_tab_management.py
@@ -84,7 +84,7 @@ async def browser_session(base_url):
@pytest.fixture(scope='module')
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -94,8 +94,8 @@ class TestTabManagement:
# Helper methods
- async def _execute_action(self, controller, browser_session: BrowserSession, action_data):
- """Generic helper to execute any action via the controller."""
+ async def _execute_action(self, tools, browser_session: BrowserSession, action_data):
+ """Generic helper to execute any action via the tools."""
# Dynamically create an appropriate ActionModel class
action_type = list(action_data.keys())[0]
action_value = action_data[action_type]
@@ -108,7 +108,7 @@ class TestTabManagement:
setattr(DynamicActionModel, action_type, type(action_value) | None)
# Execute the action
- result = await controller.act(DynamicActionModel(**action_data), browser_session)
+ result = await tools.act(DynamicActionModel(**action_data), browser_session)
# Give the browser a moment to process the action
await asyncio.sleep(0.5)
diff --git a/tests/ci/test_browser_watchdog_downloads_upload_full_circle.py b/tests/ci/test_browser_watchdog_downloads_upload_full_circle.py
index 94af342e5..0e5ca3b07 100644
--- a/tests/ci/test_browser_watchdog_downloads_upload_full_circle.py
+++ b/tests/ci/test_browser_watchdog_downloads_upload_full_circle.py
@@ -151,8 +151,8 @@ class TestDownloadUploadFullCircle:
await browser_session.start()
- # Create controller and file system
- controller = Tools()
+ # Create tools and file system
+ tools = Tools()
file_system = FileSystem(base_dir=tmpdir)
try:
@@ -162,7 +162,7 @@ class TestDownloadUploadFullCircle:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- result = await controller.act(
+ result = await tools.act(
GoToUrlActionModel(go_to_url=GoToUrlAction(url=f'{base_url}/download-page', new_tab=False)), browser_session
)
assert result.error is None, f'Navigation to download page failed: {result.error}'
@@ -187,7 +187,7 @@ class TestDownloadUploadFullCircle:
click_element_by_index: ClickElementAction | None = None
# Click the download link
- result = await controller.act(
+ result = await tools.act(
ClickActionModel(click_element_by_index=ClickElementAction(index=download_link_index)), browser_session
)
assert result.error is None, f'Click on download link failed: {result.error}'
@@ -224,7 +224,7 @@ class TestDownloadUploadFullCircle:
print(f'📑 Tabs before navigation: {len(tabs_before)} tabs')
for i, tab in enumerate(tabs_before):
print(f' Tab {i}: {tab.url}')
- result = await controller.act(
+ result = await tools.act(
GoToUrlActionModel(go_to_url=GoToUrlAction(url=f'{base_url}/upload-page', new_tab=True)), browser_session
)
assert result.error is None, f'Navigation to upload page failed: {result.error}'
@@ -266,7 +266,7 @@ class TestDownloadUploadFullCircle:
upload_file_to_element: UploadFileAction | None = None
# The downloaded file should be automatically available for upload
- result = await controller.act(
+ result = await tools.act(
UploadActionModel(upload_file_to_element=UploadFileAction(index=file_input_index, path=downloaded_file_path)),
browser_session,
available_file_paths=[], # Empty, but file is in downloaded_files
@@ -294,7 +294,7 @@ class TestDownloadUploadFullCircle:
assert submit_button_index is not None, 'Submit button not found'
# Click the submit button
- result = await controller.act(
+ result = await tools.act(
ClickActionModel(click_element_by_index=ClickElementAction(index=submit_button_index)), browser_session
)
assert result.error is None, f'Click on submit button failed: {result.error}'
diff --git a/tests/ci/test_llm_custom_structured_ouput.py b/tests/ci/test_llm_custom_structured_ouput.py
index 3e21e916a..92ef1b62c 100644
--- a/tests/ci/test_llm_custom_structured_ouput.py
+++ b/tests/ci/test_llm_custom_structured_ouput.py
@@ -11,9 +11,9 @@ from browser_use.tools.service import Tools
def test_optimized_schema():
"""Test the optimized schema generation and save to file."""
- # Create controller and get all registered actions
- controller = Tools()
- ActionModel = controller.registry.create_action_model()
+ # Create tools and get all registered actions
+ tools = Tools()
+ ActionModel = tools.registry.create_action_model()
# Create the agent output model with custom actions
agent_output_model = AgentOutput.type_with_custom_actions(ActionModel)
diff --git a/tests/ci/test_llm_schema_optimizer.py b/tests/ci/test_llm_schema_optimizer.py
index 14e1d5d52..5fc5e15a5 100644
--- a/tests/ci/test_llm_schema_optimizer.py
+++ b/tests/ci/test_llm_schema_optimizer.py
@@ -26,12 +26,12 @@ def test_optimizer_preserves_all_fields_in_structured_done_action():
This test specifically checks for a bug where fields were being lost
during the optimization process.
"""
- # 1. Setup a controller with a custom output model, simulating an Agent
+ # 1. Setup a tools with a custom output model, simulating an Agent
# being created with an `output_model_schema`.
- controller = Tools(output_model=ProductInfo)
+ tools = Tools(output_model=ProductInfo)
# 2. Get the dynamically created AgentOutput model, which includes all registered actions.
- ActionModel = controller.registry.create_action_model()
+ ActionModel = tools.registry.create_action_model()
agent_output_model = AgentOutput.type_with_custom_actions(ActionModel)
# 3. Run the schema optimizer on the agent's output model.
diff --git a/tests/ci/test_mcp_client.py b/tests/ci/test_mcp_client.py
index 6aa675285..92ab9b8d0 100644
--- a/tests/ci/test_mcp_client.py
+++ b/tests/ci/test_mcp_client.py
@@ -230,7 +230,7 @@ async def test_mcp_server_script():
async def test_mcp_client_basic_connection(test_mcp_server_script):
"""Test basic MCP client connection and tool discovery."""
- controller = Tools()
+ tools = Tools()
mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
@@ -246,11 +246,11 @@ async def test_mcp_client_basic_connection(test_mcp_server_script):
assert 'process_trace_update' in mcp_client._tools
assert 'process_array_data' in mcp_client._tools
- # Register tools to controller
- await mcp_client.register_to_controller(controller)
+ # Register tools to tools
+ await mcp_client.register_to_tools(tools)
# Verify tools are registered as actions
- actions = controller.registry.registry.actions
+ actions = tools.registry.registry.actions
assert 'count_to_n' in actions
assert 'echo_message' in actions
assert 'get_test_data' in actions
@@ -286,14 +286,14 @@ async def test_mcp_tools_with_agent(test_mcp_server_script, httpserver: HTTPServ
browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True, user_data_dir=None, keep_alive=True))
await browser_session.start()
- controller = Tools()
+ tools = Tools()
# Connect MCP client
mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
try:
await mcp_client.connect()
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
# Import create_mock_llm from conftest
from tests.ci.conftest import create_mock_llm
@@ -312,7 +312,7 @@ async def test_mcp_tools_with_agent(test_mcp_server_script, httpserver: HTTPServ
task=f"Go to {httpserver.url_for('/')} then use count_to_n to count to 3, and echo_message to say 'MCP works!'",
llm=mock_llm,
browser_session=browser_session,
- controller=controller,
+ tools=tools,
)
# Run agent
@@ -348,16 +348,16 @@ async def test_mcp_tools_with_agent(test_mcp_server_script, httpserver: HTTPServ
async def test_mcp_tool_parameter_validation(test_mcp_server_script):
"""Test that MCP tool parameters are properly validated."""
- controller = Tools()
+ tools = Tools()
mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
try:
await mcp_client.connect()
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
# Get the count_to_n action
- count_action = controller.registry.registry.actions['count_to_n']
+ count_action = tools.registry.registry.actions['count_to_n']
# Test with valid parameter
params = count_action.param_model(n=7)
@@ -373,7 +373,7 @@ async def test_mcp_tool_parameter_validation(test_mcp_server_script):
assert param_model.model_fields['n'].is_required()
# Test echo_message with optional parameter
- echo_action = controller.registry.registry.actions['echo_message']
+ echo_action = tools.registry.registry.actions['echo_message']
# With default prefix
params = echo_action.param_model(message='Test')
@@ -391,7 +391,7 @@ async def test_mcp_tool_parameter_validation(test_mcp_server_script):
async def test_mcp_client_prefix_and_filtering(test_mcp_server_script):
"""Test tool filtering and prefixing."""
- controller = Tools()
+ tools = Tools()
mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
@@ -399,10 +399,10 @@ async def test_mcp_client_prefix_and_filtering(test_mcp_server_script):
await mcp_client.connect()
# Register only specific tools with prefix
- await mcp_client.register_to_controller(controller, tool_filter=['count_to_n', 'echo_message'], prefix='mcp_')
+ await mcp_client.register_to_tools(tools, tool_filter=['count_to_n', 'echo_message'], prefix='mcp_')
# Verify registration
- actions = controller.registry.registry.actions
+ actions = tools.registry.registry.actions
assert 'mcp_count_to_n' in actions
assert 'mcp_echo_message' in actions
assert 'mcp_get_test_data' not in actions # Filtered out
@@ -420,19 +420,19 @@ async def test_mcp_client_prefix_and_filtering(test_mcp_server_script):
async def test_mcp_tool_error_handling(test_mcp_server_script):
"""Test error handling in MCP tools."""
- controller = Tools()
+ tools = Tools()
mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
try:
await mcp_client.connect()
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
# Disconnect to simulate connection loss
await mcp_client.disconnect()
# Try to use tool after disconnect
- echo_action = controller.registry.registry.actions['echo_message']
+ echo_action = tools.registry.registry.actions['echo_message']
params = echo_action.param_model(message='Test')
result: ActionResult = await echo_action.function(params=params)
@@ -446,17 +446,17 @@ async def test_mcp_tool_error_handling(test_mcp_server_script):
async def test_mcp_client_context_manager(test_mcp_server_script):
"""Test using MCP client as context manager."""
- controller = Tools()
+ tools = Tools()
# Use as context manager
async with MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script]) as mcp_client:
# Should auto-connect
assert mcp_client.session is not None
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
# Test tool works
- action = controller.registry.registry.actions['get_test_data']
+ action = tools.registry.registry.actions['get_test_data']
# get_test_data has no parameters
result = await action.function()
assert 'apple' in result.extracted_content
@@ -467,8 +467,8 @@ async def test_mcp_client_context_manager(test_mcp_server_script):
async def test_multiple_mcp_servers(test_mcp_server_script):
- """Test connecting multiple MCP servers to the same controller."""
- controller = Tools()
+ """Test connecting multiple MCP servers to the same tools."""
+ tools = Tools()
# First MCP server with prefix
mcp1 = MCPClient(server_name='server1', command=sys.executable, args=[test_mcp_server_script])
@@ -479,13 +479,13 @@ async def test_multiple_mcp_servers(test_mcp_server_script):
try:
# Connect and register both
await mcp1.connect()
- await mcp1.register_to_controller(controller, prefix='s1_')
+ await mcp1.register_to_tools(tools, prefix='s1_')
await mcp2.connect()
- await mcp2.register_to_controller(controller, prefix='s2_')
+ await mcp2.register_to_tools(tools, prefix='s2_')
# Verify both sets of tools are available
- actions = controller.registry.registry.actions
+ actions = tools.registry.registry.actions
assert 's1_count_to_n' in actions
assert 's2_count_to_n' in actions
@@ -512,16 +512,16 @@ async def test_multiple_mcp_servers(test_mcp_server_script):
async def test_mcp_result_formatting(test_mcp_server_script):
"""Test that different MCP result formats are handled correctly."""
- controller = Tools()
+ tools = Tools()
mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
try:
await mcp_client.connect()
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
# Test JSON result formatting
- action = controller.registry.registry.actions['get_test_data']
+ action = tools.registry.registry.actions['get_test_data']
result = await action.function()
# Should contain formatted JSON
@@ -550,7 +550,7 @@ async def test_agent_with_multiple_mcp_servers(test_mcp_server_script, httpserve
browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True, user_data_dir=None))
await browser_session.start()
- controller = Tools()
+ tools = Tools()
# Connect two MCP servers with different prefixes
mcp_server1 = MCPClient(server_name='math-server', command=sys.executable, args=[test_mcp_server_script])
@@ -559,10 +559,10 @@ async def test_agent_with_multiple_mcp_servers(test_mcp_server_script, httpserve
try:
# Connect and register both servers
await mcp_server1.connect()
- await mcp_server1.register_to_controller(controller, prefix='math_', tool_filter=['count_to_n'])
+ await mcp_server1.register_to_tools(tools, prefix='math_', tool_filter=['count_to_n'])
await mcp_server2.connect()
- await mcp_server2.register_to_controller(controller, prefix='data_', tool_filter=['echo_message', 'get_test_data'])
+ await mcp_server2.register_to_tools(tools, prefix='data_', tool_filter=['echo_message', 'get_test_data'])
# Import create_mock_llm from conftest
from tests.ci.conftest import create_mock_llm
@@ -582,7 +582,7 @@ async def test_agent_with_multiple_mcp_servers(test_mcp_server_script, httpserve
task=f'Go to {httpserver.url_for("/")}, use math_count_to_n to count to 5, then use data_echo_message and data_get_test_data',
llm=mock_llm,
browser_session=browser_session,
- controller=controller,
+ tools=tools,
extend_system_message="""You have access to tools from two MCP servers:
- math server: Provides math_count_to_n for counting
- data server: Provides data_echo_message for echoing and data_get_test_data for JSON data
@@ -635,16 +635,16 @@ Use tools from both servers to complete the task.""",
async def test_mcp_nested_object_parameters(test_mcp_server_script):
"""Test that MCP tools with nested object parameters are properly handled."""
- controller = Tools()
+ tools = Tools()
mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
try:
await mcp_client.connect()
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
# Get the process_trace_update action
- trace_action = controller.registry.registry.actions['process_trace_update']
+ trace_action = tools.registry.registry.actions['process_trace_update']
# Verify the parameter model has nested structure
param_model = trace_action.param_model
@@ -727,16 +727,16 @@ async def test_mcp_nested_object_parameters(test_mcp_server_script):
async def test_mcp_array_type_inference(test_mcp_server_script):
"""Test that MCP tools with array parameters have proper type inference."""
- controller = Tools()
+ tools = Tools()
mcp_client = MCPClient(server_name='test-server', command=sys.executable, args=[test_mcp_server_script])
try:
await mcp_client.connect()
- await mcp_client.register_to_controller(controller)
+ await mcp_client.register_to_tools(tools)
# Get the process_array_data action
- array_action = controller.registry.registry.actions['process_array_data']
+ array_action = tools.registry.registry.actions['process_array_data']
# Verify the parameter model has array types
param_model = array_action.param_model
diff --git a/tests/ci/test_mcp_server.py b/tests/ci/test_mcp_server.py
index 5db3270b4..82ad9bd5f 100644
--- a/tests/ci/test_mcp_server.py
+++ b/tests/ci/test_mcp_server.py
@@ -582,12 +582,12 @@ class TestMCPServerExtraction:
result = await server._extract_content('query')
assert result == 'Error: FileSystem not initialized'
- async def test_extract_content_no_controller(self, mock_llm):
- """Test extraction without controller."""
+ async def test_extract_content_no_tools(self, mock_llm):
+ """Test extraction without tools."""
server = BrowserUseServer()
await server._init_browser_session(headless=True, user_data_dir=None, keep_alive=False)
server.llm = mock_llm # Use mock LLM so we get past the LLM check
- server.controller = None
+ server.tools = None
result = await server._extract_content('query')
assert result == 'Error: Tools not initialized'
@@ -612,7 +612,7 @@ class TestMCPServerLifecycle:
# Verify no session initially
assert server.browser_session is None
- assert server.controller is None
+ assert server.tools is None
assert server.file_system is None
# Initialize session
@@ -620,7 +620,7 @@ class TestMCPServerLifecycle:
# Verify all components initialized
assert server.browser_session is not None
- assert server.controller is not None
+ assert server.tools is not None
assert server.file_system is not None
# Verify browser profile settings
@@ -662,7 +662,7 @@ class TestMCPServerLifecycle:
# Verify everything cleaned up
assert server.browser_session is None
- assert server.controller is None
+ assert server.tools is None
async def test_close_browser_no_session(self):
"""Test closing when no browser session."""
diff --git a/tests/ci/test_registry.py b/tests/ci/test_registry.py
index 43feab36a..263a7e627 100644
--- a/tests/ci/test_registry.py
+++ b/tests/ci/test_registry.py
@@ -505,7 +505,7 @@ class TestRegistryEdgeCases:
class TestExistingToolsActions:
- """Test that existing controller actions continue to work"""
+ """Test that existing tools actions continue to work"""
async def test_existing_action_models(self, registry, browser_session):
"""Test that existing action parameter models work correctly"""
@@ -954,7 +954,7 @@ class TestParamsModelArgsAndKwargs:
This test demonstrates the problem and our fix. The issue happens because:
- 1. In controller/service.py, we have:
+ 1. In tools/service.py, we have:
```python
@registry.action('Google Sheets: Select a specific cell or range of cells')
async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
diff --git a/tests/ci/test_registry_action_search_google.py b/tests/ci/test_registry_action_search_google.py
index 203d2aa76..3ab430711 100644
--- a/tests/ci/test_registry_action_search_google.py
+++ b/tests/ci/test_registry_action_search_google.py
@@ -20,8 +20,8 @@ async def browser_session():
async def test_search_google_creates_and_focuses_new_tab(browser_session: BrowserSession):
"""Test that search_google creates a new tab and properly switches focus to it."""
- # Create controller to get the search_google action
- controller = Tools()
+ # Create tools to get the search_google action
+ tools = Tools()
# Get initial browser state
initial_state_event = browser_session.event_bus.dispatch(BrowserStateRequestEvent(include_screenshot=False))
@@ -30,7 +30,7 @@ async def test_search_google_creates_and_focuses_new_tab(browser_session: Browse
initial_tabs_count = len(initial_state.tabs)
# Execute search_google action
- action_result = await controller.registry.execute_action(
+ action_result = await tools.registry.execute_action(
action_name='search_google',
params={'query': 'test search'},
browser_session=browser_session,
diff --git a/tests/ci/test_controller.py b/tests/ci/test_tools.py
similarity index 87%
rename from tests/ci/test_controller.py
rename to tests/ci/test_tools.py
index 36fe55c72..0d5de47b5 100644
--- a/tests/ci/test_controller.py
+++ b/tests/ci/test_tools.py
@@ -85,7 +85,7 @@ async def browser_session():
@pytest.fixture(scope='function')
-def controller():
+def tools():
"""Create and provide a Tools instance."""
return Tools()
@@ -93,7 +93,7 @@ def controller():
class TestToolsIntegration:
"""Integration tests for Tools using actual browser instances."""
- async def test_registry_actions(self, controller, browser_session):
+ async def test_registry_actions(self, tools, browser_session):
"""Test that the registry contains the expected default actions."""
# Check that common actions are registered
common_actions = [
@@ -109,18 +109,18 @@ class TestToolsIntegration:
]
for action in common_actions:
- assert action in controller.registry.registry.actions
- assert controller.registry.registry.actions[action].function is not None
- assert controller.registry.registry.actions[action].description is not None
+ assert action in tools.registry.registry.actions
+ assert tools.registry.registry.actions[action].function is not None
+ assert tools.registry.registry.actions[action].description is not None
- async def test_custom_action_registration(self, controller, browser_session, base_url):
+ async def test_custom_action_registration(self, tools, browser_session, base_url):
"""Test registering a custom action and executing it."""
# Define a custom action
class CustomParams(BaseModel):
text: str
- @controller.action('Test custom action', param_model=CustomParams)
+ @tools.action('Test custom action', param_model=CustomParams)
async def custom_action(params: CustomParams, browser_session):
page = await browser_session.get_current_page()
return ActionResult(extracted_content=f'Custom action executed with: {params.text} on {page.url}')
@@ -131,7 +131,7 @@ class TestToolsIntegration:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Create the custom action model
custom_action_data = {'custom_action': CustomParams(text='test_value')}
@@ -140,7 +140,7 @@ class TestToolsIntegration:
custom_action: CustomParams | None = None
# Execute the custom action
- result = await controller.act(CustomActionModel(**custom_action_data), browser_session)
+ result = await tools.act(CustomActionModel(**custom_action_data), browser_session)
# Verify the result
assert isinstance(result, ActionResult)
@@ -148,16 +148,16 @@ class TestToolsIntegration:
assert 'Custom action executed with: test_value on' in result.extracted_content
assert f'{base_url}/page1' in result.extracted_content
- async def test_wait_action(self, controller, browser_session):
+ async def test_wait_action(self, tools, browser_session):
"""Test that the wait action correctly waits for the specified duration."""
# verify that it's in the default action set
wait_action = None
- for action_name, action in controller.registry.registry.actions.items():
+ for action_name, action in tools.registry.registry.actions.items():
if 'wait' in action_name.lower() and 'seconds' in str(action.param_model.model_fields):
wait_action = action
break
- assert wait_action is not None, 'Could not find wait action in controller'
+ assert wait_action is not None, 'Could not find wait action in tools'
# Check that it has seconds parameter with default
assert 'seconds' in wait_action.param_model.model_fields
@@ -174,7 +174,7 @@ class TestToolsIntegration:
start_time = time.time()
# Execute wait action
- result = await controller.act(WaitActionModel(**wait_action), browser_session)
+ result = await tools.act(WaitActionModel(**wait_action), browser_session)
# Record end time
end_time = time.time()
@@ -195,7 +195,7 @@ class TestToolsIntegration:
start_time = time.time()
# Execute wait action
- result = await controller.act(WaitActionModel(**wait_action), browser_session)
+ result = await tools.act(WaitActionModel(**wait_action), browser_session)
# Record end time
end_time = time.time()
@@ -209,7 +209,7 @@ class TestToolsIntegration:
assert end_time - start_time <= 2.1 # Allow some timing margin
assert end_time - start_time >= 1.9 # Allow some timing margin
- async def test_go_back_action(self, controller, browser_session, base_url):
+ async def test_go_back_action(self, tools, browser_session, base_url):
"""Test that go_back action navigates to the previous page."""
# Navigate to first page
goto_action1 = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1', new_tab=False)}
@@ -217,7 +217,7 @@ class TestToolsIntegration:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action1), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action1), browser_session)
# Store the first page URL
page1 = await browser_session.get_current_page()
@@ -226,7 +226,7 @@ class TestToolsIntegration:
# Navigate to second page
goto_action2 = {'go_to_url': GoToUrlAction(url=f'{base_url}/page2', new_tab=False)}
- await controller.act(GoToUrlActionModel(**goto_action2), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action2), browser_session)
# Verify we're on the second page
page2 = await browser_session.get_current_page()
@@ -240,7 +240,7 @@ class TestToolsIntegration:
class GoBackActionModel(ActionModel):
go_back: NoParamsAction | None = None
- result = await controller.act(GoBackActionModel(**go_back_action), browser_session)
+ result = await tools.act(GoBackActionModel(**go_back_action), browser_session)
# Verify the result
assert isinstance(result, ActionResult)
@@ -258,7 +258,7 @@ class TestToolsIntegration:
# Try to verify we're back on the first page, but don't fail the test if not
assert f'{base_url}/page1' in final_url, f'Expected to return to page1 but got {final_url}'
- async def test_navigation_chain(self, controller, browser_session, base_url):
+ async def test_navigation_chain(self, tools, browser_session, base_url):
"""Test navigating through multiple pages and back through history."""
# Set up a chain of navigation: Home -> Page1 -> Page2
urls = [f'{base_url}/', f'{base_url}/page1', f'{base_url}/page2']
@@ -270,7 +270,7 @@ class TestToolsIntegration:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**action_data), browser_session)
+ await tools.act(GoToUrlActionModel(**action_data), browser_session)
# Verify current page
page = await browser_session.get_current_page()
@@ -283,14 +283,14 @@ class TestToolsIntegration:
class GoBackActionModel(ActionModel):
go_back: NoParamsAction | None = None
- await controller.act(GoBackActionModel(**go_back_action), browser_session)
+ await tools.act(GoBackActionModel(**go_back_action), browser_session)
await asyncio.sleep(1) # Wait for navigation to complete
page = await browser_session.get_current_page()
assert expected_url in page.url
# TODO: update to use TargetIDs / 4-char tab_id
- # async def test_concurrent_tab_operations(self, controller, browser_session, base_url):
+ # async def test_concurrent_tab_operations(self, tools, browser_session, base_url):
# """Test operations across multiple tabs."""
# # Create two tabs with different content
# urls = [f'{base_url}/page1', f'{base_url}/page2']
@@ -301,7 +301,7 @@ class TestToolsIntegration:
# class GoToUrlActionModel(ActionModel):
# go_to_url: GoToUrlAction | None = None
- # await controller.act(GoToUrlActionModel(**goto_action1), browser_session)
+ # await tools.act(GoToUrlActionModel(**goto_action1), browser_session)
# # Open second tab
# open_tab_action = {'go_to_url': GoToUrlAction(url=urls[1], new_tab=True)}
@@ -309,7 +309,7 @@ class TestToolsIntegration:
# class OpenTabActionModel(ActionModel):
# go_to_url: GoToUrlAction | None = None
- # await controller.act(OpenTabActionModel(**open_tab_action), browser_session)
+ # await tools.act(OpenTabActionModel(**open_tab_action), browser_session)
# # Verify we're on second tab
# page = await browser_session.get_current_page()
@@ -321,7 +321,7 @@ class TestToolsIntegration:
# class SwitchTabActionModel(ActionModel):
# switch_tab: SwitchTabAction | None = None
- # await controller.act(SwitchTabActionModel(**switch_tab_action), browser_session)
+ # await tools.act(SwitchTabActionModel(**switch_tab_action), browser_session)
# # Verify we're back on first tab
# page = await browser_session.get_current_page()
@@ -333,7 +333,7 @@ class TestToolsIntegration:
# class CloseTabActionModel(ActionModel):
# close_tab: CloseTabAction | None = None
- # await controller.act(CloseTabActionModel(**close_tab_action), browser_session)
+ # await tools.act(CloseTabActionModel(**close_tab_action), browser_session)
# # Verify tabs after close - AboutBlankWatchdog may create an animation tab
# tabs_info = await browser_session.get_tabs_info()
@@ -352,18 +352,18 @@ class TestToolsIntegration:
async def test_excluded_actions(self, browser_session):
"""Test that excluded actions are not registered."""
- # Create controller with excluded actions
- excluded_controller = Tools(exclude_actions=['search_google', 'scroll'])
+ # Create tools with excluded actions
+ excluded_tools = Tools(exclude_actions=['search_google', 'scroll'])
# Verify excluded actions are not in the registry
- assert 'search_google' not in excluded_controller.registry.registry.actions
- assert 'scroll' not in excluded_controller.registry.registry.actions
+ assert 'search_google' not in excluded_tools.registry.registry.actions
+ assert 'scroll' not in excluded_tools.registry.registry.actions
# But other actions are still there
- assert 'go_to_url' in excluded_controller.registry.registry.actions
- assert 'click_element_by_index' in excluded_controller.registry.registry.actions
+ assert 'go_to_url' in excluded_tools.registry.registry.actions
+ assert 'click_element_by_index' in excluded_tools.registry.registry.actions
- async def test_search_google_action(self, controller, browser_session, base_url):
+ async def test_search_google_action(self, tools, browser_session, base_url):
"""Test the search_google action."""
await browser_session.get_current_page()
@@ -374,7 +374,7 @@ class TestToolsIntegration:
class SearchGoogleActionModel(ActionModel):
search_google: SearchGoogleAction | None = None
- result = await controller.act(SearchGoogleActionModel(**search_action), browser_session)
+ result = await tools.act(SearchGoogleActionModel(**search_action), browser_session)
# Verify the result
assert isinstance(result, ActionResult)
@@ -385,7 +385,7 @@ class TestToolsIntegration:
page = await browser_session.get_current_page()
assert page.url is not None and 'Python' in page.url
- async def test_done_action(self, controller, browser_session, base_url):
+ async def test_done_action(self, tools, browser_session, base_url):
"""Test that DoneAction completes a task and reports success or failure."""
# Create a temporary directory for the file system
with tempfile.TemporaryDirectory() as temp_dir:
@@ -397,7 +397,7 @@ class TestToolsIntegration:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
success_done_message = 'Successfully completed task'
@@ -408,7 +408,7 @@ class TestToolsIntegration:
done: DoneAction | None = None
# Execute done action with file_system
- result = await controller.act(DoneActionModel(**done_action), browser_session, file_system=file_system)
+ result = await tools.act(DoneActionModel(**done_action), browser_session, file_system=file_system)
# Verify the result
assert isinstance(result, ActionResult)
@@ -424,7 +424,7 @@ class TestToolsIntegration:
failed_done_action = {'done': DoneAction(text=failed_done_message, success=False)}
# Execute failed done action with file_system
- result = await controller.act(DoneActionModel(**failed_done_action), browser_session, file_system=file_system)
+ result = await tools.act(DoneActionModel(**failed_done_action), browser_session, file_system=file_system)
# Verify the result
assert isinstance(result, ActionResult)
@@ -434,7 +434,7 @@ class TestToolsIntegration:
assert result.is_done is True
assert result.error is None
- async def test_send_keys_action(self, controller, browser_session, base_url, http_server):
+ async def test_send_keys_action(self, tools, browser_session, base_url, http_server):
"""Test SendKeysAction using a controlled local HTML file."""
# Set up keyboard test page for this test
http_server.expect_request('/keyboard').respond_with_data(
@@ -501,7 +501,7 @@ class TestToolsIntegration:
go_to_url: GoToUrlAction | None = None
# Execute navigation
- goto_result = await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ goto_result = await tools.act(GoToUrlActionModel(**goto_action), browser_session)
await asyncio.sleep(0.1)
# Verify navigation result
@@ -528,7 +528,7 @@ class TestToolsIntegration:
class SendKeysActionModel(ActionModel):
send_keys: SendKeysAction | None = None
- tab_result = await controller.act(SendKeysActionModel(**tab_keys_action), browser_session)
+ tab_result = await tools.act(SendKeysActionModel(**tab_keys_action), browser_session)
await asyncio.sleep(0.1)
# Verify Tab action result
@@ -549,7 +549,7 @@ class TestToolsIntegration:
# 2. Type text into the input
test_text = 'This is a test'
type_action = {'send_keys': SendKeysAction(keys=test_text)}
- type_result = await controller.act(SendKeysActionModel(**type_action), browser_session)
+ type_result = await tools.act(SendKeysActionModel(**type_action), browser_session)
await asyncio.sleep(0.1)
# Verify typing action result
@@ -570,7 +570,7 @@ class TestToolsIntegration:
# 3. Test Ctrl+A for select all
select_all_action = {'send_keys': SendKeysAction(keys='ControlOrMeta+a')}
- select_all_result = await controller.act(SendKeysActionModel(**select_all_action), browser_session)
+ select_all_result = await tools.act(SendKeysActionModel(**select_all_action), browser_session)
# Wait longer for selection to take effect
await asyncio.sleep(1.0)
@@ -596,7 +596,7 @@ class TestToolsIntegration:
assert 'Selection length:' in result_text
# 4. Test Tab to next field
- tab_result2 = await controller.act(SendKeysActionModel(**tab_keys_action), browser_session)
+ tab_result2 = await tools.act(SendKeysActionModel(**tab_keys_action), browser_session)
await asyncio.sleep(0.1)
# Verify second Tab action result
@@ -616,7 +616,7 @@ class TestToolsIntegration:
# 5. Type in the textarea
textarea_text = 'Testing multiline\ninput text'
textarea_action = {'send_keys': SendKeysAction(keys=textarea_text)}
- textarea_result = await controller.act(SendKeysActionModel(**textarea_action), browser_session)
+ textarea_result = await tools.act(SendKeysActionModel(**textarea_action), browser_session)
# Verify textarea typing action result
assert isinstance(textarea_result, ActionResult)
@@ -638,8 +638,8 @@ class TestToolsIntegration:
assert lines[1] == 'input text'
# Test that Tab cycles back to the first element if we tab again
- await controller.act(SendKeysActionModel(**tab_keys_action), browser_session)
- await controller.act(SendKeysActionModel(**tab_keys_action), browser_session)
+ await tools.act(SendKeysActionModel(**tab_keys_action), browser_session)
+ await tools.act(SendKeysActionModel(**tab_keys_action), browser_session)
active_element_id = await page.evaluate('() => document.activeElement.id')
assert active_element_id == 'textInput', 'Tab cycling through form elements failed'
@@ -648,7 +648,7 @@ class TestToolsIntegration:
input_value = await page.evaluate('() => document.getElementById("textInput").value')
assert input_value == test_text, "Input value shouldn't have changed after tabbing"
- async def test_get_dropdown_options(self, controller, browser_session, base_url, http_server):
+ async def test_get_dropdown_options(self, tools, browser_session, base_url, http_server):
"""Test that get_dropdown_options correctly retrieves options from a dropdown."""
# Add route for dropdown test page
http_server.expect_request('/dropdown1').respond_with_data(
@@ -678,7 +678,7 @@ class TestToolsIntegration:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for the page to load using CDP
cdp_session = browser_session.agent_focus
@@ -715,7 +715,7 @@ class TestToolsIntegration:
get_dropdown_options: dict[str, int]
# Execute the action with the dropdown index
- result = await controller.act(
+ result = await tools.act(
action=GetDropdownOptionsModel(get_dropdown_options={'index': dropdown_index}),
browser_session=browser_session,
)
@@ -772,7 +772,7 @@ class TestToolsIntegration:
f"Option at index {i} has wrong value: expected '{expected['value']}', got '{actual['value']}'"
)
- async def test_select_dropdown_option(self, controller, browser_session, base_url, http_server):
+ async def test_select_dropdown_option(self, tools, browser_session, base_url, http_server):
"""Test that select_dropdown_option correctly selects an option from a dropdown."""
# Add route for dropdown test page
http_server.expect_request('/dropdown2').respond_with_data(
@@ -802,7 +802,7 @@ class TestToolsIntegration:
class GoToUrlActionModel(ActionModel):
go_to_url: GoToUrlAction | None = None
- await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await tools.act(GoToUrlActionModel(**goto_action), browser_session)
# Wait for the page to load using CDP
cdp_session = browser_session.agent_focus
@@ -839,7 +839,7 @@ class TestToolsIntegration:
select_dropdown_option: dict
# Execute the action with the dropdown index
- result = await controller.act(
+ result = await tools.act(
SelectDropdownOptionModel(select_dropdown_option={'index': dropdown_index, 'text': 'Second Option'}),
browser_session,
)
diff --git a/tests/old/test_google_sheets_real.py b/tests/old/test_google_sheets_real.py
index 7733e0631..a9dbadaa4 100644
--- a/tests/old/test_google_sheets_real.py
+++ b/tests/old/test_google_sheets_real.py
@@ -1,7 +1,7 @@
"""
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.
+Uses the existing Google Sheets actions from the main tools.
"""
import asyncio
@@ -31,13 +31,13 @@ async def browser_session():
@pytest.fixture
-def controller():
- """Create a controller instance (Google Sheets actions are already registered)."""
+def tools():
+ """Create a tools instance (Google Sheets actions are already registered)."""
return Tools()
@pytest.mark.asyncio
-async def test_selector_map_basic(browser_session, controller):
+async def test_selector_map_basic(browser_session, tools):
"""Test that the selector map gets populated on a basic page."""
# Go to a simple page first
page = await browser_session.get_current_page()
@@ -56,7 +56,7 @@ async def test_selector_map_basic(browser_session, controller):
@pytest.mark.asyncio
-async def test_click_element_basic(browser_session, controller):
+async def test_click_element_basic(browser_session, tools):
"""Test basic click element action to verify registry works."""
# Go to a simple page
page = await browser_session.get_current_page()
@@ -75,7 +75,7 @@ async def test_click_element_basic(browser_session, controller):
first_index = list(selector_map.keys())[0]
print(f'Trying to click element index: {first_index}')
- result = await controller.registry.execute_action(
+ result = await tools.registry.execute_action(
'click_element_by_index', {'index': first_index}, browser_session=browser_session
)
@@ -91,10 +91,10 @@ async def test_click_element_basic(browser_session, controller):
@pytest.mark.asyncio
-async def test_google_sheets_open(browser_session, controller):
+async def test_google_sheets_open(browser_session, tools):
"""Test opening a Google Sheet using the existing action."""
# First check what actions are available
- available_actions = list(controller.registry.registry.actions.keys())
+ available_actions = list(tools.registry.registry.actions.keys())
# Google Sheets actions are registered with specific names
sheet_actions = [
@@ -110,10 +110,10 @@ async def test_google_sheets_open(browser_session, controller):
found_sheet_actions = [action for action in sheet_actions if action in available_actions]
if not found_sheet_actions:
- pytest.skip('No Google Sheets actions found in controller')
+ pytest.skip('No Google Sheets actions found in tools')
# First navigate to the Google Sheets URL
- result = await controller.registry.execute_action(
+ result = await tools.registry.execute_action(
'go_to_url', {'url': TEST_GOOGLE_SHEET_URL, 'new_tab': False}, browser_session=browser_session
)
@@ -126,18 +126,18 @@ async def test_google_sheets_open(browser_session, controller):
# Try to read the sheet contents
if 'read_sheet_contents' in available_actions:
- result = await controller.registry.execute_action('read_sheet_contents', {}, browser_session=browser_session)
+ result = await tools.registry.execute_action('read_sheet_contents', {}, browser_session=browser_session)
print(f'Read result: {result.extracted_content if result.extracted_content else "No content"}')
print(f'Read error: {result.error if result.error else "No error"}')
@pytest.mark.asyncio
-async def test_list_all_actions(browser_session, controller):
+async def test_list_all_actions(browser_session, tools):
"""Debug test to list all available actions."""
- available_actions = list(controller.registry.registry.actions.keys())
+ available_actions = list(tools.registry.registry.actions.keys())
print('All available actions:')
for action in sorted(available_actions):
print(f' - {action}')
- # Just verify the controller has some actions
+ # Just verify the tools has some actions
assert len(available_actions) > 0
diff --git a/tests/old/test_self_registered_actions.py b/tests/old/test_self_registered_actions.py
index 09cb88907..77094bad1 100644
--- a/tests/old/test_self_registered_actions.py
+++ b/tests/old/test_self_registered_actions.py
@@ -21,22 +21,22 @@ async def browser_session():
@pytest.fixture
-async def controller():
- """Initialize the controller with self-registered actions"""
- controller = Tools()
+async def tools():
+ """Initialize the tools with self-registered actions"""
+ tools = Tools()
# Define custom actions without Pydantic models
- @controller.action('Print a message')
+ @tools.action('Print a message')
def print_message(message: str):
print(f'Message: {message}')
return f'Printed message: {message}'
- @controller.action('Add two numbers')
+ @tools.action('Add two numbers')
def add_numbers(a: int, b: int):
result = a + b
return f'The sum is {result}'
- @controller.action('Concatenate strings')
+ @tools.action('Concatenate strings')
def concatenate_strings(str1: str, str2: str):
result = str1 + str2
return f'Concatenated string: {result}'
@@ -55,21 +55,21 @@ async def controller():
address: Address
# Add actions with Pydantic model arguments
- @controller.action('Process simple model', param_model=SimpleModel)
+ @tools.action('Process simple model', param_model=SimpleModel)
def process_simple_model(model: SimpleModel):
return f'Processed {model.name}, age {model.age}'
- @controller.action('Process nested model', param_model=NestedModel)
+ @tools.action('Process nested model', param_model=NestedModel)
def process_nested_model(model: NestedModel):
user_info = f'{model.user.name}, age {model.user.age}'
address_info = f'{model.address.street}, {model.address.city}'
return f'Processed user {user_info} at address {address_info}'
- @controller.action('Process multiple models')
+ @tools.action('Process multiple models')
def process_multiple_models(model1: SimpleModel, model2: Address):
return f'Processed {model1.name} living at {model2.street}, {model2.city}'
- yield controller
+ yield tools
@pytest.fixture
@@ -83,12 +83,12 @@ def llm():
# @pytest.mark.skip(reason="Skipping test for now")
-async def test_self_registered_actions_no_pydantic(llm, controller):
+async def test_self_registered_actions_no_pydantic(llm, tools):
"""Test self-registered actions with individual arguments"""
agent = Agent(
task="First, print the message 'Hello, World!'. Then, add 10 and 20. Next, concatenate 'foo' and 'bar'.",
llm=llm,
- controller=controller,
+ tools=tools,
)
history: AgentHistoryList = await agent.run(max_steps=10)
# Check that custom actions were executed
@@ -100,12 +100,12 @@ async def test_self_registered_actions_no_pydantic(llm, controller):
# @pytest.mark.skip(reason="Skipping test for now")
-async def test_mixed_arguments_actions(llm, controller):
+async def test_mixed_arguments_actions(llm, tools):
"""Test actions with mixed argument types"""
# Define another action during the test
# Test for async actions
- @controller.action('Calculate the area of a rectangle')
+ @tools.action('Calculate the area of a rectangle')
async def calculate_area(length: float, width: float):
area = length * width
return f'The area is {area}'
@@ -113,7 +113,7 @@ async def test_mixed_arguments_actions(llm, controller):
agent = Agent(
task='Calculate the area of a rectangle with length 5.5 and width 3.2.',
llm=llm,
- controller=controller,
+ tools=tools,
)
history = await agent.run(max_steps=5)
@@ -130,12 +130,12 @@ async def test_mixed_arguments_actions(llm, controller):
pytest.fail(f'{correct} not found in extracted content')
-async def test_pydantic_simple_model(llm, controller):
+async def test_pydantic_simple_model(llm, tools):
"""Test action with a simple Pydantic model argument"""
agent = Agent(
task="Process a simple model with name 'Alice' and age 30.",
llm=llm,
- controller=controller,
+ tools=tools,
)
history = await agent.run(max_steps=5)
@@ -151,12 +151,12 @@ async def test_pydantic_simple_model(llm, controller):
pytest.fail(f'{correct} not found in extracted content')
-async def test_pydantic_nested_model(llm, controller):
+async def test_pydantic_nested_model(llm, tools):
"""Test action with a nested Pydantic model argument"""
agent = Agent(
task="Process a nested model with user name 'Bob', age 25, living at '123 Maple St', 'Springfield'.",
llm=llm,
- controller=controller,
+ tools=tools,
)
history = await agent.run(max_steps=5)
diff --git a/tests/old/test_vision.py b/tests/old/test_vision.py
index 73c5d68b0..1d75fb847 100644
--- a/tests/old/test_vision.py
+++ b/tests/old/test_vision.py
@@ -17,21 +17,21 @@ from browser_use import Agent, AgentHistoryList, BrowserSession, Tools
from browser_use.llm import ChatOpenAI
llm = ChatOpenAI(model='gpt-4.1')
-controller = Tools()
+tools = Tools()
# use this test to ask the model questions about the page like
# which color do you see for bbox labels, list all with their label
# what's the smallest bboxes with labels and
[email protected](description='explain what you see on the screen and ask user for input')
[email protected](description='explain what you see on the screen and ask user for input')
async def explain_screen(text: str) -> str:
pprint(text)
answer = input('\nuser input next question: \n')
return answer
[email protected](description='done')
[email protected](description='done')
async def done(text: str) -> str:
# pprint(text)
return 'call explain_screen'
@@ -48,7 +48,7 @@ async def test_vision():
agent = Agent(
task='call explain_screen all the time the user asks you questions e.g. about the page like bbox which you see are labels - your task is to explain it and get the next question',
llm=llm,
- controller=controller,
+ tools=tools,
browser_session=browser_session,
)
history: AgentHistoryList = await agent.run(20)
diff --git a/tests/old/test_wait_for_element.py b/tests/old/test_wait_for_element.py
index 98a06f552..4264749af 100644
--- a/tests/old/test_wait_for_element.py
+++ b/tests/old/test_wait_for_element.py
@@ -20,9 +20,9 @@ from browser_use.browser import BrowserProfile, BrowserSession
# Load environment variables.
load_dotenv()
-# Initialize language model and controller.
+# Initialize language model and tools.
llm = ChatOpenAI(model='gpt-4.1')
-controller = Tools()
+tools = Tools()
@pytest.mark.skip(reason='this is for local testing only')
@@ -46,7 +46,7 @@ async def test_wait_for_element():
llm=llm,
browser_session=browser_session,
initial_actions=initial_actions,
- controller=controller,
+ tools=tools,
)
# Run the agent for a few steps to trigger navigation and then the wait action.
diff --git a/tests/scripts/debug_iframe_scrolling.py b/tests/scripts/debug_iframe_scrolling.py
index 245d072f8..e2914eac9 100644
--- a/tests/scripts/debug_iframe_scrolling.py
+++ b/tests/scripts/debug_iframe_scrolling.py
@@ -175,11 +175,11 @@ async def debug_iframe_scrolling():
# Navigate to the page first
from browser_use.tools.service import Tools
- controller = Tools()
+ tools = Tools()
# Create the action model for navigation
goto_action = ActionModel.model_validate_json(actions[0])
- await controller.act(goto_action, browser_session)
+ await tools.act(goto_action, browser_session)
await asyncio.sleep(2) # Wait for page to fully load
initial_state = await capture_dom_state('INITIAL (after page load)')
@@ -200,7 +200,7 @@ async def debug_iframe_scrolling():
# Hook into agent actions to capture state after each one
states = []
- original_act = controller.act
+ original_act = tools.act
async def wrapped_act(action, session):
result = await original_act(action, session)
@@ -218,7 +218,7 @@ async def debug_iframe_scrolling():
states.append(state)
return result
- controller.act = wrapped_act
+ tools.act = wrapped_act
# Run the agent with remaining actions
result = await agent.run()