Skip to content

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

force-shutdown event_bus 20sec after browser stop

Nick Sweeting68496ef8028e
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index f3c7d201f..46407be80 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -371,6 +371,18 @@ class BrowserSession(BaseModel):
event = self.event_bus.dispatch(BrowserStopEvent())
await event
+ # Schedule EventBus cleanup after all events complete
+ async def cleanup_eventbus():
+ try:
+ await self.event_bus.wait_until_idle(timeout=20.0)
+ except TimeoutError:
+ logger.warning("EventBus didn't become idle within 20 seconds during stop")
+ await self.event_bus.stop(timeout=1.0, clear=True)
+
+ import asyncio
+
+ asyncio.create_task(cleanup_eventbus())
+
async def on_ClickElementEvent(self, event: ClickElementEvent) -> None:
"""Handle click request."""
page = await self.get_current_page()
@@ -548,9 +560,13 @@ class BrowserSession(BaseModel):
else:
page = await self.get_current_page()
- # Execute the JavaScript and return result directly
- result = await page.evaluate(event.expression)
- return result
+ # Execute the JavaScript with timeout protection
+ try:
+ result = await asyncio.wait_for(page.evaluate(event.expression), timeout=30.0)
+ return result
+ except TimeoutError:
+ logger.error(f'[Session] JavaScript evaluation timed out after 30 seconds: {event.expression[:100]}...')
+ raise Exception('JavaScript evaluation timed out after 30 seconds')
def _generate_recent_events_summary(self, max_events: int = 10) -> str:
"""Generate a JSON summary of recent browser events."""
diff --git a/tests/ci/test_aboutblank_watchdog.py b/tests/ci/test_aboutblank_watchdog.py
index adc0e6c42..0bf9b642b 100644
--- a/tests/ci/test_aboutblank_watchdog.py
+++ b/tests/ci/test_aboutblank_watchdog.py
@@ -9,7 +9,6 @@ from browser_use.browser.events import (
BrowserConnectedEvent,
BrowserStartEvent,
BrowserStopEvent,
- BrowserStoppedEvent,
NavigateToUrlEvent,
TabCreatedEvent,
)
@@ -33,26 +32,7 @@ async def test_aboutblank_watchdog_lifecycle():
assert session._aboutblank_watchdog is not None, 'AboutBlankWatchdog should not be None'
finally:
- # Stop browser
- stop_event = session.event_bus.dispatch(BrowserStopEvent())
- try:
- await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)
- except TimeoutError:
- print('BrowserStoppedEvent timed out')
-
- # Force close browser context if it exists
- try:
- if hasattr(session, '_browser_context') and session._browser_context:
- await session._browser_context.close()
- except Exception:
- pass
-
- # Stop playwright if it exists
- try:
- if hasattr(session, '_playwright') and session._playwright:
- await session._playwright.stop()
- except Exception:
- pass
+ await session.kill()
@pytest.mark.asyncio
@@ -76,29 +56,10 @@ async def test_aboutblank_watchdog_creates_animation_tab():
# Look for about:blank pages (animation tab)
about_blank_pages = [p for p in pages if p.url == 'about:blank']
# AboutBlankWatchdog should create at least one animation tab
- # Note: This depends on timing and browser state, so we don't assert strict count
+ assert len(about_blank_pages) >= 1, f'Expected at least one about:blank animation tab, but found {len(about_blank_pages)}'
finally:
- # Stop browser
- stop_event = session.event_bus.dispatch(BrowserStopEvent())
- try:
- await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)
- except TimeoutError:
- print('BrowserStoppedEvent timed out')
-
- # Force close browser context if it exists
- try:
- if hasattr(session, '_browser_context') and session._browser_context:
- await session._browser_context.close()
- except Exception:
- pass
-
- # Stop playwright if it exists
- try:
- if hasattr(session, '_playwright') and session._playwright:
- await session._playwright.stop()
- except Exception:
- pass
+ await session.kill()
@pytest.mark.asyncio
@@ -127,26 +88,7 @@ async def test_aboutblank_watchdog_handles_tab_creation():
# We can't easily verify internal state without accessing private methods
finally:
- # Stop browser
- stop_event = session.event_bus.dispatch(BrowserStopEvent())
- try:
- await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)
- except TimeoutError:
- print('BrowserStoppedEvent timed out')
-
- # Force close browser context if it exists
- try:
- if hasattr(session, '_browser_context') and session._browser_context:
- await session._browser_context.close()
- except Exception:
- pass
-
- # Stop playwright if it exists
- try:
- if hasattr(session, '_playwright') and session._playwright:
- await session._playwright.stop()
- except Exception:
- pass
+ await session.kill()
@pytest.mark.asyncio
@@ -181,26 +123,7 @@ async def test_aboutblank_watchdog_dvd_screensaver():
print(f'DVD screensaver test encountered expected issue: {e}')
finally:
- # Stop browser
- stop_event = session.event_bus.dispatch(BrowserStopEvent())
- try:
- await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)
- except TimeoutError:
- print('BrowserStoppedEvent timed out')
-
- # Force close browser context if it exists
- try:
- if hasattr(session, '_browser_context') and session._browser_context:
- await session._browser_context.close()
- except Exception:
- pass
-
- # Stop playwright if it exists
- try:
- if hasattr(session, '_playwright') and session._playwright:
- await session._playwright.stop()
- except Exception:
- pass
+ await session.kill()
@pytest.mark.asyncio
@@ -237,26 +160,7 @@ async def test_aboutblank_watchdog_animation_tab_management():
assert len(final_pages) >= initial_page_count, 'Should not lose pages'
finally:
- # Stop browser
- stop_event = session.event_bus.dispatch(BrowserStopEvent())
- try:
- await asyncio.wait_for(session.event_bus.expect(BrowserStoppedEvent), timeout=5.0)
- except TimeoutError:
- print('BrowserStoppedEvent timed out')
-
- # Force close browser context if it exists
- try:
- if hasattr(session, '_browser_context') and session._browser_context:
- await session._browser_context.close()
- except Exception:
- pass
-
- # Stop playwright if it exists
- try:
- if hasattr(session, '_playwright') and session._playwright:
- await session._playwright.stop()
- except Exception:
- pass
+ await session.kill()
@pytest.mark.asyncio