Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
feat: added login cookie tracker for all the steps
Saurav Pandaea03f2dc4c31
diff --git a/eval/service.py b/eval/service.pyindex a29f95a46..3c2bd5bb6 100644--- a/eval/service.py+++ b/eval/service.py@@ -50,6 +50,7 @@ import signalimport sysimport threadingimport time+from pathlib import Pathfrom uuid import UUIDimport anyio@@ -79,6 +80,9 @@ _resource_monitor_task = None_resource_monitor_stop_event = None_graceful_shutdown_initiated = False+# Global tracking for login cookie monitoring+_login_cookie_tracker = {}+def get_system_resources():"""Get current system resource usage"""@@ -493,7 +497,6 @@ from dataclasses import dataclass, field# Define Stage enum and related classes for the pipelinefrom enum import Enum-from pathlib import Pathfrom typing import Anyimport requests@@ -1431,6 +1434,24 @@ async def run_agent_with_browser("Please remove the 'enable_memory' parameter.")+ # Set up login cookie monitoring if this is a login task+ is_login_task = hasattr(task, 'login_cookie') and task.login_cookie+ new_step_callback = None++ if is_login_task:+ logger.info(f'π Setting up login cookie monitoring for task {task.task_id}')++ async def login_cookie_step_callback(browser_state_summary, agent_output, step_number):+ """Callback to check login cookie after each step"""+ try:+ await check_login_cookie_at_step(+ browser_session=browser_session, task_id=task.task_id, login_cookie=task.login_cookie, step=step_number+ )+ except Exception as e:+ logger.warning(f'β Error checking login cookie at step {step_number}: {type(e).__name__}: {e}')++ new_step_callback = login_cookie_step_callback+agent = Agent(task=task.confirmed_task,llm=llm,@@ -1444,11 +1465,20 @@ async def run_agent_with_browser(use_thinking=use_thinking,source='eval_platform',calculate_cost=True,+ register_new_step_callback=new_step_callback,)+# get last messageawait agent.run(max_steps=max_steps)last_input_messages = agent.message_manager.last_input_messageslast_message = last_input_messages[-1].text++ # Save login cookie tracking if this was a login task+ if is_login_task:+ # Save tracking data to the task folder (will be created later in the pipeline)+ # For now, we'll save it when the task folder is available+ pass+return agent.state.history, last_message@@ -1469,6 +1499,9 @@ async def evaluate_task_with_login_cookie(login_cookie: str, task_folder: Path)"""Evaluate a login task by checking if the login_cookie is present in browser cookies.+ First checks step-by-step tracking to see if the cookie was found during execution.+ If not found in tracking, falls back to checking end-state cookies.+Args:login_cookie: String identifier that should appear in cookies if login was successfultask_folder: Path to the task result folder containing saved cookies@@ -1476,6 +1509,44 @@ async def evaluate_task_with_login_cookie(login_cookie: str, task_folder: Path)Returns:Dictionary containing evaluation results similar to Online_Mind2Web_eval format"""+ task_id = task_folder.name++ # First, check if we have step-by-step tracking data+ tracking_file = task_folder / 'login_cookie_tracking.json'+ if tracking_file.exists():+ try:+ async with await anyio.open_file(tracking_file) as f:+ tracking_data = json.loads(await f.read())++ if tracking_data.get('found', False):+ # Cookie was found during execution!+ step_found = tracking_data.get('step', 'unknown')+ match_type = tracking_data.get('match_type', 'unknown')+ cookie_name = tracking_data.get('cookie_name', 'unknown')++ success = True+ score = 1.0+ judgement = f"Automatic judgement: Login cookie '{login_cookie}' was found during step {step_found} ({match_type} match on '{cookie_name}')"+ error = None++ logger.info(+ f"β Cookie evaluation result from step tracking: success={success} for login_cookie='{login_cookie}'"+ )++ return {+ 'task_id': task_id,+ 'judgement': judgement,+ 'success': success,+ 'error': error,+ 'score': score,+ 'tracking_data': tracking_data,+ }+ except Exception as e:+ logger.warning(f'Failed to load login cookie tracking: {e}')++ # Fallback to end-state cookie checking (original behavior)+ logger.info(f'π No step-by-step tracking found for task {task_id}, falling back to end-state cookie checking')+# Look for cookies in saved_trajectories (saved by browser-use during shutdown)cookies_file = task_folder / 'cookies.json'storage_state_file = task_folder / 'storage_state.json'@@ -1504,10 +1575,10 @@ async def evaluate_task_with_login_cookie(login_cookie: str, task_folder: Path)if not cookies_data:return {- 'task_id': task_folder.name,- 'judgement': 'Automatic judgement: No cookies saved for evaluation',+ 'task_id': task_id,+ 'judgement': 'Automatic judgement: No cookies saved for evaluation and no step-by-step tracking','success': False,- 'error': 'No cookies file found for login task evaluation',+ 'error': 'No cookies file found for login task evaluation and no step-by-step tracking','score': 0.0,}@@ -1552,25 +1623,29 @@ async def evaluate_task_with_login_cookie(login_cookie: str, task_folder: Path)# Prepare evaluation resultif login_cookie_found:if is_exact_match:- judgement = f"Automatic judgement: Login cookie '{search_target}' was found as exact match in browser cookies"+ judgement = (+ f"Automatic judgement: Login cookie '{search_target}' was found as exact match in end-state browser cookies"+ )else:- judgement = f"Automatic judgement: Login cookie '{search_target}' was found in browser cookies"+ judgement = f"Automatic judgement: Login cookie '{search_target}' was found in end-state browser cookies"success = Truescore = 1.0error = Noneelse:if is_exact_match:- judgement = f"Automatic judgement: Login cookie '{search_target}' was NOT found as exact match in browser cookies"+ judgement = (+ f"Automatic judgement: Login cookie '{search_target}' was NOT found as exact match in end-state browser cookies"+ )else:- judgement = f"Automatic judgement: Login cookie '{search_target}' was NOT found in browser cookies"+ judgement = f"Automatic judgement: Login cookie '{search_target}' was NOT found in end-state browser cookies"success = Falsescore = 0.0error = None- logger.info(f"Cookie evaluation result: success={success} for login_cookie='{login_cookie}'")+ logger.info(f"Cookie evaluation result from end-state: success={success} for login_cookie='{login_cookie}'")return {- 'task_id': task_folder.name,+ 'task_id': task_id,'judgement': judgement,'success': success,'error': error,@@ -1780,6 +1855,16 @@ async def run_task_with_semaphore(task_result.stage_completed(Stage.RUN_AGENT)logger.info(f'Task {task.task_id}: Agent run completed in {agent_execution_time:.2f}s.')++ # Save login cookie tracking data if this was a login task+ if hasattr(task, 'login_cookie') and task.login_cookie:+ try:+ await save_login_cookie_tracking(task_folder, task.task_id)+ except Exception as e:+ logger.warning(+ f'Failed to save login cookie tracking for task {task.task_id}: {type(e).__name__}: {e}'+ )+# Send progress update for completed agent runsend_progress_update(convex_url, secret_key, run_id, task.task_id, 'agent_completed', 'active', github_workflow_url@@ -2526,6 +2611,104 @@ async def run_evaluation_pipeline()+async def check_login_cookie_at_step(browser_session, task_id: str, login_cookie: str, step: int) -> bool:+ """+ Check if login cookie is present at the current step.++ Args:+ browser_session: The browser session to check cookies from+ task_id: The task ID for tracking+ login_cookie: The cookie to search for+ step: Current step number++ Returns:+ bool: True if login cookie was found, False otherwise+ """+ global _login_cookie_tracker++ try:+ # Get current cookies from browser+ current_cookies = await browser_session.get_cookies()++ if not current_cookies:+ logger.debug(f'Task {task_id} Step {step}: No cookies found')+ return False++ # Check if this is an exact match requirement+ if login_cookie.startswith('EXACTMATCH '):+ exact_cookie_name = login_cookie[11:] # Remove "EXACTMATCH " prefix+ is_exact_match = True+ search_target = exact_cookie_name+ else:+ is_exact_match = False+ search_target = login_cookie++ # Check if login_cookie is present+ for cookie in current_cookies:+ cookie_name = cookie.get('name', '')+ cookie_value = cookie.get('value', '')++ if is_exact_match:+ if cookie_name == search_target:+ logger.info(f'β Task {task_id} Step {step}: Login cookie "{search_target}" found (exact match)')+ # Track that we found the cookie+ _login_cookie_tracker[task_id] = {+ 'found': True,+ 'step': step,+ 'cookie_name': cookie_name,+ 'match_type': 'exact',+ }+ return True+ else:+ if search_target in cookie_name or search_target in cookie_value:+ logger.info(f'β Task {task_id} Step {step}: Login cookie "{search_target}" found (substring match)')+ # Track that we found the cookie+ _login_cookie_tracker[task_id] = {+ 'found': True,+ 'step': step,+ 'cookie_name': cookie_name,+ 'match_type': 'substring',+ }+ return True++ logger.debug(f'Task {task_id} Step {step}: Login cookie "{search_target}" not found in {len(current_cookies)} cookies')+ return False++ except Exception as e:+ logger.warning(f'Task {task_id} Step {step}: Error checking login cookie: {type(e).__name__}: {e}')+ return False+++async def save_login_cookie_tracking(task_folder: Path, task_id: str) -> None:+ """+ Save the login cookie tracking information to a file.++ Args:+ task_folder: Directory to save the tracking file+ task_id: The task ID+ """+ global _login_cookie_tracker++ try:+ tracking_file = task_folder / 'login_cookie_tracking.json'+ tracking_data = _login_cookie_tracker.get(task_id, {'found': False})++ # Add timestamp+ tracking_data['timestamp'] = time.time()++ # Save to file+ async with await anyio.open_file(tracking_file, 'w') as f:+ await f.write(json.dumps(tracking_data, indent=2))++ logger.info(f'π Saved login cookie tracking for task {task_id}: {tracking_data}')++ # Clean up tracking data to avoid memory leaks+ _login_cookie_tracker.pop(task_id, None)++ except Exception as e:+ logger.warning(f'β Failed to save login cookie tracking for task {task_id}: {type(e).__name__}: {e}')++if __name__ == '__main__':parser = argparse.ArgumentParser(description='Run and evaluate browser automation tasks')parser.add_argument('--parallel-runs', type=int, default=3, help='Number of parallel tasks to run')