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 gif tests
Nick Sweetingc73c87c9f415
diff --git a/browser_use/agent/gif.py b/browser_use/agent/gif.pyindex 99cc6ea19..9a5c18f6d 100644--- a/browser_use/agent/gif.py+++ b/browser_use/agent/gif.py@@ -8,6 +8,7 @@ import platformfrom typing import TYPE_CHECKINGfrom browser_use.agent.views import AgentHistoryList+from browser_use.browser.session import BLANK_PAGE_SCREENSHOT_PLACEHOLDERfrom browser_use.config import CONFIGif TYPE_CHECKING:@@ -60,6 +61,17 @@ def create_history_gif(logger.warning('No history or first screenshot to create GIF from')return+ # Find the first non-placeholder screenshot+ first_real_screenshot = None+ for item in history.history:+ if item.state.screenshot and item.state.screenshot != BLANK_PAGE_SCREENSHOT_PLACEHOLDER:+ first_real_screenshot = item.state.screenshot+ break++ if not first_real_screenshot:+ logger.warning('No valid screenshots found (all are placeholders)')+ return+# Try to load nicer fontstry:# Try different font options in order of preference@@ -116,7 +128,7 @@ def create_history_gif(if show_task and task:task_frame = _create_task_frame(task,- history.history[0].state.screenshot,+ first_real_screenshot,title_font, # type: ignoreregular_font, # type: ignorelogo,@@ -129,6 +141,10 @@ def create_history_gif(if not item.state.screenshot:continue+ # Skip placeholder screenshots from about:blank pages+ if item.state.screenshot == BLANK_PAGE_SCREENSHOT_PLACEHOLDER:+ continue+# Convert base64 screenshot to PIL Imageimg_data = base64.b64decode(item.state.screenshot)image = Image.open(io.BytesIO(img_data))diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex de734d28f..eeb12416d 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -1351,9 +1351,10 @@ class Agent(Generic[Context, AgentStructuredOutput]):create_history_gif(task=self.task, history=self.state.history, output_path=output_path)- # Emit output file generated event for GIF- output_event = await CreateAgentOutputFileEvent.from_agent_and_file(self, output_path)- self.eventbus.dispatch(output_event)+ # Only emit output file event if GIF was actually created+ if Path(output_path).exists():+ output_event = await CreateAgentOutputFileEvent.from_agent_and_file(self, output_path)+ self.eventbus.dispatch(output_event)# Wait briefly for cloud auth to start and print the URL, but don't block for completionif self.enable_cloud_sync and hasattr(self, 'cloud_sync'):diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex a0a28855b..9d585a122 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -26,6 +26,11 @@ from .utils import normalize_urlos.environ['PW_TEST_SCREENSHOT_NO_FONTS_READY'] = '1' # https://github.com/microsoft/playwright/issues/35972+# 4x4 white PNG placeholder for about:blank pages to save tokens+BLANK_PAGE_SCREENSHOT_PLACEHOLDER = (+ 'iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAFElEQVR4nGP8//8/AwwwMSAB3BwAlm4DBfIlvvkAAAAASUVORK5CYII='+)+import psutilfrom bubus.helpers import retryfrom playwright._impl._api_structures import ViewportSize@@ -3618,7 +3623,7 @@ class BrowserSession(BaseModel):# not an exception because there's no point in retrying if we hit this, its always pointless to screenshot about:blank# raise ValueError('Refusing to take unneeded screenshot of empty new tab page')# return a 4px*4px white png to avoid wasting tokens - instead of 1px*1px white png that was- return 'iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAFElEQVR4nGP8//8/AwwwMSAB3BwAlm4DBfIlvvkAAAAASUVORK5CYII='+ return BLANK_PAGE_SCREENSHOT_PLACEHOLDER# Always bring page to front before rendering, otherwise it crashes in some cases, not sure whytry:@@ -4099,7 +4104,17 @@ class BrowserSession(BaseModel):await element_handle.evaluate('el => {el.textContent = ""; el.value = "";}')await element_handle.type(text, delay=5, timeout=5_000) # Add 5 second timeoutelse:- await element_handle.fill(text, timeout=3_000) # Add 3 second timeout+ # Try fill() first for supported elements+ try:+ await element_handle.fill(text, timeout=3_000) # Add 3 second timeout+ except Exception as fill_error:+ # If fill() fails because element doesn't support it, try type() instead+ if 'not an <input>, <textarea>, <select>' in str(fill_error):+ self.logger.debug(f'Element does not support fill(), using type() instead: {fill_error}')+ await element_handle.evaluate('el => {el.textContent = ""; el.value = "";}')+ await element_handle.type(text, delay=5, timeout=5_000)+ else:+ raiseexcept Exception as e:self.logger.error(f'Error during input text into element: {type(e).__name__}: {e}')raise BrowserError(f'Failed to input text into element: {repr(element_node)}')diff --git a/tests/ci/test_browser_session_output_paths.py b/tests/ci/test_browser_session_output_paths.pyindex 8260219ca..fd61b4ec6 100644--- a/tests/ci/test_browser_session_output_paths.py+++ b/tests/ci/test_browser_session_output_paths.py@@ -189,14 +189,14 @@ class TestAgentRecordings:gif_files = list(Path.cwd().glob('*.gif'))assert len(gif_files) == 0, 'GIF file was created when generate_gif=False'elif generate_gif is True:- gif_files = list(Path.cwd().glob('agent_*.gif'))- assert len(gif_files) > 0, 'No GIF file was created when generate_gif=True'- # Clean up- for gif in gif_files:- gif.unlink()+ # With mock LLM that doesn't navigate, all screenshots will be about:blank placeholders+ # So no GIF will be created (this is expected behavior)+ gif_files = list(Path.cwd().glob('agent_history.gif'))+ assert len(gif_files) == 0, 'GIF should not be created when all screenshots are placeholders'else: # custom_pathassert expected_gif_path is not None, 'expected_gif_path should be set for custom_path'- assert expected_gif_path.exists(), f'GIF was not created at {expected_gif_path}'+ # With mock LLM that doesn't navigate, no GIF will be created+ assert not expected_gif_path.exists(), 'GIF should not be created when all screenshots are placeholders'finally:await browser_session.kill()