Skip to content

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

lint and hint fixes

Nick Sweeting3209fd95f769
diff --git a/eval/service.py b/eval/service.py
index a723e63c5..1789067e4 100644
--- a/eval/service.py
+++ b/eval/service.py
@@ -49,6 +49,7 @@ import signal
import sys
import threading
import time
+from uuid import UUID
import anyio
import psutil
@@ -1397,8 +1398,8 @@ def determine_current_stage(completed_stages: set) -> Stage:
async def run_task_with_semaphore(
task: Task,
run_id: str,
- lmnr_run_id: str,
- laminar_eval_link: str,
+ lmnr_run_id: str | None,
+ laminar_eval_link: str | None,
convex_url: str,
secret_key: str,
eval_model: BaseChatModel,
@@ -1441,7 +1442,7 @@ async def run_task_with_semaphore(
if lmnr_run_id:
try:
datapoint_id = await laminar_client.evals.create_datapoint(
- eval_id=lmnr_run_id,
+ eval_id=UUID(lmnr_run_id),
data={
'task_id': task.task_id,
'confirmed_task': task.confirmed_task,
@@ -1575,7 +1576,7 @@ async def run_task_with_semaphore(
if lmnr_run_id and datapoint_id:
await laminar_client.evals.update_datapoint(
- eval_id=lmnr_run_id,
+ eval_id=UUID(lmnr_run_id),
datapoint_id=datapoint_id,
scores={
'accuracy': evaluation['score'],
@@ -1591,7 +1592,9 @@ async def run_task_with_semaphore(
logger.info(f'Task {task.task_id}: Saving result to server.')
await run_stage(
Stage.SAVE_SERVER,
- lambda: asyncio.to_thread(save_result_to_server, convex_url, secret_key, task_result.server_payload),
+ lambda: asyncio.to_thread(
+ save_result_to_server, convex_url, secret_key, task_result.server_payload if task_result else {}
+ ),
timeout=60,
)
task_result.stage_completed(Stage.SAVE_SERVER)
@@ -1613,7 +1616,9 @@ async def run_task_with_semaphore(
logger.info(f'Task {task.task_id}: Attempting server save after timeout.')
await run_stage(
Stage.SAVE_SERVER,
- lambda: asyncio.to_thread(save_result_to_server, convex_url, secret_key, task_result.server_payload),
+ lambda: asyncio.to_thread(
+ save_result_to_server, convex_url, secret_key, task_result.server_payload if task_result else {}
+ ),
timeout=30, # Shorter timeout for emergency save
)
task_result.stage_completed(Stage.SAVE_SERVER)
@@ -1630,7 +1635,9 @@ async def run_task_with_semaphore(
logger.info(f'Task {task.task_id}: Attempting server save after cancellation.')
await run_stage(
Stage.SAVE_SERVER,
- lambda: asyncio.to_thread(save_result_to_server, convex_url, secret_key, task_result.server_payload),
+ lambda: asyncio.to_thread(
+ save_result_to_server, convex_url, secret_key, task_result.server_payload if task_result else {}
+ ),
timeout=30, # Shorter timeout for emergency save
)
task_result.stage_completed(Stage.SAVE_SERVER)
@@ -1647,7 +1654,9 @@ async def run_task_with_semaphore(
logger.info(f'Task {task.task_id}: Attempting server save after critical error.')
await run_stage(
Stage.SAVE_SERVER,
- lambda: asyncio.to_thread(save_result_to_server, convex_url, secret_key, task_result.server_payload),
+ lambda: asyncio.to_thread(
+ save_result_to_server, convex_url, secret_key, task_result.server_payload if task_result else {}
+ ),
timeout=30, # Shorter timeout for emergency save
)
task_result.stage_completed(Stage.SAVE_SERVER)
@@ -1677,7 +1686,9 @@ async def run_task_with_semaphore(
# Try emergency server save
try:
logger.info(f'Task {task.task_id}: Attempting emergency server save after initialization error.')
- await asyncio.to_thread(save_result_to_server, convex_url, secret_key, task_result.server_payload)
+ await asyncio.to_thread(
+ save_result_to_server, convex_url, secret_key, task_result.server_payload if task_result else {}
+ )
except Exception as save_e:
logger.error(f'Task {task.task_id}: Emergency server save after initialization error failed: {str(save_e)}')
@@ -1716,8 +1727,8 @@ async def run_multiple_tasks(
tasks: list[Task],
llm: BaseChatModel,
run_id: str,
- lmnr_run_id: str,
- laminar_eval_link: str,
+ lmnr_run_id: str | None,
+ laminar_eval_link: str | None,
convex_url: str,
secret_key: str,
eval_model: BaseChatModel,
@@ -1858,7 +1869,7 @@ async def run_multiple_tasks(
failed_tasks += 1
else:
processed_results.append(result)
- if result.get('success', False):
+ if isinstance(result, dict) and result.get('success', False):
successful_tasks += 1
else:
failed_tasks += 1
@@ -1959,7 +1970,7 @@ def get_git_info():
# Helper function to start a new run on the server
-def start_new_run(convex_url: str, secret_key: str, run_details: dict, existing_run_id: str = None):
+def start_new_run(convex_url: str, secret_key: str, run_details: dict, existing_run_id: str | None = None):
"""Sends a request to start a new evaluation run and returns the run ID."""
if not convex_url or not secret_key:
logger.error('Error: Convex URL or Secret Key not provided for starting run.')
diff --git a/examples/browser/window_sizing.py b/examples/browser/window_sizing.py
index 4eb679f25..3b48c9f5e 100644
--- a/examples/browser/window_sizing.py
+++ b/examples/browser/window_sizing.py
@@ -124,7 +124,11 @@ async def example_no_viewport_option():
def validate_window_size(configured: dict[str, Any], actual: dict[str, Any]) -> None:
- """Compare configured window size with actual size and report differences"""
+ """Compare configured window size with actual size and report differences.
+
+ Raises:
+ Exception: If the window size difference exceeds tolerance
+ """
# Allow for small differences due to browser chrome, scrollbars, etc.
width_diff = abs(configured['width'] - actual['width'])
height_diff = abs(configured['height'] - actual['height'])
@@ -139,6 +143,8 @@ def validate_window_size(configured: dict[str, Any], actual: dict[str, Any]) ->
else:
print('✅ Window size validation passed: actual size matches configured size within tolerance')
+ return None
+
async def main():
"""Run all window sizing examples"""
diff --git a/examples/features/custom_vector_store.py b/examples/features/custom_vector_store.py
index b6535ed71..77088bbfe 100644
--- a/examples/features/custom_vector_store.py
+++ b/examples/features/custom_vector_store.py
@@ -174,7 +174,7 @@ if __name__ == '__main__':
if sys.platform.startswith('win'):
# WindowsProactorEventLoopPolicy is only available on Windows
try:
- asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
+ asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) # type: ignore
except AttributeError:
pass # Not on Windows, ignore
asyncio.run(main())
diff --git a/examples/features/sensitive_data.py b/examples/features/sensitive_data.py
index 3924a612b..c38be553c 100644
--- a/examples/features/sensitive_data.py
+++ b/examples/features/sensitive_data.py
@@ -11,6 +11,7 @@ load_dotenv()
from langchain_openai import ChatOpenAI
from browser_use import Agent
+from browser_use.browser import BrowserProfile
# Initialize the model
llm = ChatOpenAI(
@@ -25,7 +26,8 @@ llm = ChatOpenAI(
company_credentials = {'company_username': '[email protected]', 'company_password': 'securePassword123'}
# Map the same credentials to multiple domains for secure access control
-sensitive_data = {
+# Type annotation to satisfy pyright
+sensitive_data: dict[str, str | dict[str, str]] = {
'https://example.com': company_credentials,
'https://admin.example.com': company_credentials,
'https://*.example-staging.com': company_credentials,
@@ -40,8 +42,10 @@ task = 'Go to example.com and login with company_username and company_password'
from browser_use.browser.session import BrowserSession
browser_session = BrowserSession(
- allowed_domains=list(sensitive_data.keys())
- + ['https://*.trusted-partner.com'] # Domain patterns from sensitive_data + additional allowed domains
+ browser_profile=BrowserProfile(
+ allowed_domains=list(sensitive_data.keys())
+ + ['https://*.trusted-partner.com'] # Domain patterns from sensitive_data + additional allowed domains
+ )
)
agent = Agent(task=task, llm=llm, sensitive_data=sensitive_data, browser_session=browser_session)
diff --git a/examples/integrations/browserbase_stagehand.py b/examples/integrations/browserbase_stagehand.py
index e05a12636..73764368d 100644
--- a/examples/integrations/browserbase_stagehand.py
+++ b/examples/integrations/browserbase_stagehand.py
@@ -1,3 +1,16 @@
+"""
+EXPERIMENTAL: Integration example with Stagehand (browserbase)
+
+This example shows how to combine browser-use with Stagehand for advanced browser automation.
+Note: This requires the stagehand-py library to be installed separately:
+ pip install stagehand-py
+
+The exact API may vary depending on the stagehand-py version.
+Please refer to the official Stagehand documentation for the latest usage:
+ https://pypi.org/project/stagehand-py/
+ https://github.com/browserbase/stagehand-python-examples/
+"""
+
import asyncio
import os
@@ -5,7 +18,7 @@ from dotenv import load_dotenv
load_dotenv()
-from stagehand import Stagehand, StagehandConfig
+from stagehand import Stagehand, StagehandConfig # type: ignore
from browser_use.agent.service import Agent
@@ -14,18 +27,14 @@ async def main():
# Configure Stagehand
# https://pypi.org/project/stagehand-py/
# https://github.com/browserbase/stagehand-python-examples/blob/main/agent_example.py
- config = StagehandConfig(
- env='BROWSERBASE',
- api_key=os.getenv('BROWSERBASE_API_KEY'),
- project_id=os.getenv('BROWSERBASE_PROJECT_ID'),
- headless=False,
- dom_settle_timeout_ms=3000,
- model_name='gpt-4o',
- self_heal=True,
- wait_for_captcha_solves=True,
- system_prompt='You are a browser automation assistant that helps users navigate websites effectively.',
- model_client_options={'model_api_key': os.getenv('OPENAI_API_KEY')},
- verbose=2,
+ # Note: This example requires the stagehand-py library to be installed
+ # pip install stagehand-py
+
+ # Create StagehandConfig with correct parameters
+ # The exact parameters depend on the stagehand-py version
+ config = StagehandConfig( # type: ignore
+ apiKey=os.getenv('BROWSERBASE_API_KEY'),
+ projectId=os.getenv('BROWSERBASE_PROJECT_ID'),
)
# Create a Stagehand client using the configuration object.
@@ -40,18 +49,21 @@ async def main():
print(f'\nCreated new session: {stagehand.session_id}')
print(f'🌐 View your live browser: https://www.browserbase.com/sessions/{stagehand.session_id}')
- await stagehand.page.goto('https://google.com/')
-
- await stagehand.page.act('search for openai')
+ # Check if stagehand has a page attribute
+ if hasattr(stagehand, 'page') and stagehand.page:
+ await stagehand.page.goto('https://google.com/')
+ await stagehand.page.act('search for openai')
+ else:
+ print('Warning: Stagehand page not available')
# Combine with Browser Use
- agent = Agent(task='click the first result', page=stagehand.page)
+ agent = Agent(task='click the first result', page=stagehand.page) # type: ignore
await agent.run()
# go back and forth
- await stagehand.page.act('open the 3 first links on the page in new tabs')
+ await stagehand.page.act('open the 3 first links on the page in new tabs') # type: ignore
- await Agent(task='click the first result', page=stagehand.page).run()
+ await Agent(task='click the first result', page=stagehand.page).run() # type: ignore
if __name__ == '__main__':
diff --git a/examples/integrations/discord/discord_api.py b/examples/integrations/discord/discord_api.py
index 676014c12..ba9484a2d 100644
--- a/examples/integrations/discord/discord_api.py
+++ b/examples/integrations/discord/discord_api.py
@@ -7,8 +7,8 @@ from dotenv import load_dotenv
load_dotenv()
-import discord
-from discord.ext import commands
+import discord # type: ignore
+from discord.ext import commands # type: ignore
from langchain_core.language_models.chat_models import BaseChatModel
from browser_use.agent.service import Agent
@@ -56,7 +56,7 @@ class DiscordBot(commands.Bot):
self.browser_profile = browser_profile
# Define intents.
- intents = discord.Intents.default()
+ intents = discord.Intents.default() # type: ignore
intents.message_content = True # Enable message content intent
intents.members = True # Enable members intent for user info
diff --git a/examples/integrations/slack/slack_api.py b/examples/integrations/slack/slack_api.py
index 06d045cc1..68cc1f7a4 100644
--- a/examples/integrations/slack/slack_api.py
+++ b/examples/integrations/slack/slack_api.py
@@ -11,9 +11,9 @@ load_dotenv()
from fastapi import Depends, FastAPI, HTTPException, Request
from langchain_core.language_models.chat_models import BaseChatModel
-from slack_sdk.errors import SlackApiError
-from slack_sdk.signature import SignatureVerifier
-from slack_sdk.web.async_client import AsyncWebClient
+from slack_sdk.errors import SlackApiError # type: ignore
+from slack_sdk.signature import SignatureVerifier # type: ignore
+from slack_sdk.web.async_client import AsyncWebClient # type: ignore
from browser_use.agent.service import Agent
from browser_use.browser import BrowserProfile, BrowserSession
diff --git a/examples/models/azure_openai.py b/examples/models/azure_openai.py
index 1e8da90b9..cb260997f 100644
--- a/examples/models/azure_openai.py
+++ b/examples/models/azure_openai.py
@@ -15,6 +15,7 @@ from dotenv import load_dotenv
load_dotenv()
from langchain_openai import AzureChatOpenAI
+from pydantic import SecretStr
from browser_use import Agent
@@ -28,7 +29,7 @@ if not azure_openai_api_key or not azure_openai_endpoint:
# Initialize the Azure OpenAI client
llm = AzureChatOpenAI(
model='gpt-4o',
- api_key=azure_openai_api_key,
+ api_key=SecretStr(azure_openai_api_key) if azure_openai_api_key else None,
azure_endpoint=azure_openai_endpoint, # Corrected to use azure_endpoint instead of openai_api_base
api_version='2024-08-01-preview', # Explicitly set the API version here
)
diff --git a/examples/models/bedrock_claude.py b/examples/models/bedrock_claude.py
index 468e60108..15a0869e6 100644
--- a/examples/models/bedrock_claude.py
+++ b/examples/models/bedrock_claude.py
@@ -17,9 +17,9 @@ from dotenv import load_dotenv
load_dotenv()
-import boto3
+import boto3 # type: ignore
from botocore.config import Config
-from langchain_aws import ChatBedrockConverse
+from langchain_aws import ChatBedrockConverse # type: ignore
from browser_use import Agent
from browser_use.browser import BrowserProfile, BrowserSession
diff --git a/examples/models/llama4-groq.py b/examples/models/llama4-groq.py
index dfcfc2691..a6bbe6095 100644
--- a/examples/models/llama4-groq.py
+++ b/examples/models/llama4-groq.py
@@ -9,13 +9,15 @@ from dotenv import load_dotenv
load_dotenv()
from langchain_openai import ChatOpenAI
+from pydantic import SecretStr
from browser_use import Agent
+groq_api_key = os.environ.get('GROQ_API_KEY')
llm = ChatOpenAI(
model='meta-llama/llama-4-maverick-17b-128e-instruct',
base_url='https://api.groq.com/openai/v1',
- api_key=os.environ.get('GROQ_API_KEY'),
+ api_key=SecretStr(groq_api_key) if groq_api_key else None,
temperature=0.0,
)
diff --git a/examples/ui/gradio_demo.py b/examples/ui/gradio_demo.py
index 9b4a86a76..d68c6416d 100644
--- a/examples/ui/gradio_demo.py
+++ b/examples/ui/gradio_demo.py
@@ -10,7 +10,7 @@ from dotenv import load_dotenv
load_dotenv()
# Third-party imports
-import gradio as gr
+import gradio as gr # type: ignore
from langchain_openai import ChatOpenAI
from rich.console import Console
from rich.panel import Panel
@@ -52,6 +52,8 @@ def parse_agent_history(history_str: str) -> None:
console.print(panel)
console.print()
+ return None
+
async def run_browser_task(
task: str,
@@ -70,8 +72,8 @@ async def run_browser_task(
llm=ChatOpenAI(model='gpt-4o'),
)
result = await agent.run()
- # TODO: The result cloud be parsed better
- return result
+ # TODO: The result could be parsed better
+ return str(result)
except Exception as e:
return f'Error: {str(e)}'
diff --git a/examples/ui/streamlit_demo.py b/examples/ui/streamlit_demo.py
index d18e11a11..aa0316a20 100644
--- a/examples/ui/streamlit_demo.py
+++ b/examples/ui/streamlit_demo.py
@@ -15,7 +15,7 @@ from dotenv import load_dotenv
load_dotenv()
-import streamlit as st
+import streamlit as st # type: ignore
from browser_use import Agent
from browser_use.browser import BrowserSession
@@ -48,6 +48,7 @@ def get_llm(provider: str):
else:
st.error(f'Unsupported provider: {provider}')
st.stop()
+ return None # Never reached, but helps with type checking
# Function to initialize the agent
@@ -58,7 +59,7 @@ def initialize_agent(query: str, provider: str):
return Agent(
task=query,
- llm=llm,
+ llm=llm, # type: ignore
controller=controller,
browser_session=browser_session,
use_vision=True,
diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.py
index c6a01b270..c63102f7e 100644
--- a/examples/use-cases/find_and_apply_to_jobs.py
+++ b/examples/use-cases/find_and_apply_to_jobs.py
@@ -20,7 +20,7 @@ load_dotenv()
from langchain_openai import AzureChatOpenAI
from pydantic import BaseModel, SecretStr
-from PyPDF2 import PdfReader
+from PyPDF2 import PdfReader # type: ignore
from browser_use import ActionResult, Agent, Controller
from browser_use.browser import BrowserProfile, BrowserSession
diff --git a/examples/use-cases/google_sheets.py b/examples/use-cases/google_sheets.py
index ac42d2031..5adf496c6 100644
--- a/examples/use-cases/google_sheets.py
+++ b/examples/use-cases/google_sheets.py
@@ -39,8 +39,8 @@ async def main():
browser_profile=BrowserProfile(
executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
user_data_dir='~/.config/browseruse/profiles/default',
+ keep_alive=True,
),
- keep_alive=True,
)
async with browser_session:
diff --git a/examples/use-cases/play_chess.py b/examples/use-cases/play_chess.py
index 598f74823..1e917e86c 100755
--- a/examples/use-cases/play_chess.py
+++ b/examples/use-cases/play_chess.py
@@ -64,7 +64,7 @@ def parse_transform(style: str) -> tuple[float, float] | None:
return x_px_str, y_px_str
except Exception as e:
logger.error(f'Error parsing transform style: {e}')
- return None, 0.0
+ return None
def algebraic_to_pixels(square: str, square_size: float) -> tuple[str, str]:
@@ -107,9 +107,12 @@ async def calculate_square_size(page) -> float | None:
raise ValueError('No pieces found.')
x_coords: set[float] = set()
for piece in pieces:
- style = piece.get('style')
+ if hasattr(piece, 'get'):
+ style = piece.get('style') # type: ignore
+ else:
+ continue
if style:
- coords = parse_transform(style)
+ coords = parse_transform(style) # type: ignore
if coords:
x_coords.add(coords[0])
@@ -151,7 +154,7 @@ def create_fen_board(board_state: dict) -> str:
return fen
-async def get_current_board_info(page) -> tuple[str | None, float]:
+async def get_current_board_info(page) -> tuple[str | None, float | None]:
"""Reads the current board HTML and returns FEN string and square size."""
board_state = {}
board_html = ''
@@ -164,29 +167,31 @@ async def get_current_board_info(page) -> tuple[str | None, float]:
square_size = await calculate_square_size(page)
except Exception as e:
logger.error(f'Error (get_info): Could not read cg-board: {e}')
- return None, 0.0
+ return None, None
if not board_html or not square_size:
- return None, 0.0
+ return None, None
soup = BeautifulSoup(board_html, 'html.parser')
pieces = soup.find_all('piece')
for piece in pieces:
- style = piece.get('style')
- class_ = piece.get('class')
+ if not hasattr(piece, 'get'):
+ continue
+ style = piece.get('style') # type: ignore
+ class_ = piece.get('class') # type: ignore
if style and class_:
- coords = parse_transform(style)
+ coords = parse_transform(style) # type: ignore
if coords:
x_px, y_px = coords
try:
square = pixels_to_algebraic(x_px, y_px, square_size)
- board_state[square] = get_piece_symbol(class_)
+ board_state[square] = get_piece_symbol(class_) # type: ignore
except ValueError as ve:
logger.error(f'Error: {ve}')
if not board_state or not square_size:
- return None, 0.0
+ return None, None
fen_board = create_fen_board(board_state)
full_fen = f'{fen_board} w KQkq - 0 1'
@@ -257,7 +262,7 @@ async def play_move(params: PlayMoveParams, browser: BrowserContext):
try:
current_fen, square_size = await get_current_board_info(page)
- if not current_fen or not square_size:
+ if not current_fen or square_size is None:
return ActionResult(extracted_content='Failed to get current FEN or square size to play move.')
board = chess.Board(current_fen)
diff --git a/examples/use-cases/post-twitter.py b/examples/use-cases/post-twitter.py
index e6ce42196..c57a55556 100644
--- a/examples/use-cases/post-twitter.py
+++ b/examples/use-cases/post-twitter.py
@@ -85,7 +85,7 @@ def create_twitter_agent(config: TwitterConfig) -> Agent:
full_message = f'@{config.target_user} {config.message}'
# Create the agent with detailed instructions
- return Agent(
+ agent = Agent(
task=f"""Navigate to Twitter and create a post and reply to a tweet.
Here are the specific steps:
@@ -111,6 +111,7 @@ def create_twitter_agent(config: TwitterConfig) -> Agent:
controller=controller,
browser_session=browser_session,
)
+ return agent
async def post_tweet(agent: Agent):
diff --git a/tests/ci/evaluate_tasks.py b/tests/ci/evaluate_tasks.py
index 53c4e46fd..24f70ddbe 100644
--- a/tests/ci/evaluate_tasks.py
+++ b/tests/ci/evaluate_tasks.py
@@ -141,7 +141,7 @@ Reply in JSON with keys: success (true/false), explanation (string).
If the agent provided no output, explain what might have gone wrong.
"""
structured_llm = judge_llm.with_structured_output(JudgeResponse)
- judge_response = await structured_llm.ainvoke(judge_prompt)
+ judge_response: JudgeResponse = await structured_llm.ainvoke(judge_prompt) # type: ignore[assignment]
result = {
'file': os.path.basename(task_file),
diff --git a/tests/ci/test_action_parameter_injection.py b/tests/ci/test_action_parameter_injection.py
index 1770c2a79..b67a57a6c 100644
--- a/tests/ci/test_action_parameter_injection.py
+++ b/tests/ci/test_action_parameter_injection.py
@@ -357,7 +357,7 @@ class TestBrowserContext:
assert 'simple_action' in action_model.model_fields
# Create an instance with the simple_action
- action_instance = action_model(simple_action={})
+ action_instance = action_model(simple_action={}) # type: ignore[call-arg]
# Test that model_dump works correctly
dumped = action_instance.model_dump(exclude_unset=True)
diff --git a/tests/ci/test_browser_session_downloads.py b/tests/ci/test_browser_session_downloads.py
index f7ea7e7a3..38125cac8 100644
--- a/tests/ci/test_browser_session_downloads.py
+++ b/tests/ci/test_browser_session_downloads.py
@@ -40,7 +40,7 @@ async def test_download_detection_timing(test_server, tmp_path):
browser_with_downloads = BrowserSession(
browser_profile=BrowserProfile(
headless=True,
- downloads_dir=str(tmp_path / 'downloads'),
+ downloads_path=str(tmp_path / 'downloads'),
user_data_dir=None,
)
)
@@ -77,7 +77,7 @@ async def test_download_detection_timing(test_server, tmp_path):
browser_no_downloads = BrowserSession(
browser_profile=BrowserProfile(
headless=True,
- downloads_dir=None,
+ downloads_path=None,
user_data_dir=None,
)
)
diff --git a/tests/ci/test_browser_session_element_cache.py b/tests/ci/test_browser_session_element_cache.py
index 04b199eab..b25a86372 100644
--- a/tests/ci/test_browser_session_element_cache.py
+++ b/tests/ci/test_browser_session_element_cache.py
@@ -356,7 +356,9 @@ async def test_assumption_9_pydantic_private_attrs(browser_session, controller,
# Check the browser_session that comes out of the model
extracted_browser_session = special_params.browser_session
print(f'5. Extracted browser_session ID: {id(extracted_browser_session)}')
- print(f'6. Extracted browser_session cache: {extracted_browser_session._cached_browser_state_summary is not None}')
+ print(
+ f'6. Extracted browser_session cache: {extracted_browser_session._cached_browser_state_summary is not None if extracted_browser_session else False}'
+ )
# Check if they're the same object
if id(browser_session) == id(extracted_browser_session):
@@ -367,11 +369,13 @@ async def test_assumption_9_pydantic_private_attrs(browser_session, controller,
# Check if private attributes were preserved
print(f'7. Original has _cached_browser_state_summary attr: {hasattr(browser_session, "_cached_browser_state_summary")}')
print(
- f'8. Extracted has _cached_browser_state_summary attr: {hasattr(extracted_browser_session, "_cached_browser_state_summary")}'
+ f'8. Extracted has _cached_browser_state_summary attr: {hasattr(extracted_browser_session, "_cached_browser_state_summary") if extracted_browser_session else False}'
)
if hasattr(extracted_browser_session, '_cached_browser_state_summary'):
- print(f'9. Extracted _cached_browser_state_summary value: {extracted_browser_session._cached_browser_state_summary}')
+ print(
+ f'9. Extracted _cached_browser_state_summary value: {extracted_browser_session._cached_browser_state_summary if extracted_browser_session else None}'
+ )
@pytest.mark.asyncio
@@ -401,7 +405,7 @@ async def test_assumption_7_cache_gets_cleared(browser_session, controller, http
from browser_use import ActionResult
cache_exists = browser_session._cached_browser_state_summary is not None
- if cache_exists:
+ if cache_exists and browser_session._cached_browser_state_summary:
cache_size = len(browser_session._cached_browser_state_summary.selector_map)
else:
cache_size = 0
@@ -415,7 +419,7 @@ async def test_assumption_7_cache_gets_cleared(browser_session, controller, http
from browser_use import ActionResult
cache_exists = browser_session._cached_browser_state_summary is not None
- if cache_exists:
+ if cache_exists and browser_session._cached_browser_state_summary:
cache_size = len(browser_session._cached_browser_state_summary.selector_map)
else:
cache_size = 0
diff --git a/tests/ci/test_browser_session_output_paths.py b/tests/ci/test_browser_session_output_paths.py
index 3c3670d90..c2854e711 100644
--- a/tests/ci/test_browser_session_output_paths.py
+++ b/tests/ci/test_browser_session_output_paths.py
@@ -217,13 +217,11 @@ class TestBrowserProfileRecordings:
video_dir = test_dir / f'videos_{context_type}_{alias}'
user_data_dir = None if context_type == 'incognito' else str(test_dir / 'user_data')
- # Create profile without the alias first
- browser_profile = BrowserProfile(headless=True, disable_security=True, user_data_dir=user_data_dir)
-
- # Set the appropriate alias dynamically
- setattr(browser_profile, alias, str(video_dir))
-
- browser_session = BrowserSession(browser_profile=browser_profile)
+ # Create profile with dynamic alias
+ profile_kwargs = {'headless': True, 'disable_security': True, 'user_data_dir': user_data_dir, alias: str(video_dir)}
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(**profile_kwargs) # type: ignore
+ )
await browser_session.start()
try:
await browser_session.navigate(httpserver_url)
@@ -259,13 +257,14 @@ class TestBrowserProfileRecordings:
har_path = test_dir / f'network_{context_type}_{alias}.har'
user_data_dir = None if context_type == 'incognito' else str(test_dir / f'user_data_har_{alias}')
- # Create profile without the alias first
- browser_profile = BrowserProfile(headless=True, disable_security=True, user_data_dir=user_data_dir)
-
- # Set the appropriate alias dynamically
- setattr(browser_profile, alias, str(har_path))
-
- browser_session = BrowserSession(browser_profile=browser_profile)
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ headless=True,
+ disable_security=True,
+ user_data_dir=user_data_dir,
+ **{alias: str(har_path)}, # type: ignore
+ )
+ )
await browser_session.start()
try:
await browser_session.navigate(httpserver_url)
@@ -312,7 +311,7 @@ class TestBrowserProfileRecordings:
if alias == 'trace_path':
browser_session.browser_profile.traces_dir = str(trace_dir)
else:
- setattr(browser_session.browser_profile, alias, str(trace_dir))
+ setattr(browser_session.browser_profile, alias, str(trace_dir)) # type: ignore
await browser_session.start()
try:
diff --git a/tests/ci/test_browser_session_tab_management.py b/tests/ci/test_browser_session_tab_management.py
index b721e89af..10ba87043 100644
--- a/tests/ci/test_browser_session_tab_management.py
+++ b/tests/ci/test_browser_session_tab_management.py
@@ -8,6 +8,7 @@ from pytest_httpserver import HTTPServer
load_dotenv()
from browser_use.agent.views import ActionModel
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.session import BrowserSession
from browser_use.controller.service import Controller
@@ -50,9 +51,11 @@ def base_url(http_server):
async def browser_session(base_url):
"""Create and provide a BrowserSession instance with a properly initialized tab."""
browser_session = BrowserSession(
- user_data_dir=None,
- headless=True,
- keep_alive=True,
+ browser_profile=BrowserProfile(
+ user_data_dir=None,
+ headless=True,
+ keep_alive=True,
+ )
)
await browser_session.start()
@@ -110,8 +113,9 @@ class TestTabManagement:
browser_session.agent_current_page = None
# close all existing tabs
- for page in browser_session.browser_context.pages:
- await page.close()
+ if browser_session.browser_context:
+ for page in browser_session.browser_context.pages:
+ await page.close()
await asyncio.sleep(0.5)
diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.py
index c802033a9..605df59a7 100644
--- a/tests/ci/test_controller.py
+++ b/tests/ci/test_controller.py
@@ -729,6 +729,10 @@ class TestControllerIntegration:
drag_action = {
'drag_drop': DragDropAction(
# Use the coordinate-based approach
+ element_source=None,
+ element_target=None,
+ element_source_offset=None,
+ element_target_offset=None,
coord_source_x=element_info['source']['x'],
coord_source_y=element_info['source']['y'],
coord_target_x=element_info['target']['x'],
@@ -839,7 +843,8 @@ class TestControllerIntegration:
# Verify navigation result
assert isinstance(goto_result, ActionResult)
- assert f'Navigated to {base_url}/keyboard' in goto_result.extracted_content
+ assert goto_result.extracted_content is not None
+ assert goto_result.extracted_content is not None and f'Navigated to {base_url}/keyboard' in goto_result.extracted_content
assert goto_result.error is None
assert goto_result.is_done is False
@@ -865,7 +870,8 @@ class TestControllerIntegration:
# Verify Tab action result
assert isinstance(tab_result, ActionResult)
- assert 'Sent keys: Tab' in tab_result.extracted_content
+ assert tab_result.extracted_content is not None
+ assert tab_result.extracted_content is not None and 'Sent keys: Tab' in tab_result.extracted_content
assert tab_result.error is None
assert tab_result.is_done is False
@@ -885,7 +891,8 @@ class TestControllerIntegration:
# Verify typing action result
assert isinstance(type_result, ActionResult)
- assert f'Sent keys: {test_text}' in type_result.extracted_content
+ assert type_result.extracted_content is not None
+ assert type_result.extracted_content is not None and f'Sent keys: {test_text}' in type_result.extracted_content
assert type_result.error is None
assert type_result.is_done is False
@@ -906,7 +913,11 @@ class TestControllerIntegration:
# Verify select all action result
assert isinstance(select_all_result, ActionResult)
- assert 'Sent keys: ControlOrMeta+a' in select_all_result.extracted_content
+ assert select_all_result.extracted_content is not None
+ assert (
+ select_all_result.extracted_content is not None
+ and 'Sent keys: ControlOrMeta+a' in select_all_result.extracted_content
+ )
assert select_all_result.error is None
# Verify selection length matches the text length
@@ -927,7 +938,8 @@ class TestControllerIntegration:
# Verify second Tab action result
assert isinstance(tab_result2, ActionResult)
- assert 'Sent keys: Tab' in tab_result2.extracted_content
+ assert tab_result2.extracted_content is not None
+ assert tab_result2.extracted_content is not None and 'Sent keys: Tab' in tab_result2.extracted_content
assert tab_result2.error is None
# Verify we moved to the textarea
@@ -945,7 +957,10 @@ class TestControllerIntegration:
# Verify textarea typing action result
assert isinstance(textarea_result, ActionResult)
- assert f'Sent keys: {textarea_text}' in textarea_result.extracted_content
+ assert textarea_result.extracted_content is not None
+ assert (
+ textarea_result.extracted_content is not None and f'Sent keys: {textarea_text}' in textarea_result.extracted_content
+ )
assert textarea_result.error is None
assert textarea_result.is_done is False
@@ -1237,14 +1252,18 @@ class TestControllerIntegration:
expected_result_text = 'Button 1 clicked'
# Verify the button text matches what we expect
- assert expected_button_text in button_text, f"Expected button text '{expected_button_text}' not found in '{button_text}'"
+ assert button_text is not None and expected_button_text in button_text, (
+ f"Expected button text '{expected_button_text}' not found in '{button_text}'"
+ )
# Create a model for the click_element_by_index action
class ClickElementActionModel(ActionModel):
click_element_by_index: ClickElementAction | None = None
# Execute the action with the button index
- result = await controller.act(ClickElementActionModel(click_element_by_index={'index': button_index}), browser_session)
+ result = await controller.act(
+ ClickElementActionModel(click_element_by_index=ClickElementAction(index=button_index)), browser_session
+ )
# Verify the result structure
assert isinstance(result, ActionResult), 'Result should be an ActionResult instance'
@@ -1255,9 +1274,10 @@ class TestControllerIntegration:
assert f'Clicked button with index {button_index}' in result.extracted_content, (
f'Expected click confirmation in result content, got: {result.extracted_content}'
)
- assert button_text in result.extracted_content, (
- f"Button text '{button_text}' not found in result content: {result.extracted_content}"
- )
+ if button_text:
+ assert result.extracted_content is not None and button_text in result.extracted_content, (
+ f"Button text '{button_text}' not found in result content: {result.extracted_content}"
+ )
# Verify the click actually had an effect on the page
result_text = await page.evaluate("document.getElementById('result').textContent")
diff --git a/tests/ci/test_registry.py b/tests/ci/test_registry.py
index c1480884d..3dcf2f1ca 100644
--- a/tests/ci/test_registry.py
+++ b/tests/ci/test_registry.py
@@ -122,6 +122,7 @@ class TestActionRegistryParameterPatterns:
result = await registry.execute_action('simple_action', {'text': 'hello', 'number': 42})
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Text: hello, Number: 42' in result.extracted_content
async def test_individual_parameters_with_browser(self, registry, browser_session, base_url):
@@ -139,6 +140,7 @@ class TestActionRegistryParameterPatterns:
result = await registry.execute_action('action_with_browser', {'text': 'hello'}, browser_session=browser_session)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Text: hello, URL:' in result.extracted_content
assert base_url in result.extracted_content
@@ -157,6 +159,7 @@ class TestActionRegistryParameterPatterns:
result = await registry.execute_action('action_with_page', {'text': 'hello'}, browser_session=browser_session)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Text: hello, Page Title: Test Page' in result.extracted_content
async def test_pydantic_model_with_page_parameter(self, registry, browser_session, base_url):
@@ -176,6 +179,7 @@ class TestActionRegistryParameterPatterns:
)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Text: test, Number: 100, Page Title: Test Page' in result.extracted_content
async def test_pydantic_model_parameters(self, registry, browser_session, base_url):
@@ -197,6 +201,7 @@ class TestActionRegistryParameterPatterns:
)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Text: test, Number: 100, Flag: True' in result.extracted_content
assert base_url in result.extracted_content
@@ -232,6 +237,7 @@ class TestActionRegistryParameterPatterns:
)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Text: hello' in result.extracted_content
assert base_url in result.extracted_content
# The mock LLM returns a JSON response
@@ -251,6 +257,7 @@ class TestActionRegistryParameterPatterns:
)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'No params action executed on' in result.extracted_content
assert '/test' in result.extracted_content
@@ -269,11 +276,13 @@ class TestActionRegistryParameterPatterns:
# Test legacy browser parameter
result1 = await registry.execute_action('legacy_browser_action', {'text': 'test1'}, browser_session=browser_session)
+ assert result1.extracted_content is not None
assert 'Legacy browser: test1, URL:' in result1.extracted_content
assert '/test' in result1.extracted_content
# Test legacy browser_context parameter
result2 = await registry.execute_action('legacy_context_action', {'text': 'test2'}, browser_session=browser_session)
+ assert result2.extracted_content is not None
assert 'Legacy context: test2, URL:' in result2.extracted_content
assert '/test' in result2.extracted_content
@@ -299,11 +308,13 @@ class TestActionRegistryParameterPatterns:
# Test direct page parameter
result1 = await registry.execute_action('direct_page_action', {'text': 'optimized'}, browser_session=browser_session)
+ assert result1.extracted_content is not None
assert 'Direct page: optimized, URL:' in result1.extracted_content
assert '/test' in result1.extracted_content
# Test browser_session parameter (should still work)
result2 = await registry.execute_action('browser_session_action', {'text': 'legacy'}, browser_session=browser_session)
+ assert result2.extracted_content is not None
assert 'Browser session: legacy, URL:' in result2.extracted_content
assert '/test' in result2.extracted_content
@@ -316,6 +327,7 @@ class TestActionRegistryParameterPatterns:
return ActionResult(extracted_content=f'Pydantic page: {params.message}, URL: {page.url}')
result3 = await registry.execute_action('pydantic_page_action', {'message': 'pydantic'}, browser_session=browser_session)
+ assert result3.extracted_content is not None
assert 'Pydantic page: pydantic, URL:' in result3.extracted_content
assert '/test' in result3.extracted_content
@@ -349,6 +361,7 @@ class TestActionToActionCalling:
result = await registry.execute_action('calling_action', {'message': 'test'}, browser_session=browser_session)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Called result: First: Helper processed: test on' in result.extracted_content
assert '/test' in result.extracted_content
@@ -376,13 +389,14 @@ class TestActionToActionCalling:
# Get the action's param model to call it properly
action = registry.registry.actions['select_cell_or_range_fixed']
params = action.param_model(cell_or_range=range_name)
- await select_cell_or_range_fixed(params=params, browser_session=browser_session)
+ await select_cell_or_range_fixed(cell_or_range=range_name, browser_session=browser_session)
return ActionResult(extracted_content=f'Updated range {range_name} with {new_contents}')
# Test the fixed version (should work)
result_fixed = await registry.execute_action(
'select_cell_or_range_fixed', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
)
+ assert result_fixed.extracted_content is not None
assert 'Selected cell A1:F100 on' in result_fixed.extracted_content
assert '/test' in result_fixed.extracted_content
@@ -390,6 +404,7 @@ class TestActionToActionCalling:
result_chain = await registry.execute_action(
'update_range_contents', {'range_name': 'B2:D4', 'new_contents': 'test data'}, browser_session=browser_session
)
+ assert result_chain.extracted_content is not None
assert 'Updated range B2:D4 with test data' in result_chain.extracted_content
# Test the problematic version (should work with enhanced registry)
@@ -397,6 +412,7 @@ class TestActionToActionCalling:
'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
)
# With the enhanced registry, this should succeed
+ assert result_problematic.extracted_content is not None
assert 'Selected cell A1:F100 on' in result_problematic.extracted_content
assert '/test' in result_problematic.extracted_content
@@ -428,6 +444,7 @@ class TestActionToActionCalling:
result = await registry.execute_action('top_action', {'original': 'test'}, browser_session=browser_session)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Top: Middle: Base: processed-enhanced-test on' in result.extracted_content
assert '/test' in result.extracted_content
@@ -447,11 +464,12 @@ class TestRegistryEdgeCases:
with pytest.raises(
TypeError, match='test_action\\(\\) does not accept positional arguments, only keyword arguments are allowed'
):
- await test_action(browser_session, 'A1:B2')
+ await test_action('A1:B2', browser_session)
# Test that calling with keyword arguments works
result = await test_action(browser_session=browser_session, cell_or_range='A1:B2')
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Selected cell A1:B2 on' in result.extracted_content
async def test_missing_required_browser_session(self, registry):
@@ -523,6 +541,7 @@ class TestRegistryEdgeCases:
result = await registry.execute_action('sync_action', {'text': 'test'}, browser_session=browser_session)
assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
assert 'Sync: test' in result.extracted_content
async def test_excluded_actions(self, browser_session):
@@ -548,6 +567,7 @@ class TestRegistryEdgeCases:
# Included action should work
result = await registry_with_exclusions.execute_action('included_action', {'text': 'test'})
+ assert result.extracted_content is not None
assert 'Should execute: test' in result.extracted_content
@@ -571,14 +591,17 @@ class TestExistingControllerActions:
# Test SearchGoogleAction
result1 = await registry.execute_action('test_search', {'query': 'python testing'}, browser_session=browser_session)
+ assert result1.extracted_content is not None
assert 'Searched for: python testing' in result1.extracted_content
# Test ClickElementAction
result2 = await registry.execute_action('test_click', {'index': 42}, browser_session=browser_session)
+ assert result2.extracted_content is not None
assert 'Clicked element: 42' in result2.extracted_content
# Test InputTextAction
result3 = await registry.execute_action('test_input', {'index': 5, 'text': 'test input'}, browser_session=browser_session)
+ assert result3.extracted_content is not None
assert 'Input text: test input at index: 5' in result3.extracted_content
async def test_pydantic_vs_individual_params_consistency(self, registry, browser_session):
@@ -606,7 +629,9 @@ class TestExistingControllerActions:
result2 = await registry.execute_action('pydantic_params_action', test_data, browser_session=browser_session)
# Both should extract the same content (just different prefixes)
+ assert result1.extracted_content is not None
assert 'hello-42' in result1.extracted_content
+ assert result2.extracted_content is not None
assert 'hello-42' in result2.extracted_content
assert 'Individual:' in result1.extracted_content
assert 'Pydantic:' in result2.extracted_content
@@ -686,7 +711,7 @@ class TestType2Pattern:
registry = Registry()
@registry.action('Scroll page')
- async def scroll_page(direction: str = 'down', amount: int = 100, browser_session: BrowserSession = None):
+ async def scroll_page(direction: str = 'down', amount: int = 100, browser_session: BrowserSession | None = None):
return ActionResult(extracted_content=f'Scrolled {direction} by {amount}')
action = registry.registry.actions['scroll_page']
@@ -850,7 +875,11 @@ class TestParamsModelGeneration:
@registry.action('Complex action')
async def complex_action(
- query: str, max_results: int, include_images: bool = True, page: Page = None, browser_session: BrowserSession = None
+ query: str,
+ max_results: int,
+ include_images: bool = True,
+ page: Page | None = None,
+ browser_session: BrowserSession | None = None,
):
return ActionResult()
@@ -872,7 +901,7 @@ class TestParamsModelGeneration:
@registry.action('Typed action')
async def typed_action(
- count: int, rate: float, enabled: bool, name: str | None = None, browser_session: BrowserSession = None
+ count: int, rate: float, enabled: bool, name: str | None = None, browser_session: BrowserSession | None = None
):
return ActionResult()
@@ -941,7 +970,7 @@ class TestParameterOrdering:
second: int,
page: Page,
third: bool = True,
- page_extraction_llm: BaseChatModel = None,
+ page_extraction_llm: BaseChatModel | None = None,
):
return ActionResult()
@@ -1009,6 +1038,7 @@ class TestParameterOrdering:
# Should retry once and succeed
result = await registry.execute_action('flaky_action', {'value': 'test'}, browser_session=browser_session)
+ assert result.extracted_content is not None
assert 'Success on attempt 2' in result.extracted_content
assert call_count == 2
@@ -1073,7 +1103,7 @@ class TestParamsModelArgsAndKwargs:
# Model that includes browser_session
class ModelWithBrowser(ActionModel):
value: str = Field(description='Test value')
- browser_session: BrowserSession = None
+ browser_session: BrowserSession | None = None
# Create a custom param model for select_cell_or_range
class CellRangeParams(ActionModel):
@@ -1139,7 +1169,9 @@ class TestParamsModelArgsAndKwargs:
# logger.info('\n--- Testing original problematic version ---')
try:
result1 = await registry.execute_action(
- 'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
+ 'select_cell_or_range',
+ {'cell_or_range': 'A1:F100'},
+ browser_session=browser_session, # type: ignore
)
# logger.info(f'Success! Result: {result1}')
except Exception as e:
@@ -1149,7 +1181,9 @@ class TestParamsModelArgsAndKwargs:
# logger.info('\n--- Testing fixed version (positional args) ---')
try:
result2 = await registry.execute_action(
- 'select_cell_or_range_fixed', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
+ 'select_cell_or_range_fixed',
+ {'cell_or_range': 'A1:F100'},
+ browser_session=browser_session, # type: ignore
)
# logger.info(f'Success! Result: {result2}')
except Exception as e:
@@ -1159,7 +1193,9 @@ class TestParamsModelArgsAndKwargs:
# logger.info('\n--- Testing kwargs simulation version ---')
try:
result3 = await registry.execute_action(
- 'select_with_kwargs', {'cell_or_range': 'A1:F100'}, browser_session=browser_session
+ 'select_with_kwargs',
+ {'cell_or_range': 'A1:F100'},
+ browser_session=browser_session, # type: ignore
)
# logger.info(f'Success! Result: {result3}')
except Exception as e:
diff --git a/tests/ci/test_sync_client.py b/tests/ci/test_sync_client.py
index aacbf992d..308ac6927 100644
--- a/tests/ci/test_sync_client.py
+++ b/tests/ci/test_sync_client.py
@@ -95,7 +95,14 @@ class TestCloudSyncEventHandling:
# Send event
await authenticated_sync.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Test task', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Test task',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -119,7 +126,14 @@ class TestCloudSyncEventHandling:
# Send event
await unauthenticated_sync.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Queued task', user_id=TEMP_USER_ID
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Queued task',
+ user_id=TEMP_USER_ID,
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -145,7 +159,14 @@ class TestCloudSyncEventHandling:
# Send event without user_id
await unauthenticated_sync.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Pre-auth task', user_id=TEMP_USER_ID
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Pre-auth task',
+ user_id=TEMP_USER_ID,
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -186,10 +207,24 @@ class TestCloudSyncRetryLogic:
sync_with_auth.pending_events.extend(
[
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Pending task 1', user_id=TEMP_USER_ID
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Pending task 1',
+ user_id=TEMP_USER_ID,
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
),
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Pending task 2', user_id=TEMP_USER_ID
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Pending task 2',
+ user_id=TEMP_USER_ID,
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
),
]
)
@@ -215,7 +250,14 @@ class TestCloudSyncRetryLogic:
# Should not raise exception
await sync_with_auth.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Task during outage', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Task during outage',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -230,7 +272,14 @@ class TestCloudSyncRetryLogic:
# Should not raise exception
await sync_with_auth.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Task during network error', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Task during network error',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -255,7 +304,14 @@ class TestCloudSyncRetryLogic:
for i in range(5):
task = sync_with_auth.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task=f'Concurrent task {i}', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task=f'Concurrent task {i}',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
tasks.append(task)
@@ -310,7 +366,14 @@ class TestCloudSyncBackendCommunication:
await service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Format validation test', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Format validation test',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -343,7 +406,14 @@ class TestCloudSyncBackendCommunication:
await service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Auth header test', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Auth header test',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -358,7 +428,16 @@ class TestCloudSyncBackendCommunication:
service.auth_client = DeviceAuthClient(base_url=httpserver.url_for('')) # No credentials
await service.handle_event(
- CreateAgentTaskEvent(agent_session_id='test-session', llm_model='test-model', task='No auth test', user_id='')
+ CreateAgentTaskEvent(
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='No auth test',
+ user_id='',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
+ )
)
# Check no auth header
@@ -383,7 +462,14 @@ class TestCloudSyncErrorHandling:
# Should not raise exception
await sync_service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Timeout test', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Timeout test',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -417,6 +503,10 @@ class TestCloudSyncErrorHandling:
llm_model='test-model',
task=f'Error {status_code} test',
user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -428,7 +518,14 @@ class TestCloudSyncErrorHandling:
# Should not raise exception
await sync_service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Invalid response test', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Invalid response test',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -480,6 +577,10 @@ class TestCloudSyncErrorHandling:
llm_model='test-model',
task=f'Concurrent error test {i}',
user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
tasks.append(task)
diff --git a/tests/ci/test_sync_client_auth.py b/tests/ci/test_sync_client_auth.py
index 876e6e0af..d62a30354 100644
--- a/tests/ci/test_sync_client_auth.py
+++ b/tests/ci/test_sync_client_auth.py
@@ -357,7 +357,14 @@ class TestCloudSync:
# Send event
await service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Test task', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Test task',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -375,7 +382,6 @@ class TestCloudSync:
assert event['event_type'] == 'CreateAgentTaskEvent'
assert event['user_id'] == 'test-user-123'
assert event['task'] == 'Test task'
- assert event['status'] == 'running'
async def test_send_event_pre_auth(self, httpserver: HTTPServer, temp_config_dir):
"""Test sending event before authentication."""
@@ -404,7 +410,16 @@ class TestCloudSync:
# Send event
await service.handle_event(
- CreateAgentTaskEvent(agent_session_id='test-session', llm_model='test-model', task='Test task', user_id=TEMP_USER_ID)
+ CreateAgentTaskEvent(
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Test task',
+ user_id=TEMP_USER_ID,
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
+ )
)
# Check request was made without auth header
@@ -458,14 +473,21 @@ class TestCloudSync:
# Send pre-auth event (should get 401 and be queued)
await service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Pre-auth task', user_id=TEMP_USER_ID
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Pre-auth task',
+ user_id=TEMP_USER_ID,
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
# Event should be in pending_events since we got 401
assert len(service.pending_events) == 1
- assert service.pending_events[0].task == 'Pre-auth task'
- assert service.pending_events[0].user_id == TEMP_USER_ID
+ assert hasattr(service.pending_events[0], 'task') and service.pending_events[0].task == 'Pre-auth task' # type: ignore
+ assert hasattr(service.pending_events[0], 'user_id') and service.pending_events[0].user_id == TEMP_USER_ID # type: ignore
# Now authenticate the auth client
auth.auth_config.api_token = 'test-api-key'
@@ -505,7 +527,14 @@ class TestCloudSync:
# Send event - should not raise exception but handle gracefully
await service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Test task', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Test task',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -656,6 +685,7 @@ class TestIntegration:
# Authenticate
authenticated = await service.authenticate(show_instructions=False)
assert authenticated is True
+ assert service.auth_client is not None
assert service.auth_client.is_authenticated
assert service.auth_client.api_token == 'test-api-key'
assert service.auth_client.user_id == 'test-user-123'
@@ -663,7 +693,14 @@ class TestIntegration:
# Send authenticated event
await service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Authenticated task', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Authenticated task',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -733,6 +770,10 @@ class TestAuthResilience:
llm_model='test-model',
task='Test task after token expiry',
user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -768,7 +809,14 @@ class TestAuthResilience:
# Should be able to send events without auth (pre-auth mode)
await service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task='Test task without auth', user_id=''
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task='Test task without auth',
+ user_id='',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -795,6 +843,10 @@ class TestAuthResilience:
llm_model='test-model',
task='Test task during server downtime',
user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -811,7 +863,14 @@ class TestAuthResilience:
for i in range(100):
await service.handle_event(
CreateAgentTaskEvent(
- agent_session_id='test-session', llm_model='test-model', task=f'Test task {i}', user_id='test-user-123'
+ agent_session_id='test-session',
+ llm_model='test-model',
+ task=f'Test task {i}',
+ user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)
@@ -852,5 +911,9 @@ class TestAuthResilience:
llm_model='test-model',
task='Test task with malformed response',
user_id='test-user-123',
+ done_output=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
)