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
Fix #1716: Consolidate pause/resume state management
MagellaXe67209c17a7b
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 29fbe7c16..626fa9469 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -472,8 +472,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self._last_known_downloads: list[str] = []self.logger.info('📁 Initialized download tracking for agent')- self._external_pause_event = asyncio.Event()- self._external_pause_event.set()+ # Pause event is now managed in AgentState - no separate attribute needed@propertydef logger(self) -> logging.Logger:@@ -665,10 +664,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):if self.state.stopped:raise InterruptedError- # Treat a cleared external pause event as the definitive paused signal.- # We intentionally rely on the event instead of the `state.paused` flag to- # avoid desynchronisation between the two.- if not self._external_pause_event.is_set():+ # Use the consolidated pause event from state as the single source of truth+ if self.state.paused:raise InterruptedError@observe(name='agent.step', ignore_output=True, ignore_input=True)@@ -1226,10 +1223,10 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.logger.debug(f'🔄 Starting main execution loop with max {max_steps} steps...')for step in range(max_steps):- # Use the pause event to wait if the agent is paused.- if not self._external_pause_event.is_set():+ # Use the consolidated pause state management+ if self.state.paused:self.logger.debug(f'⏸️ Step {step}: Agent paused, waiting to resume...')- await self.wait_until_resumed()+ await self.state.wait_until_resumed()signal_handler.reset()# Check if we should stop due to too many failures@@ -1615,16 +1612,12 @@ class Agent(Generic[Context, AgentStructuredOutput]):file_path = 'AgentHistory.json'self.state.history.save_to_file(file_path)- async def wait_until_resumed(self):- await self._external_pause_event.wait()-def pause(self) -> None:"""Pause the agent before the next step"""print('\n\n⏸️ Got [Ctrl+C], paused the agent and left the browser open.\n\tPress [Enter] to resume or [Ctrl+C] again to quit.')- self.state.paused = True- self._external_pause_event.clear()+ self.state.pause()# Task paused@@ -1635,8 +1628,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):"""Resume the agent"""print('----------------------------------------------------------------------')print('▶️ Got Enter, resuming agent execution where it left off...\n')- self.state.paused = False- self._external_pause_event.set()+ self.state.resume()# Task resumeddiff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 044b23af0..c67e4c427 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport jsonimport tracebackfrom dataclasses import dataclass@@ -72,6 +73,8 @@ class AgentSettings(BaseModel):class AgentState(BaseModel):"""Holds all state information for an Agent"""+ model_config = ConfigDict(arbitrary_types_allowed=True)+agent_id: str = Field(default_factory=uuid7str)n_steps: int = 1consecutive_failures: int = 0@@ -79,14 +82,38 @@ class AgentState(BaseModel):history: AgentHistoryList = Field(default_factory=lambda: AgentHistoryList(history=[], usage=None))last_plan: str | None = Nonelast_model_output: AgentOutput | None = None- paused: bool = False++ # Consolidated pause/resume state management+ # The pause_event serves as the single source of truth for pause state+ # When set: agent is running, when cleared: agent is paused+ pause_event: asyncio.Event = Field(default_factory=lambda: asyncio.Event(), exclude=True, repr=False)stopped: bool = Falsemessage_manager_state: MessageManagerState = Field(default_factory=MessageManagerState)file_system_state: FileSystemState | None = None- # class Config:- # arbitrary_types_allowed = True+ def __init__(self, **data):+ super().__init__(**data)+ # Ensure pause_event is initially set (not paused)+ if not self.pause_event.is_set():+ self.pause_event.set()++ @property+ def paused(self) -> bool:+ """Check if agent is paused by examining the pause event"""+ return not self.pause_event.is_set()++ def pause(self) -> None:+ """Pause the agent by clearing the pause event"""+ self.pause_event.clear()++ def resume(self) -> None:+ """Resume the agent by setting the pause event"""+ self.pause_event.set()++ async def wait_until_resumed(self) -> None:+ """Wait until the agent is resumed"""+ await self.pause_event.wait()@dataclass