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
refactor ctrl-c handling to separate class
Nick Sweetingad3080353b7d
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 6ccb37acc..6c65e4820 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -5,14 +5,8 @@ import gcimport inspectimport jsonimport logging-import osimport re-import signal-import sysimport time--# Global flag to prevent duplicate exit messages-_exiting = Falsefrom pathlib import Pathfrom typing import Any, Awaitable, Callable, Dict, Generic, List, Optional, TypeVar, Union@@ -65,9 +59,6 @@ from browser_use.utils import check_env_variables, time_execution_async, time_exload_dotenv()logger = logging.getLogger(__name__)-# Global flag to prevent duplicate exit messages-_exiting = False-def log_response(response: AgentOutput) -> None:"""Utility function to log the model's response."""@@ -86,61 +77,6 @@ def log_response(response: AgentOutput) -> None:logger.info(f'๐ ๏ธ Action {i + 1}/{len(response.action)}: {action.model_dump_json(exclude_unset=True)}')-def sigint_handler(loop: asyncio.AbstractEventLoop, agent=None):- """SIGINT (Ctrl+C) handler.-- First Ctrl+C: Cancel current step and pause the agent.- Second Ctrl+C: Exit immediately.- """- global _exiting-- if _exiting:- # Already exiting, force exit immediately- os._exit(0)-- if getattr(loop, 'ctrl_c_pressed', False):- # If we're in the waiting for input state, let the pause method handle it- if getattr(loop, 'waiting_for_input', False):- return-- # Second Ctrl+C - exit immediately- _exiting = True- logger.info('\n\n๐๐ Second Ctrl+C detected. Exiting immediately...\n\n')-- # Force exit - more reliable than sys.exit()- os._exit(0)-- # Mark that Ctrl+C was pressed- loop.ctrl_c_pressed = True-- # Cancel current tasks- current_task = asyncio.current_task(loop)- for task in asyncio.all_tasks(loop):- if task != current_task and not task.done():- task_name = task.get_name() if hasattr(task, 'get_name') else str(task)- if 'step' in task_name or 'multi_act' in task_name or 'get_next_action' in task_name:- task.cancel()-- # If we can get the agent reference, pause it- if agent and hasattr(agent, 'pause'):- agent.pause()-- logger.info('\n\n๐ Ctrl+C detected. Current step cancelled and agent paused.')- logger.info('Press Enter to resume or Ctrl+C again to exit completely.\n\n')---def sigterm_handler(loop: asyncio.AbstractEventLoop):- """SIGTERM handler.-- Always exits the program completely.- """- global _exiting- if not _exiting:- _exiting = True- logger.info('\n\n๐ SIGTERM received. Exiting immediately...\n\n')- os._exit(0)--Context = TypeVar('Context')@@ -400,7 +336,7 @@ class Agent(Generic[Context]):raise InterruptedErrorif self.state.stopped or self.state.paused:- logger.debug('Agent paused after getting state')+ # logger.debug('Agent paused after getting state')raise InterruptedError# @observe(name='agent.step', ignore_output=True, ignore_input=True)@@ -443,6 +379,10 @@ class Agent(Generic[Context]):try:model_output = await self.get_next_action(input_messages)+ # Check again for paused/stopped state after getting model output+ # This is needed in case Ctrl+C was pressed during the get_next_action call+ await self._raise_if_stopped_or_paused()+self.state.n_steps += 1if self.register_new_step_callback:@@ -459,6 +399,14 @@ class Agent(Generic[Context]):await self._raise_if_stopped_or_paused()self._message_manager.add_model_output(model_output)+ except asyncio.CancelledError:+ # Task was cancelled due to Ctrl+C+ self._message_manager._remove_last_state_message()+ raise InterruptedError('Model query cancelled by user')+ except InterruptedError:+ # Agent was paused during get_next_action+ self._message_manager._remove_last_state_message()+ raise # Re-raise to be caught by the outer try/exceptexcept Exception as e:# model call failed, remove last state message from historyself._message_manager._remove_last_state_message()@@ -474,13 +422,18 @@ class Agent(Generic[Context]):self.state.consecutive_failures = 0except InterruptedError:- logger.debug('Agent paused')+ # logger.debug('Agent paused')self.state.last_result = [ActionResult(- error='The agent was paused - now continuing actions might need to be repeated', include_in_memory=True+ error='The agent was paused mid-step - the last action might need to be repeated', include_in_memory=True)]return+ except asyncio.CancelledError:+ # Directly handle the case where the step is cancelled at a higher level+ # logger.debug('Task cancelled - agent was paused with Ctrl+C')+ self.state.last_result = [ActionResult(error='The agent was paused with Ctrl+C', include_in_memory=True)]+ raise InterruptedError('Step cancelled by user')except Exception as e:result = await self._handle_step_error(e)self.state.last_result = result@@ -668,7 +621,8 @@ class Agent(Generic[Context]):if len(parsed.action) > self.settings.max_actions_per_step:parsed.action = parsed.action[: self.settings.max_actions_per_step]- log_response(parsed)+ if not (hasattr(self.state, 'paused') and (self.state.paused or self.state.stopped)):+ log_response(parsed)return parsed@@ -719,13 +673,17 @@ class Agent(Generic[Context]):loop = asyncio.get_event_loop()- # Initialize control attributes- setattr(loop, 'ctrl_c_pressed', False)- setattr(loop, 'waiting_for_input', False)+ # Set up the Ctrl+C signal handler with callbacks specific to this agent+ from browser_use.utils import SignalHandler- # Set up signal handlers with reference to self (the agent)- loop.add_signal_handler(signal.SIGINT, lambda: sigint_handler(loop, self))- loop.add_signal_handler(signal.SIGTERM, lambda: sigterm_handler(loop))+ signal_handler = SignalHandler(+ loop=loop,+ pause_callback=self.pause,+ resume_callback=self.resume,+ custom_exit_callback=None, # No special cleanup needed on forced exit+ exit_on_second_int=True,+ )+ signal_handler.register()# Start non-blocking LLM connection verificationassert await self.llm._verified_api_keys, 'Failed to verify LLM API keys'@@ -740,32 +698,9 @@ class Agent(Generic[Context]):for step in range(max_steps):# Check if waiting for user input after Ctrl+C- if getattr(loop, 'waiting_for_user_input', False):- # Create a future that will be resolved when user presses Enter- user_input_future = loop.create_future()-- # Use a separate thread to read user input without blocking the event loop- def wait_for_input():- try:- input() # Wait for Enter key- if not user_input_future.done():- loop.call_soon_threadsafe(user_input_future.set_result, None)- except (EOFError, KeyboardInterrupt):- # If another Ctrl+C is received during input, exit- sys.exit(0)-- import threading-- threading.Thread(target=wait_for_input, daemon=True).start()-- try:- # Wait for user to press Enter- await user_input_future- logger.info('Resuming agent execution...')- loop.waiting_for_user_input = False- except asyncio.CancelledError:- # User pressed Ctrl+C again- sys.exit(0)+ if self.state.paused:+ signal_handler.wait_for_resume()+ signal_handler.reset()# Check if we should stop due to too many failuresif self.state.consecutive_failures >= self.settings.max_failures:@@ -803,6 +738,9 @@ class Agent(Generic[Context]):return self.state.historyfinally:+ # Unregister signal handlers before cleanup+ signal_handler.unregister()+self.telemetry.capture(AgentEndTelemetryEvent(agent_id=self.state.agent_id,@@ -851,25 +789,34 @@ class Agent(Generic[Context]):results.append(ActionResult(extracted_content=msg, include_in_memory=True))break- await self._raise_if_stopped_or_paused()+ try:+ await self._raise_if_stopped_or_paused()- result = await self.controller.act(- action,- self.browser_context,- self.settings.page_extraction_llm,- self.sensitive_data,- self.settings.available_file_paths,- context=self.context,- )+ result = await self.controller.act(+ action,+ self.browser_context,+ self.settings.page_extraction_llm,+ self.sensitive_data,+ self.settings.available_file_paths,+ context=self.context,+ )++ results.append(result)- results.append(result)+ logger.debug(f'Executed action {i + 1} / {len(actions)}')+ if results[-1].is_done or results[-1].error or i == len(actions) - 1:+ break- logger.debug(f'Executed action {i + 1} / {len(actions)}')- if results[-1].is_done or results[-1].error or i == len(actions) - 1:- break+ await asyncio.sleep(self.browser_context.config.wait_between_actions)+ # hash all elements. if it is a subset of cached_state its fine - else break (new elements on page)- await asyncio.sleep(self.browser_context.config.wait_between_actions)- # hash all elements. if it is a subset of cached_state its fine - else break (new elements on page)+ except asyncio.CancelledError:+ # Gracefully handle task cancellation+ logger.info(f'Action {i + 1} was cancelled due to Ctrl+C')+ if not results:+ # Add a result for the cancelled action+ results.append(ActionResult(error='The action was cancelled due to Ctrl+C', include_in_memory=True))+ raise InterruptedError('Action cancelled by user')return results@@ -1060,57 +1007,25 @@ class Agent(Generic[Context]):def pause(self) -> None:"""Pause the agent before the next step"""- logger.info('\n\nโธ๏ธ Got Ctrl+C, paused the agent and left the browser open.')+ print('\n\nโธ๏ธ Got Ctrl+C, paused the agent and left the browser open.')self.state.paused = True- # If this was triggered by Ctrl+C, wait for user input- loop = asyncio.get_event_loop()- if getattr(loop, 'ctrl_c_pressed', False):- # Set flag to indicate we're waiting for input- setattr(loop, 'waiting_for_input', True)-- # Temporarily restore default signal handling for SIGINT- # This ensures KeyboardInterrupt will be raised during input()- original_handler = signal.getsignal(signal.SIGINT)- signal.signal(signal.SIGINT, signal.default_int_handler)-- try:- print('Press [Enter] to resume or [Ctrl+C] to exit... ', end='', flush=True)- input() # This will raise KeyboardInterrupt on Ctrl+C-- self.resume()- except KeyboardInterrupt:- # Second Ctrl+C detected- global _exiting- if not _exiting:- _exiting = True- logger.info('\n\n๐ Second Ctrl+C detected. Exiting immediately...\n\n')- # Force exit with os._exit which doesn't run cleanup handlers (hides big wall of errors)- os._exit(0)- finally:- try:- signal.signal(signal.SIGINT, original_handler)- setattr(loop, 'waiting_for_input', False)- except BaseException:- pass+ # The signal handler will handle the asyncio pause logic for us+ # No need to duplicate the code heredef resume(self) -> None:"""Resume the agent"""- print()- logger.info('โถ๏ธ Resuming agent after user confirmation')+ print('\nโถ๏ธ Resuming agent after user confirmation')self.state.paused = False- # Clear the flags- loop = asyncio.get_event_loop()- if hasattr(loop, 'ctrl_c_pressed'):- loop.ctrl_c_pressed = False- if hasattr(loop, 'waiting_for_input'):- loop.waiting_for_input = False+ # The signal handler should have already reset the flags+ # through its reset() method when called from run()# playwright browser is always immediately killed by the first Ctrl+C (no way to stop that)# so we need to restart the browser if user wants to continueif self.browser:logger.info('๐ Restarting/reconnecting to browser...')+ loop = asyncio.get_event_loop()loop.create_task(self.browser._init())loop.create_task(asyncio.sleep(5))diff --git a/browser_use/utils.py b/browser_use/utils.pyindex d232b0aa6..8f278466a 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -1,17 +1,237 @@+import asyncioimport logging+import os+import signalimport timefrom functools import wraps-from typing import Any, Callable, Coroutine, ParamSpec, TypeVar-import os+from sys import stderr+from typing import Any, Callable, Coroutine, List, Optional, ParamSpec, TypeVarlogger = logging.getLogger(__name__)+# Global flag to prevent duplicate exit messages+_exiting = False# Define generic type variables for return type and parametersR = TypeVar('R')P = ParamSpec('P')+class SignalHandler:+ """+ A modular and reusable signal handling system for managing SIGINT (Ctrl+C), SIGTERM,+ and other signals in asyncio applications.++ This class provides:+ - Configurable signal handling for SIGINT and SIGTERM+ - Support for custom pause/resume callbacks+ - Management of event loop state across signals+ - Standardized handling of first and second Ctrl+C presses+ """++ def __init__(+ self,+ loop: Optional[asyncio.AbstractEventLoop] = None,+ pause_callback: Optional[Callable[[], None]] = None,+ resume_callback: Optional[Callable[[], None]] = None,+ custom_exit_callback: Optional[Callable[[], None]] = None,+ exit_on_second_int: bool = True,+ interruptible_task_patterns: List[str] = None,+ ):+ """+ Initialize the signal handler.++ Args:+ loop: The asyncio event loop to use. Defaults to current event loop.+ pause_callback: Function to call when system is paused (first Ctrl+C)+ resume_callback: Function to call when system is resumed+ custom_exit_callback: Function to call on exit (second Ctrl+C or SIGTERM)+ exit_on_second_int: Whether to exit on second SIGINT (Ctrl+C)+ interruptible_task_patterns: List of patterns to match task names that should be+ canceled on first Ctrl+C (default: ['step', 'multi_act', 'get_next_action'])+ """+ self.loop = loop or asyncio.get_event_loop()+ self.pause_callback = pause_callback+ self.resume_callback = resume_callback+ self.custom_exit_callback = custom_exit_callback+ self.exit_on_second_int = exit_on_second_int+ self.interruptible_task_patterns = interruptible_task_patterns or ['step', 'multi_act', 'get_next_action']++ # Initialize loop state attributes+ self._initialize_loop_state()++ # Store original signal handlers to restore them later if needed+ self.original_sigint_handler = None+ self.original_sigterm_handler = None++ def _initialize_loop_state(self) -> None:+ """Initialize loop state attributes used for signal handling."""+ setattr(self.loop, 'ctrl_c_pressed', False)+ setattr(self.loop, 'waiting_for_input', False)++ def register(self) -> None:+ """Register signal handlers for SIGINT and SIGTERM."""+ self.original_sigint_handler = self.loop.add_signal_handler(signal.SIGINT, lambda: self.sigint_handler())+ self.original_sigterm_handler = self.loop.add_signal_handler(signal.SIGTERM, lambda: self.sigterm_handler())++ def unregister(self) -> None:+ """Unregister signal handlers and restore original handlers if possible."""+ try:+ # Remove signal handlers+ self.loop.remove_signal_handler(signal.SIGINT)+ self.loop.remove_signal_handler(signal.SIGTERM)++ # Restore original handlers if available+ if self.original_sigint_handler:+ signal.signal(signal.SIGINT, self.original_sigint_handler)+ if self.original_sigterm_handler:+ signal.signal(signal.SIGTERM, self.original_sigterm_handler)+ except Exception as e:+ logger.warning(f'Error while unregistering signal handlers: {e}')++ def sigint_handler(self) -> None:+ """+ SIGINT (Ctrl+C) handler.++ First Ctrl+C: Cancel current step and pause.+ Second Ctrl+C: Exit immediately if exit_on_second_int is True.+ """+ global _exiting++ if _exiting:+ # Already exiting, force exit immediately+ os._exit(0)++ if getattr(self.loop, 'ctrl_c_pressed', False):+ # If we're in the waiting for input state, let the pause method handle it+ if getattr(self.loop, 'waiting_for_input', False):+ return++ # Second Ctrl+C - exit immediately if configured to do so+ if self.exit_on_second_int:+ _exiting = True+ print('\n\n๐ Second Ctrl+C detected. Exiting immediately...\n\n', file=stderr)++ # Call custom exit callback if provided+ if self.custom_exit_callback:+ try:+ self.custom_exit_callback()+ except Exception as e:+ logger.error(f'Error in exit callback: {e}')++ # Force immediate exit - more reliable than sys.exit()+ logger.debug('Forcing immediate exit with os._exit(0)')+ os._exit(0)++ # Mark that Ctrl+C was pressed+ self.loop.ctrl_c_pressed = True++ # Cancel current tasks that should be interruptible - this is crucial for immediate pausing+ self._cancel_interruptible_tasks()++ # Call pause callback if provided - this sets the paused flag+ if self.pause_callback:+ try:+ self.pause_callback()+ except Exception as e:+ logger.error(f'Error in pause callback: {e}')++ # Log pause message after pause_callback is called (not before)+ print('\n\n----------------------------------------------------------------------', file=stderr)+ print('Press [Enter] to resume or [Ctrl+C] again to exit completely.\n\n', file=stderr)++ def sigterm_handler(self) -> None:+ """+ SIGTERM handler.++ Always exits the program completely.+ """+ global _exiting+ if not _exiting:+ _exiting = True+ print('\n\n๐ SIGTERM received. Exiting immediately...\n\n', file=stderr)++ # Call custom exit callback if provided+ if self.custom_exit_callback:+ self.custom_exit_callback()++ os._exit(0)++ def _cancel_interruptible_tasks(self) -> None:+ """Cancel current tasks that should be interruptible."""+ current_task = asyncio.current_task(self.loop)+ for task in asyncio.all_tasks(self.loop):+ if task != current_task and not task.done():+ task_name = task.get_name() if hasattr(task, 'get_name') else str(task)+ # Cancel tasks that match certain patterns+ if any(pattern in task_name for pattern in self.interruptible_task_patterns):+ logger.debug(f'Cancelling task: {task_name}')+ task.cancel()++ # Also cancel the current task if it's interruptible+ if current_task and not current_task.done():+ task_name = current_task.get_name() if hasattr(current_task, 'get_name') else str(current_task)+ if any(pattern in task_name for pattern in self.interruptible_task_patterns):+ logger.debug(f'Cancelling current task: {task_name}')+ current_task.cancel()++ def wait_for_resume(self) -> None:+ """+ Wait for user input to resume or exit.++ This method should be called after handling the first Ctrl+C.+ It temporarily restores default signal handling to allow catching+ a second Ctrl+C directly.+ """+ # Set flag to indicate we're waiting for input+ setattr(self.loop, 'waiting_for_input', True)++ # Temporarily restore default signal handling for SIGINT+ # This ensures KeyboardInterrupt will be raised during input()+ original_handler = signal.getsignal(signal.SIGINT)+ signal.signal(signal.SIGINT, signal.default_int_handler)++ try:+ print('Press [Enter] to resume or [Ctrl+C] to exit... ', end='', flush=True, file=stderr)+ input() # This will raise KeyboardInterrupt on Ctrl+C++ # Call resume callback if provided+ if self.resume_callback:+ self.resume_callback()+ except KeyboardInterrupt:+ # Second Ctrl+C detected+ global _exiting+ if not _exiting:+ _exiting = True+ print('\n\n๐ Second Ctrl+C detected. Exiting immediately...\n\n', file=stderr)++ # Call custom exit callback if provided+ if self.custom_exit_callback:+ try:+ self.custom_exit_callback()+ except Exception as e:+ logger.error(f'Error in exit callback: {e}')++ # Force immediate exit+ # Force exit with os._exit which doesn't run cleanup handlers+ os._exit(0)+ finally:+ try:+ # Restore our signal handler+ signal.signal(signal.SIGINT, original_handler)+ setattr(self.loop, 'waiting_for_input', False)+ except Exception:+ pass++ def reset(self) -> None:+ """Reset state after resuming."""+ # Clear the flags+ if hasattr(self.loop, 'ctrl_c_pressed'):+ self.loop.ctrl_c_pressed = False+ if hasattr(self.loop, 'waiting_for_input'):+ self.loop.waiting_for_input = False++def time_execution_sync(additional_text: str = '') -> Callable[[Callable[P, R]], Callable[P, R]]:def decorator(func: Callable[P, R]) -> Callable[P, R]:@wraps(func)@@ -56,5 +276,5 @@ def singleton(cls):def check_env_variables(keys: list[str], any_or_all=all) -> bool:- """ Check if all required environment variables are set """- return any_or_all(os.getenv(key).strip() for key in keys)\ No newline at end of file+ """Check if all required environment variables are set"""+ return any_or_all(os.getenv(key).strip() for key in keys)