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
Add `record start/stop` CLI command for session video capture
Saurav Pandab1d933258cab
diff --git a/browser_use/browser/watchdogs/recording_watchdog.py b/browser_use/browser/watchdogs/recording_watchdog.pyindex a9b74f9e4..424b633b2 100644--- a/browser_use/browser/watchdogs/recording_watchdog.py+++ b/browser_use/browser/watchdogs/recording_watchdog.py@@ -36,29 +36,46 @@ class RecordingWatchdog(BaseWatchdog):if not profile.record_video_dir:return- # Dynamically determine video size- size = profile.record_video_size- if not size:- self.logger.debug('record_video_size not specified, detecting viewport size...')- size = await self._get_current_viewport_size()-- if not size:- self.logger.warning('Cannot start video recording: viewport size could not be determined.')- return-video_format = getattr(profile, 'record_video_format', 'mp4').strip('.')output_path = Path(profile.record_video_dir) / f'{uuid7str()}.{video_format}'+ await self.start_recording(output_path, size=profile.record_video_size, framerate=profile.record_video_framerate)++ async def start_recording(+ self,+ output_path: Path,+ size: ViewportSize | None = None,+ framerate: int | None = None,+ ) -> Path:+ """+ Begin recording the current session to `output_path`. Safe to call at any time+ after the browser has connected.- self.logger.debug(f'Initializing video recorder for format: {video_format}')- self._recorder = VideoRecorderService(output_path=output_path, size=size, framerate=profile.record_video_framerate)- self._recorder.start()+ Returns the resolved output path. Raises RuntimeError if recording is already active+ or if the viewport size could not be determined.+ """+ if self._recorder is not None:+ raise RuntimeError(f'Recording already in progress (output: {self._recorder.output_path})')- if not self._recorder._is_active:- self._recorder = None- return+ if size is None:+ self.logger.debug('record size not specified, detecting viewport size...')+ size = await self._get_current_viewport_size()+ if not size:+ raise RuntimeError('Cannot start video recording: viewport size could not be determined.')++ if framerate is None:+ framerate = self.browser_session.browser_profile.record_video_framerate++ output_path = Path(output_path)+ self.logger.debug(f'Initializing video recorder → {output_path}')+ recorder = VideoRecorderService(output_path=output_path, size=size, framerate=framerate)+ recorder.start()+ if not recorder._is_active:+ raise RuntimeError(+ 'Failed to initialize video recorder — ensure optional deps are installed (`pip install "browser-use[video]"`).'+ )+ self._recorder = recorderself.browser_session.cdp_client.register.Page.screencastFrame(self.on_screencastFrame)-self._screencast_params = {'format': 'png','quality': 90,@@ -66,8 +83,39 @@ class RecordingWatchdog(BaseWatchdog):'maxHeight': size['height'],'everyNthFrame': 1,}-await self._start_screencast()+ return output_path++ async def stop_recording(self) -> Path | None:+ """+ Stop any in-progress recording and finalize the output file.++ Returns the path of the saved video, or None if no recording was active.+ """+ if not self._recorder:+ return None++ recorder = self._recorder+ session_id = self._current_session_id+ self._recorder = None+ self._current_session_id = None+ self._screencast_params = None++ if session_id:+ try:+ await self.browser_session.cdp_client.send.Page.stopScreencast(session_id=session_id)+ except Exception as e:+ self.logger.debug(f'Failed to stop CDP screencast on {session_id}: {e}')++ output_path = recorder.output_path+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, recorder.stop_and_save)+ return output_path++ @property+ def is_recording(self) -> bool:+ """Whether a recording is currently in progress."""+ return self._recorder is not Noneasync def on_AgentFocusChangedEvent(self, event: AgentFocusChangedEvent) -> None:"""@@ -166,11 +214,5 @@ class RecordingWatchdog(BaseWatchdog):Stops the video recording and finalizes the video file."""if self._recorder:- recorder = self._recorder- self._recorder = None- self._current_session_id = None- self._screencast_params = None-self.logger.debug('Stopping video recording and saving file...')- loop = asyncio.get_event_loop()- await loop.run_in_executor(None, recorder.stop_and_save)+ await self.stop_recording()diff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.pyindex 221e45aad..5c824e893 100644--- a/browser_use/skill_cli/commands/browser.py+++ b/browser_use/skill_cli/commands/browser.py@@ -31,6 +31,7 @@ COMMANDS = {'dblclick','rightclick','get',+ 'record',}@@ -770,4 +771,57 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> Areturn {'error': 'Invalid get command. Use: title, html, text, value, attributes, bbox'}+ elif action == 'record':+ # CLIBrowserSession skips watchdogs by default — attach RecordingWatchdog lazily on first use.+ watchdog = getattr(bs, '_recording_watchdog', None)+ if watchdog is None:+ from browser_use.browser.watchdogs.recording_watchdog import RecordingWatchdog++ RecordingWatchdog.model_rebuild()+ watchdog = RecordingWatchdog(event_bus=bs.event_bus, browser_session=bs)+ bs._recording_watchdog = watchdog++ record_command = params.get('record_command')++ if record_command == 'start':+ path = params.get('path')+ if not path:+ return {'error': 'Usage: record start <output-path>'}+ if watchdog.is_recording:+ return {'error': 'Recording already in progress. Call `record stop` first.'}++ output_path = Path(path).expanduser()+ try:+ output_path.parent.mkdir(parents=True, exist_ok=True)+ except OSError as e:+ return {'error': f'Cannot create output directory {output_path.parent}: {e}'}++ framerate = params.get('framerate')+ try:+ saved = await watchdog.start_recording(output_path, framerate=framerate)+ except RuntimeError as e:+ return {'error': str(e)}+ return {'recording': True, 'path': str(saved)}++ elif record_command == 'stop':+ if not watchdog.is_recording:+ return {'error': 'No recording in progress'}+ saved = await watchdog.stop_recording()+ if saved is None:+ return {'error': 'No recording in progress'}+ return {'_raw_text': str(saved)}++ elif record_command == 'status':+ recorder = watchdog._recorder+ if recorder is None:+ return {'recording': False}+ return {+ 'recording': True,+ 'path': str(recorder.output_path),+ 'framerate': recorder.framerate,+ 'size': {'width': recorder.size['width'], 'height': recorder.size['height']},+ }++ return {'error': 'Invalid record command. Use: start <path>, stop, status'}+raise ValueError(f'Unknown browser action: {action}')diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex cbf4c36a0..2790f93cc 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -782,6 +782,17 @@ Setup:p = subparsers.add_parser('rightclick', help='Right-click element')p.add_argument('index', type=int, help='Element index')+ # record (start <path> | stop | status)+ record_p = subparsers.add_parser('record', help='Record browser session video (start/stop)')+ record_sub = record_p.add_subparsers(dest='record_command')++ p = record_sub.add_parser('start', help='Start recording to file (.mp4)')+ p.add_argument('path', help='Output video path (.mp4 recommended)')+ p.add_argument('--framerate', type=int, default=None, help='Framerate (default: 30)')++ record_sub.add_parser('stop', help='Stop recording and print saved file path')+ record_sub.add_parser('status', help='Show current recording status')+# -------------------------------------------------------------------------# Cookies Commands# -------------------------------------------------------------------------@@ -1454,6 +1465,8 @@ def main() -> int:# Resolve file paths to absolute before sending to daemon (daemon may have different CWD)if args.command == 'upload' and 'path' in params:params['path'] = str(Path(params['path']).expanduser().resolve())+ if args.command == 'record' and params.get('record_command') == 'start' and 'path' in params:+ params['path'] = str(Path(params['path']).expanduser().resolve())# Add profile to params for commands that need itif args.profile:diff --git a/tests/ci/test_action_record.py b/tests/ci/test_action_record.pynew file mode 100644index 000000000..1611fd8a1--- /dev/null+++ b/tests/ci/test_action_record.py@@ -0,0 +1,162 @@+"""Tests for the RecordingWatchdog start/stop API and the `browser-use record` CLI command.++The watchdog drives CDP screencast (`Page.startScreencast`/`stopScreencast`) and+`VideoRecorderService` (imageio+ffmpeg) to produce an MP4. These tests exercise+the full stack against a real headless browser.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++import pytest++try:+ import imageio.v2 as iio # type: ignore[import-not-found]++ IMAGEIO_AVAILABLE = True+except ImportError:+ IMAGEIO_AVAILABLE = False++from browser_use.browser.events import NavigateToUrlEvent+from browser_use.browser.profile import BrowserProfile+from browser_use.browser.session import BrowserSession++pytestmark = pytest.mark.skipif(+ not IMAGEIO_AVAILABLE,+ reason='Recording requires the [video] extra: pip install "browser-use[video]"',+)+++async def browser_session():+ session = BrowserSession(browser_profile=BrowserProfile(headless=True))+ await session.start()+ yield session+ await session.kill()+++def page_url(httpserver):+ httpserver.expect_request('/recpage').respond_with_data(+ """+ <html>+ <body style='background:#f0f;padding:40px;'>+ <h1 id='title'>Recording test</h1>+ <p>This content should appear in the captured video.</p>+ </body>+ </html>+ """,+ content_type='text/html',+ )+ return httpserver.url_for('/recpage')+++async def _drive_browser_briefly(bs: BrowserSession, url: str, ticks: int = 8) -> None:+ """Navigate + poke the page so screencast emits a few frames."""+ await bs.event_bus.dispatch(NavigateToUrlEvent(url=url, new_tab=False))+ # Screencast emits frames as the page changes; give it enough time to collect some+ for _ in range(ticks):+ await asyncio.sleep(0.15)+++async def test_start_stop_recording_produces_video(browser_session: BrowserSession, page_url: str, tmp_path: Path):+ """start_recording → activity → stop_recording should write a valid MP4."""+ watchdog = browser_session._recording_watchdog+ assert watchdog is not None, 'BrowserSession should always attach a RecordingWatchdog'++ out_path = tmp_path / 'session.mp4'+ assert not watchdog.is_recording++ saved = await watchdog.start_recording(out_path)+ assert saved == out_path+ assert watchdog.is_recording++ await _drive_browser_briefly(browser_session, page_url)++ final = await watchdog.stop_recording()+ assert final == out_path+ assert not watchdog.is_recording+ assert out_path.exists(), 'recording stop should leave a file on disk'+ assert out_path.stat().st_size > 0, 'recorded video must be non-empty'++ # Confirm the file is actually a decodable video with at least one frame.+ reader: Any = iio.get_reader(str(out_path))+ try:+ frame: Any = reader.get_next_data()+ assert frame is not None and frame.size > 0+ finally:+ reader.close()+++async def test_start_recording_twice_raises(browser_session: BrowserSession, tmp_path: Path):+ watchdog = browser_session._recording_watchdog+ assert watchdog is not None++ await watchdog.start_recording(tmp_path / 'first.mp4')+ try:+ with pytest.raises(RuntimeError, match='already in progress'):+ await watchdog.start_recording(tmp_path / 'second.mp4')+ finally:+ await watchdog.stop_recording()+++async def test_stop_without_start_returns_none(browser_session: BrowserSession):+ watchdog = browser_session._recording_watchdog+ assert watchdog is not None+ assert await watchdog.stop_recording() is None+++async def test_profile_record_video_dir_still_works(page_url: str, tmp_path: Path):+ """The existing event-driven flow (profile.record_video_dir) must keep working."""+ session = BrowserSession(+ browser_profile=BrowserProfile(headless=True, record_video_dir=tmp_path),+ )+ await session.start()+ try:+ watchdog = session._recording_watchdog+ assert watchdog is not None+ # on_BrowserConnectedEvent should have auto-started recording via the watchdog+ assert watchdog.is_recording, 'profile.record_video_dir should have auto-started recording'+ await _drive_browser_briefly(session, page_url)+ finally:+ await session.kill()++ # After kill, BrowserStopEvent should have finalized the video file into tmp_path+ videos = list(tmp_path.glob('*.mp4'))+ assert videos, f'expected at least one recorded mp4 in {tmp_path}'+ assert videos[0].stat().st_size > 0+++# ---------------------------------------------------------------------------+# CLI plumbing (argparse + command routing)+# ---------------------------------------------------------------------------+++def test_cli_argparse_record_start_stop():+ """`browser-use record start <path>` and `record stop` parse correctly."""+ from browser_use.skill_cli.main import build_parser++ parser = build_parser()++ args = parser.parse_args(['record', 'start', '/tmp/x.mp4'])+ assert args.command == 'record'+ assert args.record_command == 'start'+ assert args.path == '/tmp/x.mp4'++ args = parser.parse_args(['record', 'stop'])+ assert args.command == 'record'+ assert args.record_command == 'stop'++ args = parser.parse_args(['record', 'status'])+ assert args.command == 'record'+ assert args.record_command == 'status'+++def test_cli_record_is_routed_to_browser_handler():+ """Daemon dispatch should route 'record' to browser.handle()."""+ from browser_use.skill_cli.commands import browser as browser_cmd++ assert 'record' in browser_cmd.COMMANDS