Skip to content

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

use self.logger to shorten log lines

Nick Sweeting2a39dfa1c516
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 58a505333..fde64c56a 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -106,7 +106,7 @@ def require_initialization(func):
except Exception as e:
# Check if this is a TargetClosedError or similar connection error
if 'TargetClosedError' in str(type(e)) or 'context or browser has been closed' in str(e):
- logger.debug(f'Detected closed browser connection in {func.__name__}, resetting connection state')
+ self.logger.debug(f'Detected closed browser connection in {func.__name__}, resetting connection state')
self._reset_connection_state()
# Re-raise the error so the caller can handle it appropriately
raise
@@ -215,6 +215,7 @@ class BrowserSession(BaseModel):
_cached_clickable_element_hashes: CachedClickableElementHashes | None = PrivateAttr(default=None)
_start_lock: asyncio.Lock = PrivateAttr(default_factory=asyncio.Lock)
_tab_visibility_callback: Any = PrivateAttr(default=None)
+ _logger: logging.Logger | None = PrivateAttr(default=None)
@model_validator(mode='after')
def apply_session_overrides_to_profile(self) -> Self:
@@ -238,6 +239,14 @@ class BrowserSession(BaseModel):
return self
+ @property
+ def logger(self) -> logging.Logger:
+ """Get instance-specific logger with session ID in the name"""
+ if self._logger is None:
+ # Create a child logger with the session ID
+ self._logger = logging.getLogger(f'browser_use.BrowserSession[{self.id[-3:]}]')
+ return self._logger
+
def __repr__(self) -> str:
return f'BrowserSession[{self.id[-3:]}](profile={self.browser_profile}, {self._connection_str})'
@@ -277,7 +286,7 @@ class BrowserSession(BaseModel):
if self.cdp_url or self.wss_url or self.browser_pid
else 'by launching a new browser (previous one was closed)'
)
- logger.info(f'♻️ {self} Re-starting stale session {connection_str}')
+ self.logger.info(f'♻️ Re-starting stale session {connection_str}')
# only reset connection state if we expected to be already connected but we're not
# avoid calling this on *first* start() as it just immediately clears many
# of the params passed in to BrowserSession(...) init, which the .setup_...() methods below expect
@@ -310,7 +319,7 @@ class BrowserSession(BaseModel):
self.initialized = False
raise
- # logger.debug(f'🎭 {self} started successfully')
+ # self.logger.debug(f'🎭 started successfully')
return self
@@ -351,24 +360,25 @@ class BrowserSession(BaseModel):
try:
await self.save_storage_state()
except Exception as e:
- logger.debug(f'{self} Failed to save storage state before stopping: {type(e).__name__}: {e}')
+ self.logger.debug(f'Failed to save storage state before stopping: {type(e).__name__}: {e}')
if self.browser_profile.keep_alive:
- logger.info(
+ self.logger.info(
f'🕊️ {self}.stop() called but keep_alive=True, leaving the browser running. Use .kill() to force close.'
)
return # nothing to do if keep_alive=True, leave the browser running
if self.browser_context or self.browser:
try:
- logger.info(
- f'🛑 {self} Stopping {self._connection_str} channel={self.browser_profile.channel.name.lower()} '
+ self.logger.info(
+ f'🛑 Closing {self._connection_str} {self.browser_profile.channel.name.lower()} context with '
f'user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"}'
+ f'storage_state= {_log_pretty_path(self.browser_profile.storage_state_path or self.browser_profile.cookies_file) or "<none>"}'
)
await (self.browser_context or self.browser).close()
except Exception as e:
- logger.debug(
- f'❌ {self} Error closing playwright browser_context={self.browser_context}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'❌ Error closing playwright browser_context={self.browser_context}: {type(e).__name__}: {e}'
)
finally:
# Always clear references to ensure a fresh start next time
@@ -381,12 +391,12 @@ class BrowserSession(BaseModel):
proc = psutil.Process(pid=self.browser_pid)
executable_path = proc.cmdline()[0]
proc.terminate()
- logger.info(f' ↳ {self} Killed browser_pid={self.browser_pid} {_log_pretty_path(executable_path)}')
+ self.logger.info(f' ↳ Killed browser_pid={self.browser_pid} {_log_pretty_path(executable_path)}')
self.browser_pid = None
except Exception as e:
if 'NoSuchProcess' not in type(e).__name__:
- logger.debug(
- f'❌ {self} Error terminating subprocess with browser_pid={self.browser_pid}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'❌ Error terminating subprocess with browser_pid={self.browser_pid}: {type(e).__name__}: {e}'
)
# Close playwright if we own it
@@ -395,14 +405,14 @@ class BrowserSession(BaseModel):
# await self.playwright.stop()
# self.playwright = None
# except Exception as e:
- # logger.debug(f'{self} Error stopping playwright: {type(e).__name__}: {e}')
+ # self.logger.debug(f'Error stopping playwright: {type(e).__name__}: {e}')
self._reset_connection_state()
async def close(self) -> None:
"""Deprecated: Provides backwards-compatibility with old class method Browser().close()"""
- # logger.debug(
- # f'⏹️ Stopping {self} gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (close() called)'
+ # self.logger.debug(
+ # f'⏹️ Stopping gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (close() called)'
# )
await self.stop()
@@ -415,8 +425,8 @@ class BrowserSession(BaseModel):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
- # logger.debug(
- # f'⏹️ Stopping {self} gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (context manager exit)'
+ # self.logger.debug(
+ # f'⏹️ Stopping gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (context manager exit)'
# )
await self.stop()
@@ -428,8 +438,8 @@ class BrowserSession(BaseModel):
if profile and (getattr(self, 'initialized', None) or getattr(self, 'browser_context', None) or browser_pid):
keep_alive = getattr(profile, 'keep_alive', None)
user_data_dir = getattr(profile, 'user_data_dir', None)
- logger.info(
- f'🛑 {self} Stopping (went out of scope) {self._connection_str} keep_alive={keep_alive} user_data_dir= {_log_pretty_path(user_data_dir) or "<incognito>"}'
+ self.logger.info(
+ f'🛑 Stopping (went out of scope) {self._connection_str} keep_alive={keep_alive} user_data_dir= {_log_pretty_path(user_data_dir) or "<incognito>"}'
)
except BaseException:
# Never let __del__ raise exceptions
@@ -444,17 +454,15 @@ class BrowserSession(BaseModel):
# use patchright instead of playwright
self.playwright = self.playwright or (await async_patchright().start())
self.browser_profile.channel = self.browser_profile.channel or BrowserChannel.CHROME
- logger.info(
- f'🕶️ {self} Activated stealth mode using patchright {self.browser_profile.channel.name.lower()} browser...'
- )
+ self.logger.info(f'🕶️ Activated stealth mode using patchright {self.browser_profile.channel.name.lower()} browser...')
# check for stealth best-practices
if self.browser_profile.channel and self.browser_profile.channel != BrowserChannel.CHROME:
- logger.info(f' 🪄 For maximum stealth, {self}(...) should be passed channel=None or BrowserChannel.CHROME')
+ self.logger.info(' 🪄 For maximum stealth, (...) should be passed channel=None or BrowserChannel.CHROME')
if not self.browser_profile.user_data_dir:
- logger.info(f' 🪄 For maximum stealth, {self}(...) should be passed a persistent user_data_dir=...')
+ self.logger.info(' 🪄 For maximum stealth, (...) should be passed a persistent user_data_dir=...')
if self.browser_profile.headless or not self.browser_profile.no_viewport:
- logger.info(f' 🪄 For maximum stealth, {self}(...) should be passed headless=False & viewport=None')
+ self.logger.info(' 🪄 For maximum stealth, (...) should be passed headless=False & viewport=None')
else:
# default is standard playwright chromium (headful, or headless=new)
self.playwright = self.playwright or (await async_playwright().start())
@@ -492,7 +500,7 @@ class BrowserSession(BaseModel):
self.browser = browser_from_context
if self.browser or self.browser_context:
- logger.info(f'🎭 {self} Connected to existing user-provided browser: {self.browser_context}')
+ self.logger.info(f'🎭 Connected to existing user-provided browser: {self.browser_context}')
self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end
async def setup_browser_via_browser_pid(self) -> None:
@@ -512,7 +520,7 @@ class BrowserSession(BaseModel):
)
# we could automatically relaunch the browser process with that arg added here, but they may have tabs open they dont want to lose
self.cdp_url = self.cdp_url or f'http://localhost:{debug_port}/'
- logger.info(f'🌎 {self} Connecting to existing local browser process: browser_pid={self.browser_pid} on {self.cdp_url}')
+ self.logger.info(f'🌎 Connecting to existing local browser process: browser_pid={self.browser_pid} on {self.cdp_url}')
self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
self.cdp_url,
**self.browser_profile.kwargs_for_connect().model_dump(),
@@ -527,7 +535,7 @@ class BrowserSession(BaseModel):
if not self.wss_url:
return # no wss_url provided, nothing to do
- logger.info(f'🌎 {self} Connecting to existing remote chromium playwright node.js server over WSS: {self.wss_url}')
+ self.logger.info(f'🌎 Connecting to existing remote chromium playwright node.js server over WSS: {self.wss_url}')
self.browser = self.browser or await self.playwright.chromium.connect(
self.wss_url,
**self.browser_profile.kwargs_for_connect().model_dump(),
@@ -542,7 +550,7 @@ class BrowserSession(BaseModel):
if not self.cdp_url:
return # no cdp_url provided, nothing to do
- logger.info(f'🌎 {self} Connecting to existing remote chromium-based browser over CDP: {self.cdp_url}')
+ self.logger.info(f'🌎 Connecting to existing remote chromium-based browser over CDP: {self.cdp_url}')
self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(
self.cdp_url,
**self.browser_profile.kwargs_for_connect().model_dump(),
@@ -558,7 +566,7 @@ class BrowserSession(BaseModel):
if self.browser and not self.browser_context:
if self.browser.contexts:
self.browser_context = self.browser.contexts[0]
- logger.info(f'🌎 {self} Using first browser_context available in existing browser: {self.browser_context}')
+ self.logger.info(f'🌎 Using first browser_context available in existing browser: {self.browser_context}')
else:
self.browser_context = await self.browser.new_context(
**self.browser_profile.kwargs_for_new_context().model_dump()
@@ -568,28 +576,28 @@ class BrowserSession(BaseModel):
if self.browser_profile.storage_state
else ''
)
- logger.info(
- f'🌎 {self} Created new empty browser_context in existing browser{storage_info}: {self.browser_context}'
+ self.logger.info(
+ f'🌎 Created new empty browser_context in existing browser{storage_info}: {self.browser_context}'
)
# if we still have no browser_context by now, launch a new local one using launch_persistent_context()
if not self.browser_context:
- logger.info(
- f'🌎 {self} Launching new local browser '
+ self.logger.info(
+ f'🌎 Launching new local browser '
f'{str(type(self.playwright).__module__).split(".")[0]}:{self.browser_profile.channel.name.lower()} keep_alive={self.browser_profile.keep_alive or False} '
f'user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"}'
)
if not self.browser_profile.user_data_dir:
- # logger.debug('🌎 Launching local browser in incognito mode')
+ # self.logger.debug('🌎 Launching local browser in incognito mode')
# if no user_data_dir is provided, launch an incognito context with no persistent user_data_dir
self.browser = self.browser or await self.playwright.chromium.launch(
**self.browser_profile.kwargs_for_launch().model_dump()
)
- # logger.debug('🌎 Launching new incognito context in browser')
+ # self.logger.debug('🌎 Launching new incognito context in browser')
self.browser_context = await self.browser.new_context(
**self.browser_profile.kwargs_for_new_context().model_dump()
)
- # logger.debug('🌎 Created new incognito context in browser')
+ # self.logger.debug('🌎 Created new incognito context in browser')
else:
# user data dir was provided, prepare it for use
self.browser_profile.prepare_user_data_dir()
@@ -597,8 +605,8 @@ class BrowserSession(BaseModel):
# search for potentially conflicting local processes running on the same user_data_dir
for proc in psutil.process_iter(['pid', 'cmdline']):
if f'--user-data-dir={self.browser_profile.user_data_dir}' in (proc.info['cmdline'] or []):
- logger.error(
- f'🚨 {self} Found potentially conflicting browser process browser_pid={proc.info["pid"]} '
+ self.logger.error(
+ f'🚨 Found potentially conflicting browser process browser_pid={proc.info["pid"]} '
f'already running with the same user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)}'
)
break
@@ -633,8 +641,8 @@ class BrowserSession(BaseModel):
if self.browser_profile.executable_path
else (self.browser_profile.channel or BROWSERUSE_DEFAULT_CHANNEL).name.lower()
)
- logger.error(
- f'❌ {self} Launching new local browser {driver}:{browser_channel} (v{test_browser_version}) failed!'
+ self.logger.error(
+ f'❌ Launching new local browser {driver}:{browser_channel} (v{test_browser_version}) failed!'
f'\n\tFailed {reason} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)} (created with v{user_data_dir_chrome_version})'
'\n\tTry using a different browser version/channel or delete the user_data_dir to start over with a fresh profile.'
'\n\t(can happen if different versions of Chrome/Chromium/Brave/etc. tried to share one dir)'
@@ -656,28 +664,28 @@ class BrowserSession(BaseModel):
new_child_procs = [psutil.Process(pid) for pid in new_child_pids]
new_chrome_procs = [proc for proc in new_child_procs if 'Helper' not in proc.name() and proc.status() == 'running']
except Exception as e:
- logger.debug(
- f'❌ {self} Error trying to find child chrome processes after launching new browser: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'❌ Error trying to find child chrome processes after launching new browser: {type(e).__name__}: {e}'
)
new_chrome_procs = []
if new_chrome_procs and not self.browser_pid:
self.browser_pid = new_chrome_procs[0].pid
- logger.info(f' ↳ {self} Spawned browser_pid={self.browser_pid} {_log_pretty_path(new_chrome_procs[0].cmdline()[0])}')
- logger.debug(' '.join(new_chrome_procs[0].cmdline())) # print the entire launch command for debugging
+ self.logger.info(f' ↳ Spawned browser_pid={self.browser_pid} {_log_pretty_path(new_chrome_procs[0].cmdline()[0])}')
+ self.logger.debug(' '.join(new_chrome_procs[0].cmdline())) # print the entire launch command for debugging
self._set_browser_keep_alive(False) # close the browser at the end because we launched it
if self.browser:
assert self.browser.is_connected(), (
f'Browser is not connected, did the browser process crash or get killed? (connection method: {self._connection_str})'
)
- logger.debug(f'🌎 {self} browser connected: v{self.browser.version} {self._connection_str}')
+ self.logger.debug(f'🌎 browser connected: v{self.browser.version} {self._connection_str}')
assert self.browser_context, (
f'{self} Failed to create a playwright BrowserContext {self.browser_context} for browser={self.browser}'
)
- # logger.debug('Setting up init scripts in browser')
+ # self.logger.debug('Setting up init scripts in browser')
init_script = """
// check to make sure we're not inside the PDF viewer
@@ -733,7 +741,7 @@ class BrowserSession(BaseModel):
await self.browser_context.add_init_script(init_script)
if self.browser_profile.stealth and not isinstance(self.playwright, Patchright):
- logger.warning(f'⚠️ {self} Failed to set up stealth mode. {self}(...) got normal playwright objects as input.')
+ self.logger.warning('⚠️ Failed to set up stealth mode. (...) got normal playwright objects as input.')
# async def _fork_locked_user_data_dir(self) -> None:
# """Fork an in-use user_data_dir by cloning it to a new location to allow a second browser to use it"""
@@ -782,17 +790,17 @@ class BrowserSession(BaseModel):
foreground_page = None
if pages:
foreground_page = pages[0]
- logger.debug(
- f'📜 {self} Found {len(pages)} existing tabs in browser, agent will start focused on Tab [{pages.index(foreground_page)}]: {foreground_page.url}'
+ self.logger.debug(
+ f'📜 Found {len(pages)} existing tabs in browser, agent will start focused on Tab [{pages.index(foreground_page)}]: {foreground_page.url}'
)
else:
foreground_page = await self.browser_context.new_page()
pages = [foreground_page]
- logger.debug('➕ {self} Opened new tab in empty browser context...')
+ self.logger.debug('➕ Opened new tab in empty browser context...')
self.agent_current_page = self.agent_current_page or foreground_page
self.human_current_page = self.human_current_page or foreground_page
- # logger.debug('About to define _BrowserUseonTabVisibilityChange callback')
+ # self.logger.debug('About to define _BrowserUseonTabVisibilityChange callback')
def _BrowserUseonTabVisibilityChange(source: dict[str, str]):
"""hook callback fired when init script injected into a page detects a focus event"""
@@ -812,8 +820,8 @@ class BrowserSession(BaseModel):
agent_url = self.agent_current_page and self.agent_current_page.url or 'about:blank'
agent_tab_idx = self.browser_context.pages.index(self.agent_current_page)
if old_url != new_url:
- logger.info(
- f'👁️ {self} Foregound tab changed by human from [{old_tab_idx}]{_log_pretty_url(old_url)} '
+ self.logger.info(
+ f'👁️ Foregound tab changed by human from [{old_tab_idx}]{_log_pretty_url(old_url)} '
f'➡️ [{new_tab_idx}]{_log_pretty_url(new_url)} '
f'(agent will stay on [{agent_tab_idx}]{_log_pretty_url(agent_url)})'
)
@@ -821,14 +829,14 @@ class BrowserSession(BaseModel):
# Store the callback so we can potentially clean it up later
self._tab_visibility_callback = _BrowserUseonTabVisibilityChange
- # logger.info('About to call expose_binding')
+ # self.logger.info('About to call expose_binding')
try:
await self.browser_context.expose_binding('_BrowserUseonTabVisibilityChange', _BrowserUseonTabVisibilityChange)
- logger.debug('expose_binding completed successfully')
+ self.logger.debug('expose_binding completed successfully')
except Exception as e:
if 'Function "_BrowserUseonTabVisibilityChange" has been already registered' in str(e):
- logger.debug(
- f'⚠️ {self} Function "_BrowserUseonTabVisibilityChange" has been already registered, '
+ self.logger.debug(
+ '⚠️ Function "_BrowserUseonTabVisibilityChange" has been already registered, '
'this is likely because the browser was already started with an existing BrowserSession()'
)
@@ -865,23 +873,23 @@ class BrowserSession(BaseModel):
try:
await self.browser_context.add_init_script(update_tab_focus_script)
except Exception as e:
- logger.debug(f'⚠️ {self} Failed to register init script for tab focus detection: {e}')
+ self.logger.debug(f'⚠️ Failed to register init script for tab focus detection: {e}')
# Set up visibility listeners for all existing tabs
- # logger.info(f'Setting up visibility listeners for {len(self.browser_context.pages)} pages')
+ # self.logger.info(f'Setting up visibility listeners for {len(self.browser_context.pages)} pages')
for page in self.browser_context.pages:
- # logger.info(f'Processing page with URL: {repr(page.url)}')
+ # self.logger.info(f'Processing page with URL: {repr(page.url)}')
# Skip about:blank pages as they can hang when evaluating scripts
if page.url == 'about:blank':
continue
try:
await page.evaluate(update_tab_focus_script)
- # logger.debug(f'👁️ {self} Added visibility listener to existing tab: {page.url}')
+ # self.logger.debug(f'👁️ Added visibility listener to existing tab: {page.url}')
except Exception as e:
page_idx = self.browser_context.pages.index(page)
- logger.debug(
- f'⚠️ {self} Failed to add visibility listener to existing tab, is it crashed or ignoring CDP commands?: [{page_idx}]{page.url}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'⚠️ Failed to add visibility listener to existing tab, is it crashed or ignoring CDP commands?: [{page_idx}]{page.url}: {type(e).__name__}: {e}'
)
async def _setup_viewports(self) -> None:
@@ -889,8 +897,8 @@ class BrowserSession(BaseModel):
# log the viewport settings to terminal
viewport = self.browser_profile.viewport
- logger.debug(
- '📐 {self} Setting up viewport: '
+ self.logger.debug(
+ '📐 Setting up viewport: '
+ f'headless={self.browser_profile.headless} '
+ (
f'window={self.browser_profile.window_size["width"]}x{self.browser_profile.window_size["height"]}px '
@@ -918,8 +926,8 @@ class BrowserSession(BaseModel):
try:
await self.browser_context.grant_permissions(self.browser_profile.permissions)
except Exception as e:
- logger.warning(
- f'⚠️ {self} Failed to grant browser permissions {self.browser_profile.permissions}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'⚠️ Failed to grant browser permissions {self.browser_profile.permissions}: {type(e).__name__}: {e}'
)
try:
if self.browser_profile.default_timeout:
@@ -927,8 +935,8 @@ class BrowserSession(BaseModel):
if self.browser_profile.default_navigation_timeout:
await self.browser_context.set_default_navigation_timeout(self.browser_profile.default_navigation_timeout)
except Exception as e:
- logger.warning(
- f'⚠️ {self} Failed to set playwright timeout settings '
+ self.logger.warning(
+ f'⚠️ Failed to set playwright timeout settings '
f'cdp_api={self.browser_profile.default_timeout} '
f'navigation={self.browser_profile.default_navigation_timeout}: {type(e).__name__}: {e}'
)
@@ -936,16 +944,16 @@ class BrowserSession(BaseModel):
if self.browser_profile.extra_http_headers:
await self.browser_context.set_extra_http_headers(self.browser_profile.extra_http_headers)
except Exception as e:
- logger.warning(
- f'⚠️ {self} Failed to setup playwright extra_http_headers: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'⚠️ Failed to setup playwright extra_http_headers: {type(e).__name__}: {e}'
) # dont print the secret header contents in the logs!
try:
if self.browser_profile.geolocation:
await self.browser_context.set_geolocation(self.browser_profile.geolocation)
except Exception as e:
- logger.warning(
- f'⚠️ {self} Failed to update browser geolocation {self.browser_profile.geolocation}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'⚠️ Failed to update browser geolocation {self.browser_profile.geolocation}: {type(e).__name__}: {e}'
)
await self.load_storage_state()
@@ -993,8 +1001,8 @@ class BrowserSession(BaseModel):
except Exception as e:
pass
- logger.warning(
- f'⚠️ {self} Failed to resize browser window to {_log_size(self.browser_profile.window_size)} using CDP setWindowBounds: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'⚠️ Failed to resize browser window to {_log_size(self.browser_profile.window_size)} using CDP setWindowBounds: {type(e).__name__}: {e}'
)
def _set_browser_keep_alive(self, keep_alive: bool | None) -> None:
@@ -1053,8 +1061,8 @@ class BrowserSession(BaseModel):
proc_is_alive = proc.status() not in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD)
assert proc_is_alive and '--remote-debugging-port' in ' '.join(proc.cmdline())
except Exception:
- logger.info(
- f'👋 {self} Browser process browser_pid={self.browser_pid} has gone away or crashed, will be re-launched'
+ self.logger.info(
+ f'👋 Browser process browser_pid={self.browser_pid} has gone away or crashed, will be re-launched'
)
# process has gone away or crashed, pid is no longer valid so we clear it
self.browser_pid = None
@@ -1152,7 +1160,7 @@ class BrowserSession(BaseModel):
"""
)
except Exception as e:
- logger.debug(f'⚠️ {self} Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')
+ self.logger.debug(f'⚠️ Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')
# Don't raise the error since this is not critical functionality
@require_initialization
@@ -1195,11 +1203,11 @@ class BrowserSession(BaseModel):
unique_filename = await self._get_unique_filename(self.browser_profile.downloads_path, suggested_filename)
download_path = os.path.join(self.browser_profile.downloads_path, unique_filename)
await download.save_as(download_path)
- logger.debug(f'⬇️ {self} Download triggered. Saved file to: {download_path}')
+ self.logger.debug(f'⬇️ Download triggered. Saved file to: {download_path}')
return download_path
except Exception:
# If no download is triggered, treat as normal click
- logger.debug(f'{self} No download triggered within timeout. Checking navigation...')
+ self.logger.debug('No download triggered within timeout. Checking navigation...')
await page.wait_for_load_state()
await self._check_and_handle_navigation(page)
else:
@@ -1237,7 +1245,7 @@ class BrowserSession(BaseModel):
except TimeoutError:
# page.title() can hang forever on tabs that are crashed/disappeared/about:blank
# we dont want to try automating those tabs because they will hang the whole script
- logger.debug(f'⚠️ {self} Failed to get tab info for tab #{page_id}: {_log_pretty_url(page.url)} (ignoring)')
+ self.logger.debug(f'⚠️ Failed to get tab info for tab #{page_id}: {_log_pretty_url(page.url)} (ignoring)')
tab_info = TabInfo(page_id=page_id, url='about:blank', title='ignore this tab and do not use it')
tabs_info.append(tab_info)
@@ -1308,10 +1316,10 @@ class BrowserSession(BaseModel):
pass
temp_path.replace(cookies_file_path)
- logger.info(f'🍪 {self} Saved {len(cookies)} cookies to cookies_file= {_log_pretty_path(cookies_file_path)}')
+ self.logger.info(f'🍪 Saved {len(cookies)} cookies to cookies_file= {_log_pretty_path(cookies_file_path)}')
except Exception as e:
- logger.warning(
- f'❌ {self} Failed to save cookies to cookies_file= {_log_pretty_path(cookies_file_path)}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'❌ Failed to save cookies to cookies_file= {_log_pretty_path(cookies_file_path)}: {type(e).__name__}: {e}'
)
async def _save_storage_state_to_file(self, path: Path, storage_state: dict[str, Any] | None) -> None:
@@ -1327,8 +1335,8 @@ class BrowserSession(BaseModel):
existing_storage_state = json.loads(json_path.read_text())
merged_storage_state = merge_dicts(existing_storage_state, storage_state)
except Exception as e:
- logger.error(
- f'❌ {self} Failed to merge cookie changes with existing storage_state= {_log_pretty_path(json_path)}: {type(e).__name__}: {e}'
+ self.logger.error(
+ f'❌ Failed to merge cookie changes with existing storage_state= {_log_pretty_path(json_path)}: {type(e).__name__}: {e}'
)
return
@@ -1341,13 +1349,9 @@ class BrowserSession(BaseModel):
pass
temp_path.replace(json_path)
- logger.info(
- f'🍪 {self} Saved {len(storage_state["cookies"])} cookies to storage_state= {_log_pretty_path(json_path)}'
- )
+ self.logger.info(f'🍪 Saved {len(storage_state["cookies"])} cookies to storage_state= {_log_pretty_path(json_path)}')
except Exception as e:
- logger.warning(
- f'❌ {self} Failed to save cookies to storage_state= {_log_pretty_path(path)}: {type(e).__name__}: {e}'
- )
+ self.logger.warning(f'❌ Failed to save cookies to storage_state= {_log_pretty_path(path)}: {type(e).__name__}: {e}')
@require_initialization
async def save_storage_state(self, path: Path | None = None) -> None:
@@ -1368,7 +1372,7 @@ class BrowserSession(BaseModel):
await self._save_cookies_to_file(path, cookies)
await self._save_storage_state_to_file(path.parent / 'storage_state.json', storage_state)
new_path = path.parent / 'storage_state.json'
- logger.warning(
+ self.logger.warning(
'⚠️ cookies_file is deprecated and will be removed in a future version. '
f'Please use storage_state="{_log_pretty_path(new_path)}" instead for persisting cookies and other browser state. '
'See: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-storage-state'
@@ -1381,7 +1385,7 @@ class BrowserSession(BaseModel):
await self._save_cookies_to_file(path or self.browser_profile.cookies_file, cookies)
await self._save_storage_state_to_file(path.parent / 'storage_state.json', storage_state)
new_path = path.parent / 'storage_state.json'
- logger.warning(
+ self.logger.warning(
'⚠️ cookies_file is deprecated and will be removed in a future version. '
f'Please use storage_state="{_log_pretty_path(new_path)}" instead for persisting cookies and other browser state. '
'See: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-storage-state'
@@ -1396,8 +1400,8 @@ class BrowserSession(BaseModel):
# if your cookies are frozen in time and don't update, they'll block you as a bot almost immediately
# if they pass a dict in it means they have to get the updated cookies manually with browser_context.cookies()
# and persist them manually on every change. most people don't realize they have to do that, so show a warning
- logger.warning(
- f'⚠️ {self} storage_state was set as a {type(self.browser_profile.storage_state)} and will not be updated with any cookie changes, use a json file path instead to persist changes'
+ self.logger.warning(
+ f'⚠️ storage_state was set as a {type(self.browser_profile.storage_state)} and will not be updated with any cookie changes, use a json file path instead to persist changes'
)
return
@@ -1415,7 +1419,7 @@ class BrowserSession(BaseModel):
if self.browser_profile.cookies_file:
# Show deprecation warning
- logger.warning(
+ self.logger.warning(
'⚠️ cookies_file is deprecated and will be removed in a future version. '
'Please use storage_state instead for loading cookies and other browser state. '
'See: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-storage-state'
@@ -1429,12 +1433,10 @@ class BrowserSession(BaseModel):
cookies_data = json.loads(cookies_path.read_text())
if cookies_data:
await self.browser_context.add_cookies(cookies_data)
- logger.info(
- f'🍪 {self} Loaded {len(cookies_data)} cookies from cookies_file= {_log_pretty_path(cookies_path)}'
- )
+ self.logger.info(f'🍪 Loaded {len(cookies_data)} cookies from cookies_file= {_log_pretty_path(cookies_path)}')
except Exception as e:
- logger.warning(
- f'❌ {self} Failed to load cookies from cookies_file= {_log_pretty_path(cookies_path)}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'❌ Failed to load cookies from cookies_file= {_log_pretty_path(cookies_path)}: {type(e).__name__}: {e}'
)
if self.browser_profile.storage_state:
@@ -1444,8 +1446,8 @@ class BrowserSession(BaseModel):
storage_state_text = await anyio.Path(storage_state).read_text()
storage_state = json.loads(storage_state_text)
except Exception as e:
- logger.warning(
- f'❌ {self} Failed to load cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'❌ Failed to load cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'
)
return
@@ -1456,12 +1458,12 @@ class BrowserSession(BaseModel):
# playwright doesn't provide an API for setting these before launch
# https://playwright.dev/python/docs/auth#session-storage
# await self.browser_context.add_local_storage(storage_state['localStorage'])
- logger.info(
- f'🍪 {self} Loaded {len(storage_state["cookies"])} cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}'
+ self.logger.info(
+ f'🍪 Loaded {len(storage_state["cookies"])} cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}'
)
except Exception as e:
- logger.warning(
- f'❌ {self} Failed to load cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'
+ self.logger.warning(
+ f'❌ Failed to load cookies from storage_state= {_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'
)
return
@@ -1584,7 +1586,7 @@ class BrowserSession(BaseModel):
nonlocal last_activity
pending_requests.add(request)
last_activity = asyncio.get_event_loop().time()
- # logger.debug(f'Request started: {request.url} ({request.resource_type})')
+ # self.logger.debug(f'Request started: {request.url} ({request.resource_type})')
async def on_response(response):
request = response.request
@@ -1625,7 +1627,7 @@ class BrowserSession(BaseModel):
nonlocal last_activity
pending_requests.remove(request)
last_activity = asyncio.get_event_loop().time()
- # logger.debug(f'Request resolved: {request.url} ({content_type})')
+ # self.logger.debug(f'Request resolved: {request.url} ({content_type})')
# Attach event listeners
page.on('request', on_request)
@@ -1644,7 +1646,7 @@ class BrowserSession(BaseModel):
):
break
if now - start_time > self.browser_profile.maximum_wait_page_load_time:
- logger.debug(
+ self.logger.debug(
f'{self} Network timeout after {self.browser_profile.maximum_wait_page_load_time}s with {len(pending_requests)} '
f'pending requests: {[r.url for r in pending_requests]}'
)
@@ -1657,7 +1659,7 @@ class BrowserSession(BaseModel):
elapsed = now - start_time
if elapsed > 1:
- logger.debug(f'💤 Page network traffic calmed down after {now - start_time:.2f} seconds')
+ self.logger.debug(f'💤 Page network traffic calmed down after {now - start_time:.2f} seconds')
async def _wait_for_page_and_frames_load(self, timeout_overwrite: float | None = None):
"""
@@ -1678,8 +1680,8 @@ class BrowserSession(BaseModel):
except URLNotAllowedError as e:
raise e
except Exception as e:
- logger.warning(
- f'⚠️ {self} Page load for {_log_pretty_url(page.url)} failed due to {type(e).__name__}, continuing anyway...'
+ self.logger.warning(
+ f'⚠️ Page load for {_log_pretty_url(page.url)} failed due to {type(e).__name__}, continuing anyway...'
)
# Calculate remaining time to meet minimum WAIT_TIME
@@ -1705,12 +1707,12 @@ class BrowserSession(BaseModel):
tab_idx = self.tabs.index(page)
if bytes_used is not None:
- logger.debug(
- f'➡️ {self} Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} used {bytes_used / 1024:.1f} KB in {elapsed:.2f}s, waiting +{remaining:.2f}s for all frames to finish'
+ self.logger.debug(
+ f'➡️ Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} used {bytes_used / 1024:.1f} KB in {elapsed:.2f}s, waiting +{remaining:.2f}s for all frames to finish'
)
else:
- logger.debug(
- f'➡️ {self} Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} took {elapsed:.2f}s, waiting +{remaining:.2f}s for all frames to finish'
+ self.logger.debug(
+ f'➡️ Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} took {elapsed:.2f}s, waiting +{remaining:.2f}s for all frames to finish'
)
# Sleep remaining time if needed
@@ -1754,11 +1756,11 @@ class BrowserSession(BaseModel):
async def _check_and_handle_navigation(self, page: Page) -> None:
"""Check if current page URL is allowed and handle if not."""
if not self._is_url_allowed(page.url):
- logger.warning(f'⛔️ {self} Navigation to non-allowed URL detected: {page.url}')
+ self.logger.warning(f'⛔️ Navigation to non-allowed URL detected: {page.url}')
try:
await self.go_back()
except Exception as e:
- logger.error(f'⛔️ {self} Failed to go back after detecting non-allowed URL: {type(e).__name__}: {e}')
+ self.logger.error(f'⛔️ Failed to go back after detecting non-allowed URL: {type(e).__name__}: {e}')
raise URLNotAllowedError(f'Navigation to non-allowed URL: {page.url}')
async def navigate_to(self, url: str):
@@ -1787,7 +1789,7 @@ class BrowserSession(BaseModel):
# await self._wait_for_page_and_frames_load(timeout_overwrite=1.0)
except Exception as e:
# Continue even if its not fully loaded, because we wait later for the page to load
- logger.debug(f'⏮️ {self} Error during go_back: {type(e).__name__}: {e}')
+ self.logger.debug(f'⏮️ Error during go_back: {type(e).__name__}: {e}')
async def go_forward(self):
"""Navigate the agent's tab forward in browser history"""
@@ -1796,7 +1798,7 @@ class BrowserSession(BaseModel):
await page.go_forward(timeout=10, wait_until='domcontentloaded')
except Exception as e:
# Continue even if its not fully loaded, because we wait later for the page to load
- logger.debug(f'⏭️ {self} Error during go_forward: {type(e).__name__}: {e}')
+ self.logger.debug(f'⏭️ Error during go_forward: {type(e).__name__}: {e}')
async def close_current_tab(self):
"""Close the current tab that the agent is working with.
@@ -1815,7 +1817,7 @@ class BrowserSession(BaseModel):
try:
await self.agent_current_page.close()
except Exception as e:
- logger.debug(f'⛔️ {self} Error during close_current_tab: {type(e).__name__}: {e}')
+ self.logger.debug(f'⛔️ Error during close_current_tab: {type(e).__name__}: {e}')
# Clear agent's reference to the closed tab
self.agent_current_page = None
@@ -1962,7 +1964,7 @@ class BrowserSession(BaseModel):
# Test if page is still accessible
await page.evaluate('1')
except Exception as e:
- logger.debug(f'👋 {self} Current page is no longer accessible: {type(e).__name__}: {e}')
+ self.logger.debug(f'👋 Current page is no longer accessible: {type(e).__name__}: {e}')
raise BrowserError('Browser closed: no valid pages available')
try:
@@ -1986,7 +1988,7 @@ class BrowserSession(BaseModel):
# if url in [tab.url for tab in tabs_info]:
# continue # skip if the iframe if we already have it open in a tab
# new_page_id = tabs_info[-1].page_id + 1
- # logger.debug(f'Opening cross-origin iframe in new tab #{new_page_id}: {url}')
+ # self.logger.debug(f'Opening cross-origin iframe in new tab #{new_page_id}: {url}')
# await self.create_new_tab(url)
# tabs_info.append(
# TabInfo(
@@ -2013,7 +2015,7 @@ class BrowserSession(BaseModel):
return self.browser_state_summary
except Exception as e:
- logger.error(f'❌ {self} Failed to update browser_state_summary: {type(e).__name__}: {e}')
+ self.logger.error(f'❌ Failed to update browser_state_summary: {type(e).__name__}: {e}')
# Return last known good state if available
if hasattr(self, 'browser_state_summary'):
return self.browser_state_summary
@@ -2046,8 +2048,8 @@ class BrowserSession(BaseModel):
screenshot_b64 = base64.b64encode(screenshot).decode('utf-8')
return screenshot_b64
except Exception as e:
- logger.error(
- f'❌ {self} Failed to take full-page screenshot: {type(e).__name__}: {e} falling back to viewport-only screenshot'
+ self.logger.error(
+ f'❌ Failed to take full-page screenshot: {type(e).__name__}: {e} falling back to viewport-only screenshot'
)
# Fallback method: manually expand the viewport and take a screenshot of the entire viewport
@@ -2337,8 +2339,8 @@ class BrowserSession(BaseModel):
return element_handle
return None
except Exception as e:
- logger.error(
- f'❌ {self} Failed to locate element {css_selector} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
+ self.logger.error(
+ f'❌ Failed to locate element {css_selector} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
)
return None
@@ -2360,7 +2362,7 @@ class BrowserSession(BaseModel):
return element_handle
return None
except Exception as e:
- logger.error(f'❌ {self} Failed to locate xpath {xpath} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}')
+ self.logger.error(f'❌ Failed to locate xpath {xpath} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}')
return None
@require_initialization
@@ -2381,8 +2383,8 @@ class BrowserSession(BaseModel):
return element_handle
return None
except Exception as e:
- logger.error(
- f'❌ {self} Failed to locate element {css_selector} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
+ self.logger.error(
+ f'❌ Failed to locate element {css_selector} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
)
return None
@@ -2405,15 +2407,15 @@ class BrowserSession(BaseModel):
elements = [el for el in elements if await self._is_visible(el)]
if not elements:
- logger.error(f"❌ {self} No visible element with text '{text}' found on page {_log_pretty_url(page.url)}.")
+ self.logger.error(f"❌ No visible element with text '{text}' found on page {_log_pretty_url(page.url)}.")
return None
if nth is not None:
if 0 <= nth < len(elements):
element_handle = elements[nth]
else:
- logger.error(
- f"❌ {self} Visible element with text '{text}' not found at index #{nth} on page {_log_pretty_url(page.url)}."
+ self.logger.error(
+ f"❌ Visible element with text '{text}' not found at index #{nth} on page {_log_pretty_url(page.url)}."
)
return None
else:
@@ -2424,8 +2426,8 @@ class BrowserSession(BaseModel):
await element_handle.scroll_into_view_if_needed()
return element_handle
except Exception as e:
- logger.error(
- f"❌ {self} Failed to locate element by text '{text}' on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}"
+ self.logger.error(
+ f"❌ Failed to locate element by text '{text}' on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}"
)
return None
@@ -2482,8 +2484,8 @@ class BrowserSession(BaseModel):
await page.keyboard.type(text)
except Exception as e:
- logger.debug(
- f'❌ {self} Failed to input text into element: {repr(element_node)} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'❌ Failed to input text into element: {repr(element_node)} on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
)
raise BrowserError(f'Failed to input text into index {element_node.highlight_index}')
@@ -2544,7 +2546,7 @@ class BrowserSession(BaseModel):
await new_page.goto(url, wait_until='domcontentloaded')
await self._wait_for_page_and_frames_load(timeout_overwrite=1)
except Exception as e:
- logger.error(f'❌ {self} Error navigating to {url}: {type(e).__name__}: {e}')
+ self.logger.error(f'❌ Error navigating to {url}: {type(e).__name__}: {e}')
assert self.human_current_page is not None
assert self.agent_current_page is not None
@@ -2666,8 +2668,8 @@ class BrowserSession(BaseModel):
except Exception as e:
page = await self.get_current_page()
- logger.debug(
- f'❌ {self} Error in find_file_upload_element_by_index(index={index}) on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
+ self.logger.debug(
+ f'❌ Error in find_file_upload_element_by_index(index={index}) on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'
)
return None
diff --git a/tests/ci/test_agent_emits_cloud_events.py b/tests/ci/test_agent_emits_cloud_events.py
index 7a8937669..ae84e17eb 100644
--- a/tests/ci/test_agent_emits_cloud_events.py
+++ b/tests/ci/test_agent_emits_cloud_events.py
@@ -8,7 +8,7 @@ emitted in the correct order during agent execution.
import base64
import json
import os
-from datetime import datetime
+from datetime import UTC, datetime
from unittest.mock import AsyncMock, MagicMock
from uuid import UUID
@@ -33,7 +33,6 @@ from browser_use import Agent
from browser_use.browser import BrowserSession
from browser_use.eventbus import (
BaseEvent,
- EventBus,
)
@@ -545,7 +544,10 @@ class TestCloudEventValidation:
# Should raise validation error for string too long
with pytest.raises(ValueError, match='String should have at most 5000 characters'):
CreateAgentTaskEvent(
- user_id='test', agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659', llm_model='test-model', task=long_task
+ user_id='test',
+ agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659',
+ llm_model='test-model',
+ task=long_task,
)
def test_all_events_have_required_base_fields(self):
@@ -553,27 +555,41 @@ class TestCloudEventValidation:
# Create a few events
events_to_test = [
CreateAgentSessionEvent(
- id='test-session',
- user_id='test-user',
+ id='0683fb03-c5da-79c9-8000-d3a39c47c651',
+ user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
browser_session_id='test-browser',
browser_session_live_url='https://example.com',
browser_session_cdp_url='ws://localhost:9222',
),
CreateAgentTaskEvent(
- user_id='test-user',
- agent_session_id='test-session',
+ id='0683fb03-c5da-79c9-8000-d3a39c47c652',
+ user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
+ agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c651',
task='test',
llm_model='gpt-4o',
),
CreateAgentStepEvent(
- user_id='test-user',
- agent_task_id='test-task',
+ user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
+ agent_task_id='0683fb03-c5da-79c9-8000-d3a39c47c652',
step=1,
evaluation_previous_goal='eval',
memory='mem',
next_goal='next',
actions=[],
),
+ CreateAgentOutputFileEvent(
+ user_id='test',
+ task_id='0683fb03-c5da-79c9-8000-d3a39c47c652',
+ file_name='test.txt',
+ file_content=base64.b64encode(b'test').decode(),
+ ),
+ UpdateAgentTaskEvent(
+ id='0683fb03-c5da-79c9-8000-d3a39c47c652',
+ user_id='test',
+ stopped=True,
+ done_output='Task completed',
+ finished_at=datetime.now(UTC),
+ ),
]
# Check all events have required fields
@@ -602,81 +618,3 @@ class TestCloudEventValidation:
# Should not be able to change event_type
with pytest.raises(ValueError):
event.event_type = 'DifferentType'
-
-
-class TestEventBusIntegration:
- """Test EventBus integration with cloud events"""
-
- async def test_eventbus_processes_all_cloud_events(self):
- """Test that EventBus can process all types of cloud events"""
- bus = EventBus()
-
- collected = []
-
- async def collect(event: BaseEvent):
- collected.append(event)
- return 'ok'
-
- bus.on('*', collect)
-
- try:
- # Emit one of each event type
- events = [
- CreateAgentSessionEvent(
- id='0683fb03-c5da-79c9-8000-d3a39c47c659',
- user_id='test',
- browser_session_id='session1',
- browser_session_live_url='https://example.com',
- browser_session_cdp_url='ws://localhost:9222',
- ),
- CreateAgentTaskEvent(
- user_id='test',
- agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659',
- llm_model='test-model',
- task='test task',
- ),
- CreateAgentStepEvent(
- user_id='test',
- agent_task_id='0683fb03-c5da-79c9-8000-d3a39c47c659',
- step=1,
- evaluation_previous_goal='eval',
- memory='memory',
- next_goal='goal',
- actions=[{'name': 'test'}],
- ),
- CreateAgentOutputFileEvent(
- user_id='test',
- task_id='0683fb03-c5da-79c9-8000-d3a39c47c659',
- file_name='test.txt',
- file_content=base64.b64encode(b'test').decode(),
- ),
- UpdateAgentTaskEvent(
- id='0683fb03-c5da-79c9-8000-d3a39c47c659',
- user_id='test',
- stopped=True,
- done_output='Task completed',
- finished_at=datetime.utcnow(),
- ),
- ]
-
- # Emit all events
- for event in events:
- bus.dispatch(event)
-
- # Wait for processing
- await bus.wait_until_idle()
-
- # Check all were collected
- assert len(collected) == len(events)
- event_types = {e.event_type for e in collected}
- expected_types = {
- 'CreateAgentSession',
- 'CreateAgentTask',
- 'CreateAgentStep',
- 'CreateAgentOutputFile',
- 'UpdateAgentTask',
- }
- assert event_types == expected_types
-
- finally:
- await bus.stop()