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 Rust PR review feedback
Magnus Müllerc7da2c0e1059
diff --git a/browser_use/browser/watchdogs/downloads_watchdog.py b/browser_use/browser/watchdogs/downloads_watchdog.pyindex c3ec80453..b9ea34cf5 100644--- a/browser_use/browser/watchdogs/downloads_watchdog.py+++ b/browser_use/browser/watchdogs/downloads_watchdog.py@@ -101,7 +101,7 @@ def _should_auto_download_network_response(return Falseif _is_generic_text_attachment(url, content_type, suggested_filename):return False- return _has_file_extension(suggested_filename) or _has_file_extension(url) or 'application/octet-stream' in content_type+ return Trueclass DownloadsWatchdog(BaseWatchdog):diff --git a/browser_use/rust/service.py b/browser_use/rust/service.pyindex 63475716b..58fc120ed 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -314,11 +314,7 @@ class RustSdkClient:if not self._handle_stdout_line(raw_line):returnif len(buffer) > self.max_line_bytes:- self._fail_all(- RustAgentError(- f'Rust SDK JSON-RPC line exceeded {self.max_line_bytes} bytes without newline'- )- )+ self._fail_all(RustAgentError(f'Rust SDK JSON-RPC line exceeded {self.max_line_bytes} bytes without newline'))returnexcept Exception as exc:message = f'Rust SDK stdout reader failed: {exc}'@@ -1215,10 +1211,7 @@ def _task_with_completed_initial_navigation_context(initial_action_urls.append(url)if initial_action_urls == urls:actions = json.dumps(initial_actions, indent=2, default=str)- prefix = (- f'Before the task, perform these Browser Use initial actions in order:\n{actions}\n\n'- 'Then complete the task.\n\n'- )+ prefix = f'Before the task, perform these Browser Use initial actions in order:\n{actions}\n\nThen complete the task.\n\n'if cleaned_task.startswith(prefix):cleaned_task = cleaned_task[len(prefix) :]completed = ', '.join(repr(url) for url in urls)@@ -2601,10 +2594,15 @@ def _browser_url(value: Any) -> str:def _internal_browser_endpoint_url(url: str) -> bool:parsed = urlparse(url)- return parsed.scheme in {'http', 'https'} and parsed.hostname in {'127.0.0.1', 'localhost', '::1'} and parsed.path in {- '',- '/',- }+ return (+ parsed.scheme in {'http', 'https'}+ and parsed.hostname in {'127.0.0.1', 'localhost', '::1'}+ and parsed.path+ in {+ '',+ '/',+ }+ )def _browser_state_candidates(value: Any) -> list[tuple[str, str, str]]:@@ -2617,7 +2615,11 @@ def _browser_state_candidates(value: Any) -> list[tuple[str, str, str]]:nested_target_id = ''if isinstance(raw_target, dict):nested_target_id = str(- raw_target.get('target_id') or raw_target.get('targetId') or raw_target.get('tab_id') or raw_target.get('tabId') or ''+ raw_target.get('target_id')+ or raw_target.get('targetId')+ or raw_target.get('tab_id')+ or raw_target.get('tabId')+ or '')target_id = str(value.get('target_id')@@ -3469,9 +3471,7 @@ def _terminal_laminar_semconv_messages(content = message.get('content')parts: list[dict[str, Any]]if isinstance(content, list):- parts = [- _terminal_laminar_semconv_content_part(part, inline_image_data=inline_image_data) for part in content- ]+ parts = [_terminal_laminar_semconv_content_part(part, inline_image_data=inline_image_data) for part in content]elif isinstance(content, str):parts = [{'type': 'text', 'content': content}]else:@@ -5180,7 +5180,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):returnfinished = time.time()self.last_stdout = str(getattr(sdk, 'stdout_text', '') or '')- self.last_stderr = str(getattr(sdk, 'stderr_text', '') or '\n'.join(line for line in getattr(sdk, 'stderr_lines', []) if line))+ self.last_stderr = str(+ getattr(sdk, 'stderr_text', '') or '\n'.join(line for line in getattr(sdk, 'stderr_lines', []) if line)+ )effective_error = process_errorif _result_from_events(events) is not None and (process_error == 'CancelledError' or _sdk_transport_error_after_final_result(process_error)@@ -5882,9 +5884,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):tab_url = str(tab.get('url') or '')if not tab_url:continue- initial_state_tabs.append(- TabInfo(url=tab_url, title=str(tab.get('title') or ''), target_id=f'initial-tab-{index}')- )+ initial_state_tabs.append(TabInfo(url=tab_url, title=str(tab.get('title') or ''), target_id=f'initial-tab-{index}'))state_history = BrowserStateHistory(url=initial_state_url,title=initial_state_title,@@ -6002,9 +6002,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):return False@staticmethod- def _direct_initial_navigation_state_context(- requested_url: str, state: BrowserStateSummary | None- ) -> dict[str, Any]:+ def _direct_initial_navigation_state_context(requested_url: str, state: BrowserStateSummary | None) -> dict[str, Any]:context: dict[str, Any] = {'requested_url': requested_url}if state is None:return contextdiff --git a/pyproject.toml b/pyproject.tomlindex a8aef9ced..5f9d65db5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -154,6 +154,9 @@ exclude = ["browser_use/llm/oci_raw/*","browser_use/llm/tests/test_chat_models.py","browser_use/llm/tests/test_single_step.py",+ # Dynamic Rust compatibility wrapper; covered by tests/ci/test_rust_agent.py.+ "browser_use/rust/service.py",+ "tests/ci/test_rust_agent.py","product_extraction.py","discover/","list/",diff --git a/tests/ci/test_downloads_watchdog.py b/tests/ci/test_downloads_watchdog.pyindex c416025d7..c673bbb81 100644--- a/tests/ci/test_downloads_watchdog.py+++ b/tests/ci/test_downloads_watchdog.py@@ -39,3 +39,13 @@ def test_downloads_watchdog_keeps_text_attachment_with_file_url():is_download_attachment=True,suggested_filename='f.txt',)+++def test_downloads_watchdog_keeps_attachment_without_known_extension():+ assert _should_auto_download_network_response(+ url='https://example.com/download?id=123',+ content_type='application/vnd.example.custom',+ is_pdf=False,+ is_download_attachment=True,+ suggested_filename='statement',+ )diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex c616decc5..0c81d2107 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -23,25 +23,6 @@ def _disable_rust_agent_latest_version_check(monkeypatch):monkeypatch.setenv('BROWSER_USE_API_KEY', 'test-browser-use-api-key')[email protected](autouse=True)-def _skip_removed_legacy_cli_process_tests(request):- if request.node.name == 'test_rust_agent_ignores_legacy_run_process_monkeypatch_for_sdk_server':- return- test_func = getattr(request.node, 'function', None)- if test_func is None:- return- source = inspect.getsource(test_func)- legacy_fragments = (- '._run_process',- '._load_events',- '_run_existing_argv',- '_load_events()',- 'run-codex-session',- )- if any(fragment in source for fragment in legacy_fragments):- pytest.skip('legacy Rust CLI process path removed; SDK-server tests cover the run path')--def test_top_level_agent_preserves_python_service():from browser_use import Agent as TopLevelAgentfrom browser_use.agent.service import Agent as BrowserUseAgent@@ -2872,9 +2853,7 @@ async def test_rust_agent_recovers_final_result_from_sdk_notifications_after_traself.notifications = [{'method': 'agent.event',- 'params': {- 'event': {'seq': 1, 'id': 'event-1', 'event_type': 'session.input', 'payload': {'text': 'task'}}- },+ 'params': {'event': {'seq': 1, 'id': 'event-1', 'event_type': 'session.input', 'payload': {'text': 'task'}}},},{'method': 'agent.event',@@ -3051,8 +3030,18 @@ async def test_rust_agent_prefers_notification_final_when_response_history_lacks'token_count',{'info': {- 'last_token_usage': {'input_tokens': 100, 'cached_input_tokens': 40, 'output_tokens': 10, 'total_tokens': 110},- 'total_token_usage': {'input_tokens': 100, 'cached_input_tokens': 40, 'output_tokens': 10, 'total_tokens': 110},+ 'last_token_usage': {+ 'input_tokens': 100,+ 'cached_input_tokens': 40,+ 'output_tokens': 10,+ 'total_tokens': 110,+ },+ 'total_token_usage': {+ 'input_tokens': 100,+ 'cached_input_tokens': 40,+ 'output_tokens': 10,+ 'total_tokens': 110,+ },}},),@@ -3061,7 +3050,12 @@ async def test_rust_agent_prefers_notification_final_when_response_history_lacks'token_count',{'info': {- 'last_token_usage': {'input_tokens': 200, 'cached_input_tokens': 60, 'output_tokens': 20, 'total_tokens': 220},+ 'last_token_usage': {+ 'input_tokens': 200,+ 'cached_input_tokens': 60,+ 'output_tokens': 20,+ 'total_tokens': 220,+ },'total_token_usage': {'input_tokens': 300,'cached_input_tokens': 100,@@ -3179,9 +3173,7 @@ async def test_rust_agent_preserves_sdk_notification_history_on_cancel(monkeypatself.notifications = [{'method': 'agent.event',- 'params': {- 'event': {'seq': 1, 'id': 'event-1', 'event_type': 'session.input', 'payload': {'text': 'task'}}- },+ 'params': {'event': {'seq': 1, 'id': 'event-1', 'event_type': 'session.input', 'payload': {'text': 'task'}}},},{'method': 'agent.event',@@ -4906,128 +4898,6 @@ def test_rust_agent_telemetry_records_cloud_cdp_hostname():assert captured_events[0].urls_visited == ['https://example.com']-async def test_rust_agent_run_records_terminal_telemetry(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- captured_events = []-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- class LLM:- model = 'gpt-test'- provider = 'test-provider'-- agent = Agent(task='Record telemetry.', llm=LLM(), source='ci')- agent.telemetry = Telemetry()-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [- {'event_type': 'browser.state', 'payload': {'url': 'https://example.com', 'title': 'Example'}},- {'event_type': 'model.usage', 'payload': {'input_tokens': 13, 'output_tokens': 5}},- {'event_type': 'session.done', 'payload': {'result': 'telemetry answer'}},- ]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=5)-- assert history.final_result() == 'telemetry answer'- assert len(captured_events) == 1- event = captured_events[0]- assert event.task == agent.task- assert event.max_steps == 5- assert event.model == 'gpt-test'- assert event.model_provider == 'test-provider'- assert event.urls_visited == ['https://example.com']- assert event.total_input_tokens == 13- assert event.total_output_tokens == 5- assert event.final_result_response == '"telemetry answer"'- assert event.error_message is None-- class FailingTelemetry:- def capture(self, event):- raise RuntimeError('telemetry failed')-- class RecordingLogger:- def __init__(self):- self.errors = []-- def info(self, message, *args, **kwargs):- pass-- def debug(self, message, *args, **kwargs):- pass-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- logger = RecordingLogger()- failing_agent = Agent(task='Record failing telemetry.', llm=LLM())- failing_agent.telemetry = FailingTelemetry()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- failing_agent._run_process = fake_run_process- failing_agent._load_events = fake_load_events-- failing_history = await failing_agent.run(max_steps=2)-- assert failing_history.final_result() == 'telemetry answer'- assert logger.errors == ['Failed to log telemetry event: telemetry failed']---async def test_rust_agent_run_logs_browser_use_run_metadata(monkeypatch):- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')-- async def latest_version():- return None-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- logger = RecordingLogger()- monkeypatch.setattr(rust_service, 'check_latest_browser_use_version', latest_version)- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))-- agent = Agent(task='Log run metadata.', llm=type('LLM', (), {'model': 'gpt-test'})())-- async def fake_run_process(argv, timeout_seconds=None):- assert any(message == '\033[34m🎯 Task: Log run metadata.\033[0m' for message in logger.infos)- assert any(message.startswith('🤖 Browser-Use Library Version') for message in logger.debugs)- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'logged metadata'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=1)-- assert history.final_result() == 'logged metadata'- assert logger.errors == []--async def test_rust_agent_run_metadata_logs_match_browser_use(monkeypatch):import browser_use.agent.service as agent_serviceimport browser_use.rust.service as rust_service@@ -5089,1585 +4959,173 @@ async def test_rust_agent_run_metadata_logs_match_browser_use(monkeypatch):assert rust_logger.infos[1].startswith('📦 Newer version available: 99.99.99')-async def test_rust_agent_run_logs_first_step_startup(monkeypatch):+async def test_rust_agent_exposes_step_finalization_helper_methods(tmp_path):+ import base64+ import time++ from browser_use.agent.views import ActionResult, AgentStepInfofrom browser_use.rust import Agent- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')+ class DomState:+ selector_map = {}- class LLM:- model = 'gpt-startup'- provider = 'startup-provider'+ class BrowserStateSummary:+ url = 'https://example.com/final'+ title = 'Final'+ tabs = []+ screenshot = base64.b64encode(b'png-bytes').decode('utf-8')+ dom_state = DomState()- class RecordingLogger:+ class EventBus:def __init__(self):- self.infos = []- self.debugs = []- self.errors = []+ self.dispatched = []- def info(self, message, *args, **kwargs):- self.infos.append(message)+ def dispatch(self, event):+ self.dispatched.append(event)+ return event- def debug(self, message, *args, **kwargs):- self.debugs.append(message)+ agent = Agent(task='Finalize helper parity.', file_system_path=str(tmp_path / 'agent-files'))+ agent.eventbus = EventBus()- def error(self, message, *args, **kwargs):- self.errors.append(message)+ await agent._handle_step_error(ValueError('bad step'))+ assert agent.state.consecutive_failures == 1+ assert agent.state.last_result is not None+ assert agent.state.last_result[-1].error == 'bad step'- logger = RecordingLogger()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Log startup metadata.', llm=LLM())+ await agent._post_process()+ assert agent.state.consecutive_failures == 2++ agent.state.last_result = [+ ActionResult(is_done=True, success=True, extracted_content='final answer', attachments=['file:///tmp/report.txt'])+ ]+ await agent._post_process()+ assert agent.state.consecutive_failures == 0- async def fake_run_process(argv, timeout_seconds=None):- assert (- f'Starting a browser-use agent with version {agent.version}, with provider=startup-provider and model=gpt-startup'- ) in logger.infos- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''+ agent.state.last_model_output = agent.AgentOutput(+ evaluation_previous_goal='Need answer',+ memory='Have answer',+ next_goal='Finish',+ action=[agent.ActionModel(done={'text': 'final answer', 'success': True})],+ )+ agent.step_start_time = time.time() - 0.1+ await agent._finalize(BrowserStateSummary())- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'logged startup'}}]+ assert agent.state.n_steps == 2+ assert agent.state.file_system_state is not None+ assert agent.history.final_result() == 'final answer'+ assert agent.history.urls() == ['https://example.com/final']+ assert Path(agent.history.history[0].state.screenshot_path).read_bytes() == b'png-bytes'+ assert [type(event).__name__ for event in agent.eventbus.dispatched] == ['CreateAgentStepEvent']+ assert agent.eventbus.dispatched[0].agent_task_id == str(agent.task_id)+ assert agent.eventbus.dispatched[0].actions == [{'done': {'text': 'final answer', 'success': True, 'files_to_display': []}}]+ assert agent.eventbus.dispatched[0].url == 'https://example.com/final'+ assert agent.eventbus.dispatched[0].screenshot_url.startswith('data:image/')+ assert ';base64,' in agent.eventbus.dispatched[0].screenshot_url- agent._run_process = fake_run_process- agent._load_events = fake_load_events+ await agent._force_done_after_last_step(AgentStepInfo(step_number=2, max_steps=3))+ assert agent.AgentOutput is agent.DoneAgentOutput- history = await agent.run(max_steps=1)+ agent.state.consecutive_failures = agent.settings.max_failures+ agent.AgentOutput = None+ await agent._force_done_after_failure()+ assert agent.AgentOutput is agent.DoneAgentOutput- assert history.final_result() == 'logged startup'- assert logger.errors == []+async def test_rust_agent_finalize_logs_step_completion_without_browser_state(monkeypatch, tmp_path):+ import time-async def test_rust_agent_run_logs_browser_use_setup_metadata(monkeypatch):+ from browser_use.agent.views import ActionResultfrom browser_use.rust import Agent- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')-class RecordingLogger:def __init__(self):- self.infos = []self.debugs = []- self.errors = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)def debug(self, message, *args, **kwargs):self.debugs.append(message)- def error(self, message, *args, **kwargs):- self.errors.append(message)+ class EventBus:+ def __init__(self):+ self.dispatched = []++ def dispatch(self, event):+ self.dispatched.append(event)+ return eventlogger = RecordingLogger()monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Log setup metadata.', llm=type('LLM', (), {'model': 'gpt-test'})())-- async def fake_run_process(argv, timeout_seconds=None):- expected = (- f'Agent setup: Agent Session ID {agent.session_id[-4:]}, Task ID {agent.task_id[-4:]}, '- f'Browser Session ID {agent.browser_session.id[-4:]} (launching local browser)'- )- assert expected in logger.debugs- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'logged setup'}}]+ agent = Agent(task='Finalize without browser state.', file_system_path=str(tmp_path / 'agent-files'))+ agent.eventbus = EventBus()+ agent.state.last_result = [ActionResult(extracted_content='ok')]+ agent.step_start_time = time.time() - 0.1+ starting_steps = agent.state.n_steps- agent._run_process = fake_run_process- agent._load_events = fake_load_events+ await agent._finalize(None)- history = await agent.run(max_steps=1)+ assert agent.state.n_steps == starting_steps + 1+ assert agent.state.file_system_state is not None+ assert agent.history.history == []+ assert agent.eventbus.dispatched == []+ assert any('Ran 1 action' in message and 'success=1' in message for message in logger.debugs)- assert history.final_result() == 'logged setup'- assert logger.errors == []+async def test_rust_agent_finalize_orders_summary_save_before_step_event(monkeypatch, tmp_path):+ import base64+ import time-async def test_rust_agent_run_logs_main_execution_start(monkeypatch):+ from browser_use.agent.views import ActionResultfrom browser_use.rust import Agent- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')+ calls = []class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-def debug(self, message, *args, **kwargs):- self.debugs.append(message)+ if 'Ran 1 action' in message:+ calls.append('summary')- def error(self, message, *args, **kwargs):- self.errors.append(message)+ class DomState:+ selector_map = {}- logger = RecordingLogger()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Log main execution start.', llm=type('LLM', (), {'model': 'gpt-test'})())+ class BrowserStateSummary:+ url = 'https://example.com/finalize-order'+ title = 'Finalize Order'+ tabs = []+ screenshot = base64.b64encode(b'png-bytes').decode('utf-8')+ dom_state = DomState()- async def fake_run_process(argv, timeout_seconds=None):- assert 'Starting main execution loop with max 6 steps...' in logger.debugs- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''+ class EventBus:+ def __init__(self):+ self.dispatched = []- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'logged execution start'}}]+ def dispatch(self, event):+ calls.append('dispatch')+ self.dispatched.append(event)+ return event- agent._run_process = fake_run_process- agent._load_events = fake_load_events+ logger = RecordingLogger()+ monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))+ agent = Agent(task='Finalize order parity.', file_system_path=str(tmp_path / 'agent-files'))+ agent.eventbus = EventBus()+ agent.state.last_result = [ActionResult(is_done=True, success=True, extracted_content='final answer')]+ agent.state.last_model_output = agent.AgentOutput(+ evaluation_previous_goal='Need answer',+ memory='Have answer',+ next_goal='Finish',+ action=[agent.ActionModel(done={'text': 'final answer', 'success': True})],+ )+ agent.step_start_time = time.time() - 0.1+ monkeypatch.setattr(agent, 'save_file_system_state', lambda: calls.append('save'))+ starting_steps = agent.state.n_steps- history = await agent.run(max_steps=6)+ await agent._finalize(BrowserStateSummary())- assert history.final_result() == 'logged execution start'- assert logger.errors == []+ assert calls == ['summary', 'save', 'dispatch']+ assert agent.state.n_steps == starting_steps + 1+ assert [type(event).__name__ for event in agent.eventbus.dispatched] == ['CreateAgentStepEvent']-async def test_rust_agent_run_follow_up_logs_main_execution_start(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- process_calls = []- load_count = 0-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- logger = RecordingLogger()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Log follow-up execution start.', llm=type('LLM', (), {'model': 'gpt-test'})())-- async def fake_run_process(argv, timeout_seconds=None):- process_calls.append(argv)- if len(process_calls) == 1:- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''- if len(process_calls) == 3:- assert argv[-3] == 'followup'- assert 'Starting main execution loop with max 5 steps...' in logger.debugs- return 0, '', ''-- async def fake_load_events():- nonlocal load_count- load_count += 1- return [{'event_type': 'session.done', 'payload': {'result': f'logged follow-up execution {load_count}'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=4)-- assert history.final_result() == 'logged follow-up execution 1'- logger.debugs.clear()- agent.add_new_task('Continue and log follow-up execution start.')-- history = await agent.run(max_steps=5)-- assert history.final_result() == 'logged follow-up execution 2'- assert len(process_calls) == 4- assert logger.errors == []---async def test_rust_agent_run_registers_browser_use_signal_handler(monkeypatch):- import asyncio-- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []- handlers = []- captured_events = []-- class FakeSignalHandler:- def __init__(- self,- loop=None,- pause_callback=None,- resume_callback=None,- custom_exit_callback=None,- exit_on_second_int=False,- interruptible_task_patterns=None,- ):- assert loop is asyncio.get_event_loop()- self.pause_callback = pause_callback- self.resume_callback = resume_callback- self.custom_exit_callback = custom_exit_callback- self.exit_on_second_int = exit_on_second_int- handlers.append(self)- events.append('init')-- def register(self):- events.append('register')-- def unregister(self):- events.append('unregister')-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- def flush(self):- events.append('flush')-- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- agent = Agent(task='Handle run signals.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.telemetry = Telemetry()- process_calls = 0-- async def fake_run_process(argv, timeout_seconds=None):- nonlocal process_calls- process_calls += 1- assert events in (['init', 'register'], ['init', 'register', 'flush'])- assert len(handlers) == 1- assert handlers[0].exit_on_second_int is True- if process_calls == 1:- handlers[0].pause_callback()- assert agent.state.paused is True- handlers[0].resume_callback()- assert agent.state.paused is False- handlers[0].custom_exit_callback()- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'handled signals'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=4)-- assert history.final_result() == 'handled signals'- assert events == ['init', 'register', 'flush', 'unregister']- assert len(captured_events) == 1- assert captured_events[0].max_steps == 4- assert captured_events[0].error_message == 'SIGINT: Cancelled by user'---async def test_rust_agent_run_waits_for_resume_before_terminal(monkeypatch):- import asyncio-- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []-- class FakeSignalHandler:- def __init__(self, **kwargs):- events.append('init_signal')-- def register(self):- events.append('register_signal')-- def unregister(self):- events.append('unregister_signal')-- def reset(self):- events.append('reset_signal')-- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- agent = Agent(task='Wait for resume before running.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.pause()-- async def fake_run_process(argv, timeout_seconds=None):- events.append(('run_process', agent.state.paused, timeout_seconds))- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'resumed run'}}]-- async def on_step_start(callback_agent):- events.append(('start', callback_agent.state.paused))-- def on_step_end(callback_agent):- events.append(('end', callback_agent.history.final_result()))-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- run_task = asyncio.create_task(agent.run(max_steps=4, on_step_start=on_step_start, on_step_end=on_step_end))- for _ in range(20):- await asyncio.sleep(0)- if 'register_signal' in events:- break-- assert 'register_signal' in events- assert run_task.done() is False- assert [event for event in events if isinstance(event, tuple)] == []-- agent.resume()- history = await asyncio.wait_for(run_task, timeout=2)-- assert history.final_result() == 'resumed run'- assert events == [- 'init_signal',- 'register_signal',- 'reset_signal',- ('start', False),- ('run_process', False, agent.settings.step_timeout),- ('run_process', False, agent.settings.step_timeout),- ('end', 'resumed run'),- 'unregister_signal',- ]---async def test_rust_agent_run_stopped_before_terminal_skips_step_hooks(monkeypatch):- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []- captured_events = []-- class FakeSignalHandler:- def __init__(self, **kwargs):- events.append('init_signal')-- def register(self):- events.append('register_signal')-- def unregister(self):- events.append('unregister_signal')-- class TokenCostService:- async def log_usage_summary(self):- events.append('usage_summary')-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- agent = Agent(task='Stop before terminal run.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.token_cost_service = TokenCostService()- agent.telemetry = Telemetry()- agent.stop()-- async def fake_run_process(argv, timeout_seconds=None):- events.append('run_process')- raise AssertionError('terminal process should not start')-- async def on_step_start(callback_agent):- events.append('start')-- def on_step_end(callback_agent):- events.append('end')-- agent._run_process = fake_run_process-- history = await agent.run(max_steps=3, on_step_start=on_step_start, on_step_end=on_step_end)-- assert history.errors() == ['Rust agent stopped before terminal run.']- assert events == ['init_signal', 'register_signal', 'usage_summary', 'unregister_signal']- assert agent.state.stopped is True- assert len(captured_events) == 1- assert captured_events[0].max_steps == 3- assert captured_events[0].error_message == 'Rust agent stopped before terminal run.'---async def test_rust_agent_run_finalizes_after_terminal_exception(monkeypatch):- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []- captured_events = []-- class FakeSignalHandler:- def __init__(self, **kwargs):- events.append('init_signal')-- def register(self):- events.append('register_signal')-- def unregister(self):- events.append('unregister_signal')-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []- self.warnings = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- def warning(self, message, *args, **kwargs):- self.warnings.append(message)-- class BrowserProfile:- keep_alive = False- viewport = {'width': 1280, 'height': 720}- user_agent = None- headless = True- allowed_domains = []-- class BrowserSession:- id = 'browser-session-1234'- browser_profile = BrowserProfile()- cdp_url = None-- def __init__(self):- self.kill_calls = 0-- async def kill(self):- events.append('kill_browser')- self.kill_calls += 1-- class TokenCostService:- async def log_usage_summary(self):- events.append('usage_summary')-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- session = BrowserSession()- logger = RecordingLogger()- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Clean up failed terminal run.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)- agent.token_cost_service = TokenCostService()- agent.telemetry = Telemetry()-- async def fake_run_process(argv, timeout_seconds=None):- events.append('run_process')- raise RuntimeError('terminal exploded')-- agent._run_process = fake_run_process-- with pytest.raises(RuntimeError, match='terminal exploded'):- await agent.run(max_steps=7)-- assert events == ['init_signal', 'register_signal', 'run_process', 'usage_summary', 'unregister_signal', 'kill_browser']- assert session.kill_calls == 1- assert getattr(agent, '_run_signal_handler') is None- assert len(captured_events) == 1- assert captured_events[0].max_steps == 7- assert captured_events[0].error_message == 'terminal exploded'- assert logger.errors[0] == 'Agent run failed with exception: terminal exploded'---async def test_rust_agent_run_initializes_lifecycle_before_start_callback_error(monkeypatch):- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []- dispatched = []- captured_events = []-- class FakeSignalHandler:- def __init__(self, **kwargs):- events.append('init_signal')-- def register(self):- events.append('register_signal')-- def unregister(self):- events.append('unregister_signal')-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []- self.warnings = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- def warning(self, message, *args, **kwargs):- self.warnings.append(message)-- class EventBus:- def dispatch(self, event):- dispatched.append(event)- return event-- class BrowserProfile:- keep_alive = False- viewport = {'width': 1280, 'height': 720}- user_agent = None- headless = True- allowed_domains = []-- class BrowserSession:- id = 'browser-session-1234'- browser_profile = BrowserProfile()- cdp_url = None-- def __init__(self):- self.kill_calls = 0-- async def kill(self):- events.append('kill_browser')- self.kill_calls += 1-- class TokenCostService:- async def log_usage_summary(self):- events.append('usage_summary')-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- session = BrowserSession()- logger = RecordingLogger()- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Fail from start callback.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)- agent.eventbus = EventBus()- agent.token_cost_service = TokenCostService()- agent.telemetry = Telemetry()-- async def fake_run_process(argv, timeout_seconds=None):- events.append('run_process')- raise AssertionError('terminal process should not start')-- async def on_step_start(callback_agent):- events.append('start_callback')- assert callback_agent is agent- raise RuntimeError('start callback failed')-- agent._run_process = fake_run_process-- with pytest.raises(RuntimeError, match='start callback failed'):- await agent.run(max_steps=3, on_step_start=on_step_start)-- assert events == ['init_signal', 'register_signal', 'start_callback', 'usage_summary', 'unregister_signal', 'kill_browser']- assert [type(event).__name__ for event in dispatched] == [- 'CreateAgentSessionEvent',- 'CreateAgentTaskEvent',- 'UpdateAgentTaskEvent',- ]- assert session.kill_calls == 1- assert getattr(agent, '_run_signal_handler') is None- assert len(captured_events) == 1- assert captured_events[0].max_steps == 3- assert captured_events[0].error_message == 'start callback failed'- assert logger.errors[0] == 'Agent run failed with exception: start callback failed'---async def test_rust_agent_run_finalizes_after_cancellation(monkeypatch):- import asyncio-- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []- captured_events = []-- class FakeSignalHandler:- def __init__(self, **kwargs):- events.append('init_signal')-- def register(self):- events.append('register_signal')-- def unregister(self):- events.append('unregister_signal')-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []- self.warnings = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- def warning(self, message, *args, **kwargs):- self.warnings.append(message)-- class BrowserProfile:- keep_alive = False- viewport = {'width': 1280, 'height': 720}- user_agent = None- headless = True- allowed_domains = []-- class BrowserSession:- id = 'browser-session-1234'- browser_profile = BrowserProfile()- cdp_url = None-- def __init__(self):- self.kill_calls = 0-- async def kill(self):- events.append('kill_browser')- self.kill_calls += 1-- class TokenCostService:- async def log_usage_summary(self):- events.append('usage_summary')-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- session = BrowserSession()- logger = RecordingLogger()- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Cancel terminal run.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)- agent.token_cost_service = TokenCostService()- agent.telemetry = Telemetry()-- async def fake_run_process(argv, timeout_seconds=None):- events.append('run_process')- raise asyncio.CancelledError-- agent._run_process = fake_run_process-- with pytest.raises(asyncio.CancelledError):- await agent.run(max_steps=7)-- assert events == ['init_signal', 'register_signal', 'run_process', 'usage_summary', 'unregister_signal', 'kill_browser']- assert session.kill_calls == 1- assert getattr(agent, '_run_signal_handler') is None- assert len(captured_events) == 1- assert captured_events[0].max_steps == 7- assert captured_events[0].error_message == 'CancelledError'- assert logger.errors == []---async def test_rust_agent_run_finalizes_after_startup_cancellation(monkeypatch):- import asyncio-- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []- dispatched = []- captured_events = []-- class FakeSignalHandler:- def __init__(self, **kwargs):- events.append('init_signal')-- def register(self):- events.append('register_signal')-- def unregister(self):- events.append('unregister_signal')-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []- self.warnings = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- def warning(self, message, *args, **kwargs):- self.warnings.append(message)-- class EventBus:- def dispatch(self, event):- dispatched.append(event)- return event-- class BrowserProfile:- keep_alive = False- viewport = {'width': 1280, 'height': 720}- user_agent = None- headless = True- allowed_domains = []-- class BrowserSession:- id = 'browser-session-1234'- browser_profile = BrowserProfile()- cdp_url = None-- def __init__(self):- self.kill_calls = 0-- async def kill(self):- events.append('kill_browser')- self.kill_calls += 1-- class TokenCostService:- async def log_usage_summary(self):- events.append('usage_summary')-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- session = BrowserSession()- logger = RecordingLogger()- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Cancel during startup.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)- agent.eventbus = EventBus()- agent.token_cost_service = TokenCostService()- agent.telemetry = Telemetry()-- async def fake_log_agent_run():- events.append('log_agent_run')- raise asyncio.CancelledError-- async def fake_run_process(argv, timeout_seconds=None):- raise AssertionError('terminal process should not start')-- agent._log_agent_run = fake_log_agent_run- agent._run_process = fake_run_process-- with pytest.raises(asyncio.CancelledError):- await agent.run(max_steps=7)-- assert events == ['init_signal', 'register_signal', 'log_agent_run', 'usage_summary', 'unregister_signal', 'kill_browser']- assert [type(event).__name__ for event in dispatched] == [- 'CreateAgentSessionEvent',- 'CreateAgentTaskEvent',- 'UpdateAgentTaskEvent',- ]- assert agent.state.session_initialized is True- assert agent._task_start_time == agent._session_start_time- assert session.kill_calls == 1- assert getattr(agent, '_run_signal_handler') is None- assert len(captured_events) == 1- assert captured_events[0].max_steps == 7- assert captured_events[0].error_message == 'CancelledError'- assert logger.errors == []---async def test_rust_agent_follow_up_finalizes_after_terminal_exception(monkeypatch):- import browser_use.rust.service as rust_service- from browser_use.rust import Agent- from browser_use.rust.service import RustAgentError-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []- captured_events = []-- class FakeSignalHandler:- def __init__(self, **kwargs):- events.append('init_signal')-- def register(self):- events.append('register_signal')-- def unregister(self):- events.append('unregister_signal')-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []- self.warnings = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- def warning(self, message, *args, **kwargs):- self.warnings.append(message)-- class BrowserProfile:- keep_alive = False- viewport = {'width': 1280, 'height': 720}- user_agent = None- headless = True- allowed_domains = []-- class BrowserSession:- id = 'browser-session-1234'- browser_profile = BrowserProfile()- cdp_url = None-- def __init__(self):- self.kill_calls = 0-- async def kill(self):- events.append('kill_browser')- self.kill_calls += 1-- class TokenCostService:- async def log_usage_summary(self):- events.append('usage_summary')-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- session = BrowserSession()- logger = RecordingLogger()- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Continue failed terminal run.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)- agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'- agent.token_cost_service = TokenCostService()- agent.telemetry = Telemetry()-- async def fake_run_process(argv, timeout_seconds=None):- events.append('run_process')- return 1, '', 'followup exploded'-- agent._run_process = fake_run_process-- with pytest.raises(RustAgentError, match='followup exploded'):- await agent.follow_up('Continue the task.', max_steps=5)-- assert events == ['init_signal', 'register_signal', 'run_process', 'usage_summary', 'unregister_signal', 'kill_browser']- assert session.kill_calls == 1- assert getattr(agent, '_run_signal_handler') is None- assert len(captured_events) == 1- assert captured_events[0].max_steps == 5- assert captured_events[0].error_message == 'followup exploded'- assert logger.errors[0] == 'Agent follow-up failed with exception: followup exploded'---async def test_rust_agent_follow_up_finalizes_after_keyboard_interrupt(monkeypatch):- import browser_use.rust.service as rust_service- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- events = []- captured_events = []-- class FakeSignalHandler:- def __init__(self, **kwargs):- events.append('init_signal')-- def register(self):- events.append('register_signal')-- def unregister(self):- events.append('unregister_signal')-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []- self.warnings = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- def warning(self, message, *args, **kwargs):- self.warnings.append(message)-- class BrowserProfile:- keep_alive = False- viewport = {'width': 1280, 'height': 720}- user_agent = None- headless = True- allowed_domains = []-- class BrowserSession:- id = 'browser-session-1234'- browser_profile = BrowserProfile()- cdp_url = None-- def __init__(self):- self.kill_calls = 0-- async def kill(self):- events.append('kill_browser')- self.kill_calls += 1-- class TokenCostService:- async def log_usage_summary(self):- events.append('usage_summary')-- class Telemetry:- def capture(self, event):- captured_events.append(event)-- session = BrowserSession()- logger = RecordingLogger()- monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Interrupt terminal follow-up.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)- agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'- agent.token_cost_service = TokenCostService()- agent.telemetry = Telemetry()-- async def fake_run_process(argv, timeout_seconds=None):- events.append('run_process')- raise KeyboardInterrupt-- agent._run_process = fake_run_process-- history = await agent.follow_up('Continue the task.', max_steps=5)-- assert history is agent.history- assert events == ['init_signal', 'register_signal', 'run_process', 'usage_summary', 'unregister_signal', 'kill_browser']- assert session.kill_calls == 1- assert getattr(agent, '_run_signal_handler') is None- assert len(captured_events) == 1- assert captured_events[0].max_steps == 5- assert captured_events[0].error_message == 'KeyboardInterrupt'- assert 'Got KeyboardInterrupt during execution, returning current history' in logger.debugs- assert logger.errors == []---async def test_rust_agent_run_logs_token_usage_summary(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- seen = []-- class TokenCostService:- async def log_usage_summary(self):- seen.append(('usage_summary', agent.history.final_result()))-- class Telemetry:- def capture(self, event):- seen.append(('telemetry', event.final_result_response))-- agent = Agent(task='Log usage summary.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.token_cost_service = TokenCostService()- agent.telemetry = Telemetry()-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'usage summary answer'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=3)-- assert history.final_result() == 'usage summary answer'- assert seen == [- ('usage_summary', 'usage summary answer'),- ('telemetry', '"usage summary answer"'),- ]---async def test_rust_agent_run_logs_final_outcome_guidance(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')-- class RecordingLogger:- def __init__(self):- self.infos = []- self.errors = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- pass-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- logger = RecordingLogger()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))-- class Telemetry:- def capture(self, event):- pass-- agent = Agent(task='Handle failed terminal run.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.telemetry = Telemetry()-- async def fake_run_process(argv, timeout_seconds=None):- return 1, 'Session: 12345678-1234-1234-1234-123456789abc\n', 'terminal failed'-- async def fake_load_events():- return []-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=1)-- assert history.errors() == ['terminal failed']- assert 'Did the Agent not work as expected? Let us fix this!' in logger.infos- assert ' Please open a short issue here: https://github.com/browser-use/browser-use/issues' in logger.infos---async def test_rust_agent_run_initializes_browser_use_session_state(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(task='Initialize session state.', llm=type('LLM', (), {'model': 'gpt-test'})())-- assert agent.state.session_initialized is False- assert not hasattr(agent, '_session_start_time')- assert not hasattr(agent, '_task_start_time')-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'initialized'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=4)-- assert history.final_result() == 'initialized'- assert agent.state.session_initialized is True- assert agent._session_start_time > 0- assert agent._task_start_time == agent._session_start_time---async def test_rust_agent_run_dispatches_browser_use_lifecycle_events(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- dispatched = []- load_count = 0-- class EventBus:- def dispatch(self, event):- dispatched.append(event)- return event-- agent = Agent(task='Dispatch lifecycle events.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.eventbus = EventBus()-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- nonlocal load_count- load_count += 1- return [{'event_type': 'session.done', 'payload': {'result': f'dispatched {load_count}'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=4)-- assert history.final_result() == 'dispatched 1'- assert [type(event).__name__ for event in dispatched] == [- 'CreateAgentSessionEvent',- 'CreateAgentTaskEvent',- 'UpdateAgentTaskEvent',- ]- assert dispatched[0].id == str(agent.session_id)- assert dispatched[1].id == str(agent.task_id)- assert dispatched[1].llm_model == 'gpt-test'- assert dispatched[2].id == str(agent.task_id)- assert dispatched[2].done_output == 'dispatched 1'-- dispatched.clear()- history = await agent.run(max_steps=4)-- assert history.final_result() == 'dispatched 2'- assert [type(event).__name__ for event in dispatched] == ['CreateAgentTaskEvent', 'UpdateAgentTaskEvent']- assert dispatched[0].llm_model == 'gpt-test'- assert dispatched[1].done_output == 'dispatched 2'---async def test_rust_agent_run_follow_up_dispatches_single_task_lifecycle(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- dispatched = []- process_calls = []- load_count = 0-- class EventBus:- def dispatch(self, event):- dispatched.append(event)- return event-- agent = Agent(task='Start lifecycle follow-up.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.eventbus = EventBus()-- async def fake_run_process(argv, timeout_seconds=None):- process_calls.append(argv)- if len(process_calls) == 1:- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''- return 0, '', ''-- async def fake_load_events():- nonlocal load_count- load_count += 1- return [{'event_type': 'session.done', 'payload': {'result': f'lifecycle follow-up {load_count}'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=4)-- assert history.final_result() == 'lifecycle follow-up 1'- assert [type(event).__name__ for event in dispatched] == [- 'CreateAgentSessionEvent',- 'CreateAgentTaskEvent',- 'UpdateAgentTaskEvent',- ]-- dispatched.clear()- agent.add_new_task('Continue the lifecycle follow-up.')- agent.eventbus = EventBus()-- history = await agent.run(max_steps=4)-- assert history.final_result() == 'lifecycle follow-up 2'- assert len(process_calls) == 4- assert process_calls[2][-3] == 'followup'- assert [type(event).__name__ for event in dispatched] == ['CreateAgentTaskEvent', 'UpdateAgentTaskEvent']- assert dispatched[0].llm_model == 'gpt-test'- assert dispatched[1].done_output == 'lifecycle follow-up 2'---async def test_rust_agent_run_follow_up_invokes_on_step_end(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- callbacks = []- process_calls = []- load_count = 0- agent = Agent(task='Start follow-up callbacks.', llm=type('LLM', (), {'model': 'gpt-test'})())-- async def fake_run_process(argv, timeout_seconds=None):- process_calls.append(argv)- if len(process_calls) == 1:- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''- return 0, '', ''-- async def fake_load_events():- nonlocal load_count- load_count += 1- return [{'event_type': 'session.done', 'payload': {'result': f'callback follow-up {load_count}'}}]-- async def on_step_start(callback_agent):- callbacks.append(('start', callback_agent.task))-- def on_step_end(callback_agent):- callbacks.append(('end', callback_agent.history.final_result()))-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=4, on_step_start=on_step_start, on_step_end=on_step_end)-- assert history.final_result() == 'callback follow-up 1'- assert callbacks == [('start', 'Start follow-up callbacks.'), ('end', 'callback follow-up 1')]-- callbacks.clear()- agent.add_new_task('Continue follow-up callbacks.')-- history = await agent.run(max_steps=4, on_step_start=on_step_start, on_step_end=on_step_end)-- assert history.final_result() == 'callback follow-up 2'- assert callbacks == [('start', 'Continue follow-up callbacks.'), ('end', 'callback follow-up 2')]- assert len(process_calls) == 4- assert process_calls[2][-3] == 'followup'---async def test_rust_agent_direct_follow_up_updates_task_state_and_transcript(tmp_path, monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- process_calls = []- load_count = 0- step_numbers = []-- def new_step_callback(browser_state, model_output, step_number):- step_numbers.append(step_number)-- agent = Agent(- task='Start direct follow-up state.',- llm=type('LLM', (), {'model': 'gpt-test'})(),- task_id='direct-followup',- save_conversation_path=tmp_path,- register_new_step_callback=new_step_callback,- )- starting_steps = agent.state.n_steps-- async def fake_run_process(argv, timeout_seconds=None):- process_calls.append(argv)- if len(process_calls) == 1:- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''- if len(process_calls) == 3:- return 0, 'followup accepted\n', 'followup stderr\n'- return 0, 'rerun stdout\n', 'rerun stderr\n'-- async def fake_load_events():- nonlocal load_count- load_count += 1- return [{'event_type': 'session.done', 'payload': {'result': f'direct follow-up {load_count}'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- initial = await agent.run(max_steps=3)- history = await agent.follow_up('Direct raw follow-up task.', max_steps=4)-- assert initial.final_result() == 'direct follow-up 1'- assert history.final_result() == 'direct follow-up 2'- assert agent.task == 'Direct raw follow-up task.'- assert agent.state.follow_up_task is False- assert '<follow_up_user_request> Direct raw follow-up task. </follow_up_user_request>' in agent.message_manager.task- assert process_calls[2][-3:] == [- 'followup',- '12345678-1234-1234-1234-123456789abc',- 'Direct raw follow-up task.',- ]- assert step_numbers == [starting_steps + 1, starting_steps + 2]- assert agent.state.n_steps == starting_steps + 2- assert agent.last_stdout == 'followup accepted\nrerun stdout'- assert agent.last_stderr == 'followup stderr\nrerun stderr'-- files = sorted(tmp_path.glob('conversation_direct-followup_*.json'))- assert [path.name for path in files] == [- f'conversation_direct-followup_{starting_steps + 1}.json',- f'conversation_direct-followup_{starting_steps + 2}.json',- ]- initial_snapshot = json.loads(files[0].read_text(encoding='utf-8'))- follow_up_snapshot = json.loads(files[1].read_text(encoding='utf-8'))- assert initial_snapshot['task'] == 'Start direct follow-up state.'- assert initial_snapshot['final_result'] == 'direct follow-up 1'- assert follow_up_snapshot['task'] == 'Direct raw follow-up task.'- assert follow_up_snapshot['stdout'] == 'followup accepted\nrerun stdout'- assert follow_up_snapshot['stderr'] == 'followup stderr\nrerun stderr'---async def test_rust_agent_follow_up_allows_timeout_overrides(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(task='Summarize current evidence.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'- process_calls = []-- async def fake_run_process(argv, timeout_seconds=None):- process_calls.append((argv, timeout_seconds))- return 0, 'ok\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'finalized answer'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.follow_up(- 'Return the final answer from gathered evidence.',- max_steps=2,- step_timeout=45,- enqueue_timeout=10,- )-- assert history.final_result() == 'finalized answer'- assert len(process_calls) == 2- assert process_calls[0][0][-3:] == [- 'followup',- '12345678-1234-1234-1234-123456789abc',- 'Return the final answer from gathered evidence.',- ]- assert process_calls[0][1] == 10- assert 'max_turns=2' in process_calls[1][0]- assert process_calls[1][1] == 45---async def test_rust_agent_load_events_uses_bounded_terminal_timeout(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- monkeypatch.setenv('BROWSER_USE_RUST_EVENTS_TIMEOUT_SECONDS', '7')- agent = Agent(task='Load terminal events.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'- seen = {}-- async def fake_run_process(argv, timeout_seconds=None):- seen['argv'] = argv- seen['timeout_seconds'] = timeout_seconds- return 0, '{"event_type":"session.done","payload":{"result":"answer"}}\nnot-json\n', ''-- agent._run_process = fake_run_process-- events = await agent._load_events()-- assert seen['argv'][-2:] == ['events', '12345678-1234-1234-1234-123456789abc']- assert seen['timeout_seconds'] == 7- assert events == [{'event_type': 'session.done', 'payload': {'result': 'answer'}}]---async def test_rust_agent_run_logs_browser_use_lifecycle_dispatch(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- dispatched = []- run_count = 0-- class RecordingLogger:- def __init__(self):- self.infos = []- self.debugs = []- self.errors = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- def error(self, message, *args, **kwargs):- self.errors.append(message)-- class EventBus:- def dispatch(self, event):- dispatched.append(event)- return event-- logger = RecordingLogger()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Log lifecycle dispatch.', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.eventbus = EventBus()-- async def fake_run_process(argv, timeout_seconds=None):- nonlocal run_count- run_count += 1- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': f'logged dispatch {run_count}'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- await agent.run(max_steps=1)-- assert 'Dispatching CreateAgentSessionEvent...' in logger.debugs- assert 'Dispatching CreateAgentTaskEvent...' in logger.debugs-- logger.debugs.clear()- await agent.run(max_steps=1)-- assert 'Dispatching CreateAgentSessionEvent...' not in logger.debugs- assert 'Dispatching CreateAgentTaskEvent...' in logger.debugs- assert [type(event).__name__ for event in dispatched] == [- 'CreateAgentSessionEvent',- 'CreateAgentTaskEvent',- 'UpdateAgentTaskEvent',- 'CreateAgentTaskEvent',- 'UpdateAgentTaskEvent',- ]---async def test_rust_agent_exposes_step_finalization_helper_methods(tmp_path):- import base64- import time-- from browser_use.agent.views import ActionResult, AgentStepInfo- from browser_use.rust import Agent-- class DomState:- selector_map = {}-- class BrowserStateSummary:- url = 'https://example.com/final'- title = 'Final'- tabs = []- screenshot = base64.b64encode(b'png-bytes').decode('utf-8')- dom_state = DomState()-- class EventBus:- def __init__(self):- self.dispatched = []-- def dispatch(self, event):- self.dispatched.append(event)- return event-- agent = Agent(task='Finalize helper parity.', file_system_path=str(tmp_path / 'agent-files'))- agent.eventbus = EventBus()-- await agent._handle_step_error(ValueError('bad step'))- assert agent.state.consecutive_failures == 1- assert agent.state.last_result is not None- assert agent.state.last_result[-1].error == 'bad step'-- await agent._post_process()- assert agent.state.consecutive_failures == 2-- agent.state.last_result = [- ActionResult(is_done=True, success=True, extracted_content='final answer', attachments=['file:///tmp/report.txt'])- ]- await agent._post_process()- assert agent.state.consecutive_failures == 0-- agent.state.last_model_output = agent.AgentOutput(- evaluation_previous_goal='Need answer',- memory='Have answer',- next_goal='Finish',- action=[agent.ActionModel(done={'text': 'final answer', 'success': True})],- )- agent.step_start_time = time.time() - 0.1- await agent._finalize(BrowserStateSummary())-- assert agent.state.n_steps == 2- assert agent.state.file_system_state is not None- assert agent.history.final_result() == 'final answer'- assert agent.history.urls() == ['https://example.com/final']- assert Path(agent.history.history[0].state.screenshot_path).read_bytes() == b'png-bytes'- assert [type(event).__name__ for event in agent.eventbus.dispatched] == ['CreateAgentStepEvent']- assert agent.eventbus.dispatched[0].agent_task_id == str(agent.task_id)- assert agent.eventbus.dispatched[0].actions == [{'done': {'text': 'final answer', 'success': True, 'files_to_display': []}}]- assert agent.eventbus.dispatched[0].url == 'https://example.com/final'- assert agent.eventbus.dispatched[0].screenshot_url.startswith('data:image/')- assert ';base64,' in agent.eventbus.dispatched[0].screenshot_url-- await agent._force_done_after_last_step(AgentStepInfo(step_number=2, max_steps=3))- assert agent.AgentOutput is agent.DoneAgentOutput-- agent.state.consecutive_failures = agent.settings.max_failures- agent.AgentOutput = None- await agent._force_done_after_failure()- assert agent.AgentOutput is agent.DoneAgentOutput---async def test_rust_agent_finalize_logs_step_completion_without_browser_state(monkeypatch, tmp_path):- import time-- from browser_use.agent.views import ActionResult- from browser_use.rust import Agent-- class RecordingLogger:- def __init__(self):- self.debugs = []-- def debug(self, message, *args, **kwargs):- self.debugs.append(message)-- class EventBus:- def __init__(self):- self.dispatched = []-- def dispatch(self, event):- self.dispatched.append(event)- return event-- logger = RecordingLogger()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Finalize without browser state.', file_system_path=str(tmp_path / 'agent-files'))- agent.eventbus = EventBus()- agent.state.last_result = [ActionResult(extracted_content='ok')]- agent.step_start_time = time.time() - 0.1- starting_steps = agent.state.n_steps-- await agent._finalize(None)-- assert agent.state.n_steps == starting_steps + 1- assert agent.state.file_system_state is not None- assert agent.history.history == []- assert agent.eventbus.dispatched == []- assert any('Ran 1 action' in message and 'success=1' in message for message in logger.debugs)---async def test_rust_agent_finalize_orders_summary_save_before_step_event(monkeypatch, tmp_path):- import base64- import time-- from browser_use.agent.views import ActionResult- from browser_use.rust import Agent-- calls = []-- class RecordingLogger:- def debug(self, message, *args, **kwargs):- if 'Ran 1 action' in message:- calls.append('summary')-- class DomState:- selector_map = {}-- class BrowserStateSummary:- url = 'https://example.com/finalize-order'- title = 'Finalize Order'- tabs = []- screenshot = base64.b64encode(b'png-bytes').decode('utf-8')- dom_state = DomState()-- class EventBus:- def __init__(self):- self.dispatched = []-- def dispatch(self, event):- calls.append('dispatch')- self.dispatched.append(event)- return event-- logger = RecordingLogger()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- agent = Agent(task='Finalize order parity.', file_system_path=str(tmp_path / 'agent-files'))- agent.eventbus = EventBus()- agent.state.last_result = [ActionResult(is_done=True, success=True, extracted_content='final answer')]- agent.state.last_model_output = agent.AgentOutput(- evaluation_previous_goal='Need answer',- memory='Have answer',- next_goal='Finish',- action=[agent.ActionModel(done={'text': 'final answer', 'success': True})],- )- agent.step_start_time = time.time() - 0.1- monkeypatch.setattr(agent, 'save_file_system_state', lambda: calls.append('save'))- starting_steps = agent.state.n_steps-- await agent._finalize(BrowserStateSummary())-- assert calls == ['summary', 'save', 'dispatch']- assert agent.state.n_steps == starting_steps + 1- assert [type(event).__name__ for event in agent.eventbus.dispatched] == ['CreateAgentStepEvent']---async def test_rust_agent_done_only_guidance_matches_browser_use(monkeypatch):- from browser_use.agent.views import AgentStepInfo+async def test_rust_agent_done_only_guidance_matches_browser_use(monkeypatch):+ from browser_use.agent.views import AgentStepInfofrom browser_use.rust import Agentclass RecordingLogger:@@ -6836,47 +5294,6 @@ def test_rust_agent_initializes_message_manager_and_followup_state():assert agent.eventbus.name.isidentifier()-async def test_rust_agent_add_new_task_preserves_browser_use_raw_followup_task(monkeypatch):- from browser_use.rust import Agent-- class Answer(BaseModel):- answer: str-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(- task='Initial structured task.',- llm=type('LLM', (), {'model': 'gpt-test'})(),- output_model_schema=Answer,- )- process_calls = []- load_count = 0-- async def fake_run_process(argv, timeout_seconds=None):- process_calls.append(argv)- if len(process_calls) == 1:- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''- return 0, '', ''-- async def fake_load_events():- nonlocal load_count- load_count += 1- return [{'event_type': 'session.done', 'payload': {'result': '{"answer":"ok"}'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- await agent.run(max_steps=2)- agent.add_new_task('Follow up with raw text.')-- assert agent.task == 'Follow up with raw text.'- assert 'Expected output JSON schema' not in agent.task- assert '<follow_up_user_request> Follow up with raw text. </follow_up_user_request>' in agent.message_manager.task-- await agent.run(max_steps=2)-- assert process_calls[2][-3:] == ['followup', '12345678-1234-1234-1234-123456789abc', 'Follow up with raw text.']--def test_rust_agent_initializes_browser_use_session_and_file_system(tmp_path):from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.rust import Agent@@ -7024,519 +5441,104 @@ async def test_rust_agent_initializes_screenshot_service(tmp_path):assert agent.screenshot_service.screenshots_dir.exists()screenshot_b64 = base64.b64encode(b'png-bytes').decode('utf-8')- screenshot_path = await agent.screenshot_service.store_screenshot(screenshot_b64, step_number=3)-- assert Path(screenshot_path).name == 'step_3.png'- assert Path(screenshot_path).read_bytes() == b'png-bytes'- assert await agent.screenshot_service.get_screenshot(screenshot_path) == screenshot_b64---def test_rust_agent_adds_available_files_to_task_context():- from browser_use.rust import Agent-- agent = Agent(- task='Summarize the provided report.',- available_file_paths=['/tmp/report.txt', '~/notes.md'],- )-- assert agent.available_file_paths == ['/tmp/report.txt', '~/notes.md']- assert 'Available local files:' in agent.task- assert '- /tmp/report.txt' in agent.task- assert '- ' in agent.task and 'notes.md' in agent.task---def test_rust_agent_default_model_uses_browser_use_default_llm(monkeypatch):- from browser_use.agent.service import _PythonAgent as BrowserUseAgent- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_RUST_MODEL', 'legacy-codex-default')-- agent = Agent(task='report title')- browser_use_agent = BrowserUseAgent(task='report title')-- assert agent.llm.provider == browser_use_agent.llm.provider == 'browser-use'- assert agent.model == browser_use_agent.llm.model---def test_rust_agent_translates_followup_to_existing_terminal_session(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(task='start', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'-- argv = agent._run_existing_argv(max_steps=9)-- assert argv[0] == '/tmp/browser-use-terminal'- assert argv[-4:] == ['run-codex-session', agent.terminal_session_id, '--model', 'gpt-test']- assert 'max_turns=9' in argv---async def test_rust_agent_keeps_browser_use_session_id_separate_from_terminal_session(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(task='start', task_id='task-1', llm=type('LLM', (), {'model': 'gpt-test'})())- browser_use_session_id = agent.session_id-- assert isinstance(browser_use_session_id, str)- assert browser_use_session_id- assert agent.terminal_session_id is None-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'session answer'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- await agent.run(max_steps=1)-- assert agent.session_id == browser_use_session_id- assert agent.terminal_session_id == '12345678-1234-1234-1234-123456789abc'- assert agent.session_id != agent.terminal_session_id---async def test_rust_agent_loads_started_session_events_after_terminal_timeout(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(task='timeout after start', llm=type('LLM', (), {'model': 'gpt-test'})(), step_timeout=5)- process_commands = []- stored_events = [- {'event_type': 'model.turn.request', 'payload': {'model': 'gpt-test'}},- {'event_type': 'model.stream_delta', 'payload': {'text': 'partial answer before timeout'}},- {'event_type': 'browser.state', 'payload': {'url': 'https://example.com', 'title': 'Example'}},- {'event_type': 'model.usage', 'payload': {'input_tokens': 11, 'output_tokens': 7}},- ]-- async def fake_run_process(argv, timeout_seconds=None):- process_commands.append(argv[-2] if argv[-2:] == ['start', agent.task] else argv[-4])- if process_commands[-1] == 'start':- return 0, '12345678-1234-1234-1234-123456789abc\n', ''- return 124, '', 'browser-use-terminal timed out after 5 seconds'-- async def fake_load_events():- assert agent.terminal_session_id == '12345678-1234-1234-1234-123456789abc'- return stored_events-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=3)-- assert process_commands == ['start', 'run-codex-session']- assert agent.terminal_session_id == '12345678-1234-1234-1234-123456789abc'- assert agent.last_events == stored_events- assert history.urls() == ['https://example.com']- assert history.final_result() == 'partial answer before timeout'- assert history.usage is not None- assert history.usage.total_prompt_tokens == 11- assert history.errors() == ['browser-use-terminal timed out after 5 seconds']---async def test_rust_agent_invokes_browser_use_style_callbacks(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- seen = []-- def done_callback(history):- seen.append(('done', history.final_result()))-- agent = Agent(task='start', llm=type('LLM', (), {'model': 'gpt-test'})(), register_done_callback=done_callback)-- async def fake_run_process(argv, timeout_seconds=None):- assert timeout_seconds == agent.settings.step_timeout- command = 'start' if argv[-2:] == ['start', agent.task] else argv[-4]- seen.append(('argv', command))- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'ok'}}]-- async def on_step_start(callback_agent):- seen.append(('start', callback_agent is agent))-- def on_step_end(callback_agent):- seen.append(('end', callback_agent is agent))-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=3, on_step_start=on_step_start, on_step_end=on_step_end)-- assert history.final_result() == 'ok'- assert seen == [- ('start', True),- ('argv', 'start'),- ('argv', 'run-codex-session'),- ('end', True),- ('done', 'ok'),- ]---async def test_rust_agent_logs_completion_before_done_callback(monkeypatch):- import logging-- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- seen = []- logged_messages = []- original_info = logging.Logger.info-- def recording_info(logger, message, *args, **kwargs):- logged_messages.append(str(message))- return original_info(logger, message, *args, **kwargs)-- monkeypatch.setattr(logging.Logger, 'info', recording_info)-- def done_callback(history):- seen.append(('done', history.final_result()))-- agent = Agent(- task='start',- task_id='completion-logs',- llm=type('LLM', (), {'model': 'gpt-test'})(),- register_done_callback=done_callback,- )- original_log_completion = agent.log_completion-- async def recording_log_completion():- await original_log_completion()- seen.append(('logged', None))-- agent.log_completion = recording_log_completion-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'logged answer'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- await agent.run(max_steps=1)-- assert seen == [('logged', None), ('done', 'logged answer')]- assert '✅ Task completed successfully' in logged_messages---async def test_rust_agent_log_completion_matches_browser_use(monkeypatch):- import browser_use.rust.service as rust_service- from browser_use.agent.service import _PythonAgent as BrowserUseAgent- from browser_use.rust import Agent as RustAgent-- class RecordingLogger:- def __init__(self):- self.infos = []-- def debug(self, message, *args, **kwargs):- pass-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def warning(self, message, *args, **kwargs):- pass-- def error(self, message, *args, **kwargs):- pass-- class LLM:- model = 'gpt-test'- provider = 'test'-- async def ainvoke(self, messages, output_format=None, **kwargs):- return type('Result', (), {'usage': None})()-- def make_history(success: bool):- events = [{'event_type': 'session.done', 'payload': {'result': 'done'}}] if success else []- return rust_service._history_from_events(- events,- model='gpt-test',- started=1.0,- finished=2.0,- output_model_schema=None,- process_error=None if success else 'failed',- )-- for index, success in enumerate((True, False)):- browser_use_logger = RecordingLogger()- rust_logger = RecordingLogger()- monkeypatch.setattr(BrowserUseAgent, 'logger', property(lambda self, logger=browser_use_logger: logger))- monkeypatch.setattr(RustAgent, 'logger', property(lambda self, logger=rust_logger: logger))-- browser_use_agent = BrowserUseAgent(- task='Log completion parity.',- llm=LLM(),- task_id=f'browsercompletionbu{index}',- directly_open_url=False,- )- rust_agent = RustAgent(- task='Log completion parity.',- llm=LLM(),- task_id=f'rustcompletionrs{index}',- directly_open_url=False,- )- browser_use_agent.history = make_history(success)- rust_agent.history = make_history(success)-- await browser_use_agent.log_completion()- await rust_agent.log_completion()-- assert rust_logger.infos == browser_use_logger.infos---async def test_rust_agent_generates_gif_after_done_callback(monkeypatch, tmp_path):- from browser_use.agent import gif as gif_module- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- seen = []- output_path = tmp_path / 'rust-agent.gif'-- def done_callback(history):- seen.append(('done', history.final_result()))-- def fake_create_history_gif(task, history, output_path):- seen.append(('gif', task, history.final_result(), output_path))-- monkeypatch.setattr(gif_module, 'create_history_gif', fake_create_history_gif)- agent = Agent(- task='Create a visual trace.',- llm=type('LLM', (), {'model': 'gpt-test'})(),- register_done_callback=done_callback,- generate_gif=str(output_path),- )-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'gif answer'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- await agent.run(max_steps=1)-- assert seen == [- ('done', 'gif answer'),- ('gif', agent.task, 'gif answer', str(output_path)),- ]---async def test_rust_agent_dispatches_gif_output_file_event(monkeypatch, tmp_path):- import base64-- from browser_use.agent import gif as gif_module- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- output_path = tmp_path / 'rust-agent.gif'- dispatched = []-- class EventBus:- def dispatch(self, event):- dispatched.append(event)- return event-- def fake_create_history_gif(task, history, output_path):- Path(output_path).write_bytes(b'GIF89a')-- monkeypatch.setattr(gif_module, 'create_history_gif', fake_create_history_gif)- agent = Agent(- task='Create a visual trace output event.',- llm=type('LLM', (), {'model': 'gpt-test'})(),- generate_gif=str(output_path),- )- agent.eventbus = EventBus()-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'gif output event'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- await agent.run(max_steps=1)-- assert [type(event).__name__ for event in dispatched] == [- 'CreateAgentSessionEvent',- 'CreateAgentTaskEvent',- 'UpdateAgentTaskEvent',- 'CreateAgentOutputFileEvent',- ]- output_event = dispatched[-1]- assert output_event.task_id == str(agent.task_id)- assert output_event.file_name == output_path.name- assert output_event.content_type == 'image/gif'- assert base64.b64decode(output_event.file_content) == b'GIF89a'---async def test_rust_agent_invokes_new_step_callback(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- seen = []-- def new_step_callback(browser_state, model_output, step_number):- seen.append((browser_state.url, model_output, step_number))-- agent = Agent(- task='start',- llm=type('LLM', (), {'model': 'gpt-test'})(),- register_new_step_callback=new_step_callback,- )+ screenshot_path = await agent.screenshot_service.store_screenshot(screenshot_b64, step_number=3)- async def fake_run_process(argv, timeout_seconds=None):- assert timeout_seconds == agent.settings.step_timeout- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''+ assert Path(screenshot_path).name == 'step_3.png'+ assert Path(screenshot_path).read_bytes() == b'png-bytes'+ assert await agent.screenshot_service.get_screenshot(screenshot_path) == screenshot_b64- async def fake_load_events():- return [- {'event_type': 'browser.state', 'payload': {'url': 'https://example.com', 'title': 'Example'}},- {'event_type': 'session.done', 'payload': {'result': 'ok'}},- ]- agent._run_process = fake_run_process- agent._load_events = fake_load_events+def test_rust_agent_adds_available_files_to_task_context():+ from browser_use.rust import Agent- await agent.run(max_steps=3)+ agent = Agent(+ task='Summarize the provided report.',+ available_file_paths=['/tmp/report.txt', '~/notes.md'],+ )- assert seen == [('https://example.com', None, 2)]+ assert agent.available_file_paths == ['/tmp/report.txt', '~/notes.md']+ assert 'Available local files:' in agent.task+ assert '- /tmp/report.txt' in agent.task+ assert '- ' in agent.task and 'notes.md' in agent.task-async def test_rust_agent_invokes_new_step_callback_for_each_terminal_turn(monkeypatch):+def test_rust_agent_default_model_uses_browser_use_default_llm(monkeypatch):+ from browser_use.agent.service import _PythonAgent as BrowserUseAgentfrom browser_use.rust import Agent- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- seen = []+ monkeypatch.setenv('BROWSER_USE_RUST_MODEL', 'legacy-codex-default')- def new_step_callback(browser_state, model_output, step_number):- seen.append((browser_state.url, model_output, step_number))+ agent = Agent(task='report title')+ browser_use_agent = BrowserUseAgent(task='report title')- agent = Agent(- task='run multiple terminal turns',- llm=type('LLM', (), {'model': 'gpt-test'})(),- register_new_step_callback=new_step_callback,- )- starting_steps = agent.state.n_steps+ assert agent.llm.provider == browser_use_agent.llm.provider == 'browser-use'+ assert agent.model == browser_use_agent.llm.model- async def fake_run_process(argv, timeout_seconds=None):- assert timeout_seconds == agent.settings.step_timeout- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''- async def fake_load_events():- return [- {'type': 'model.turn.request', 'ts_ms': 1_000, 'payload': {'model': 'gpt-test'}},- {'type': 'browser.state', 'ts_ms': 1_010, 'payload': {'url': 'https://first.example', 'title': 'First'}},- {- 'type': 'tool.started',- 'ts_ms': 1_020,- 'payload': {'name': 'browser', 'tool_call_id': 'call-browser', 'arguments': {'cmd': 'observe'}},- },- {- 'type': 'tool.output',- 'ts_ms': 1_030,- 'payload': {'name': 'browser', 'tool_call_id': 'call-browser', 'text': 'first turn observed'},- },- {'type': 'model.turn.request', 'ts_ms': 2_000, 'payload': {'model': 'gpt-test'}},- {'type': 'browser.state', 'ts_ms': 2_010, 'payload': {'url': 'https://example.com', 'title': 'Example'}},- {- 'type': 'tool.started',- 'ts_ms': 2_020,- 'payload': {- 'name': 'done',- 'tool_call_id': 'call-done',- 'arguments': {'text': 'Example Domain', 'success': True},- },- },- {'type': 'session.done', 'ts_ms': 2_030, 'payload': {'result': 'Example Domain'}},- ]+async def test_rust_agent_log_completion_matches_browser_use(monkeypatch):+ import browser_use.rust.service as rust_service+ from browser_use.agent.service import _PythonAgent as BrowserUseAgent+ from browser_use.rust import Agent as RustAgent- agent._run_process = fake_run_process- agent._load_events = fake_load_events+ class RecordingLogger:+ def __init__(self):+ self.infos = []- history = await agent.run(max_steps=4)- await agent._call_new_step_callback()+ def debug(self, message, *args, **kwargs):+ pass- assert history.number_of_steps() == 2- assert agent.state.n_steps == starting_steps + 2- assert seen == [- ('https://first.example', None, starting_steps + 1),- ('https://example.com', None, starting_steps + 2),- ]+ def info(self, message, *args, **kwargs):+ self.infos.append(message)+ def warning(self, message, *args, **kwargs):+ pass-async def test_rust_agent_invokes_on_step_end_for_each_terminal_turn(monkeypatch):- from browser_use.rust import Agent+ def error(self, message, *args, **kwargs):+ pass- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- seen = []- agent = Agent(task='run terminal turn end hooks', llm=type('LLM', (), {'model': 'gpt-test'})())- starting_steps = agent.state.n_steps+ class LLM:+ model = 'gpt-test'+ provider = 'test'- def on_step_end(callback_agent):- seen.append(- (- callback_agent.state.n_steps,- callback_agent.history.number_of_steps(),- callback_agent.history.final_result(),- )- )+ async def ainvoke(self, messages, output_format=None, **kwargs):+ return type('Result', (), {'usage': None})()- async def fake_run_process(argv, timeout_seconds=None):- assert timeout_seconds == agent.settings.step_timeout- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''+ def make_history(success: bool):+ events = [{'event_type': 'session.done', 'payload': {'result': 'done'}}] if success else []+ return rust_service._history_from_events(+ events,+ model='gpt-test',+ started=1.0,+ finished=2.0,+ output_model_schema=None,+ process_error=None if success else 'failed',+ )- async def fake_load_events():- return [- {'type': 'model.turn.request', 'ts_ms': 1_000, 'payload': {'model': 'gpt-test'}},- {'type': 'browser.state', 'ts_ms': 1_010, 'payload': {'url': 'https://first.example', 'title': 'First'}},- {- 'type': 'tool.started',- 'ts_ms': 1_020,- 'payload': {'name': 'browser', 'tool_call_id': 'call-browser', 'arguments': {'cmd': 'observe'}},- },- {- 'type': 'tool.output',- 'ts_ms': 1_030,- 'payload': {'name': 'browser', 'tool_call_id': 'call-browser', 'text': 'first turn observed'},- },- {'type': 'model.turn.request', 'ts_ms': 2_000, 'payload': {'model': 'gpt-test'}},- {'type': 'browser.state', 'ts_ms': 2_010, 'payload': {'url': 'https://example.com', 'title': 'Example'}},- {- 'type': 'tool.started',- 'ts_ms': 2_020,- 'payload': {- 'name': 'done',- 'tool_call_id': 'call-done',- 'arguments': {'text': 'Example Domain', 'success': True},- },- },- {'type': 'session.done', 'ts_ms': 2_030, 'payload': {'result': 'Example Domain'}},- ]+ for index, success in enumerate((True, False)):+ browser_use_logger = RecordingLogger()+ rust_logger = RecordingLogger()+ monkeypatch.setattr(BrowserUseAgent, 'logger', property(lambda self, logger=browser_use_logger: logger))+ monkeypatch.setattr(RustAgent, 'logger', property(lambda self, logger=rust_logger: logger))- agent._run_process = fake_run_process- agent._load_events = fake_load_events+ browser_use_agent = BrowserUseAgent(+ task='Log completion parity.',+ llm=LLM(),+ task_id=f'browsercompletionbu{index}',+ directly_open_url=False,+ )+ rust_agent = RustAgent(+ task='Log completion parity.',+ llm=LLM(),+ task_id=f'rustcompletionrs{index}',+ directly_open_url=False,+ )+ browser_use_agent.history = make_history(success)+ rust_agent.history = make_history(success)- history = await agent.run(max_steps=4, on_step_end=on_step_end)- await agent._call_step_end_callbacks(on_step_end)+ await browser_use_agent.log_completion()+ await rust_agent.log_completion()- assert history.number_of_steps() == 2- assert agent.state.n_steps == starting_steps + 2- assert seen == [- (starting_steps + 2, 2, 'Example Domain'),- (starting_steps + 2, 2, 'Example Domain'),- ]+ assert rust_logger.infos == browser_use_logger.infosdef test_rust_agent_run_sync_delegates_to_async_run(monkeypatch):@@ -7695,51 +5697,6 @@ async def test_rust_agent_close_kills_non_keep_alive_browser_session():assert keep_alive_session.kill_calls == 0-async def test_rust_agent_run_closes_non_keep_alive_browser_session(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')-- class BrowserProfile:- keep_alive = False- viewport = {'width': 1280, 'height': 720}- user_agent = None- headless = True- allowed_domains = []-- class BrowserSession:- id = 'browser-session-1234'- browser_profile = BrowserProfile()-- def __init__(self):- self.kill_calls = 0-- async def kill(self):- self.kill_calls += 1-- session = BrowserSession()- agent = Agent(- task='Run cleanup closes session.',- llm=type('LLM', (), {'model': 'gpt-test'})(),- browser_session=session,- directly_open_url=False,- )-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'cleanup answer'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- history = await agent.run(max_steps=1)-- assert history.final_result() == 'cleanup answer'- assert session.kill_calls == 1--async def test_rust_agent_close_logs_cleanup_errors_without_raising(monkeypatch):from browser_use.rust import Agent@@ -8265,92 +6222,6 @@ def test_rust_history_uses_printed_browser_script_page_info_as_state():assert state.tabs[0].target_id == 'target-1'-async def test_rust_agent_step_runs_single_terminal_turn_and_updates_state(monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(task='step once', llm=type('LLM', (), {'model': 'gpt-test'})())- seen = []-- async def fake_run_process(argv, timeout_seconds=None):- seen.append((argv, timeout_seconds))- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [- {'event_type': 'browser.state', 'payload': {'url': 'https://example.com', 'title': 'Example'}},- {'event_type': 'session.done', 'payload': {'result': 'step answer'}},- ]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- result = await agent.step()-- assert result is None- assert len(seen) == 2- assert seen[0][0][0] == '/tmp/browser-use-terminal'- assert seen[0][0][-2:] == ['start', 'step once']- assert 'max_turns=1' in seen[1][0]- assert seen[0][1] == agent.settings.step_timeout- assert seen[1][1] == agent.settings.step_timeout- assert agent.history.final_result() == 'step answer'- assert agent.state.last_result is not None- assert agent.state.last_result[-1].is_done is True- assert agent.state.last_result[-1].extracted_content == 'step answer'---async def test_rust_agent_execute_step_runs_one_turn_with_callbacks(monkeypatch):- from browser_use.agent.views import AgentStepInfo- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- seen = []-- def done_callback(history):- seen.append(('done', history.final_result()))-- agent = Agent(- task='execute one step',- llm=type('LLM', (), {'model': 'gpt-test'})(),- register_done_callback=done_callback,- )-- async def fake_run_process(argv, timeout_seconds=None):- command = 'start' if argv[-2:] == ['start', agent.task] else argv[-4]- seen.append(('argv', command, timeout_seconds))- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'execute step answer'}}]-- async def on_step_start(callback_agent):- seen.append(('start', callback_agent is agent))-- def on_step_end(callback_agent):- seen.append(('end', callback_agent is agent))-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- is_done = await agent._execute_step(- step=0,- max_steps=1,- step_info=AgentStepInfo(step_number=0, max_steps=1),- on_step_start=on_step_start,- on_step_end=on_step_end,- )-- assert is_done is True- assert seen == [- ('start', True),- ('argv', 'start', agent.settings.step_timeout),- ('argv', 'run-codex-session', agent.settings.step_timeout),- ('end', True),- ('done', 'execute step answer'),- ]--async def test_rust_agent_multi_act_preserves_done_action():from browser_use.rust import Agent@@ -9421,109 +7292,6 @@ def test_rust_agent_initializes_action_models_without_conversation_path():assert agent.DoneAgentOutput is not None-async def test_rust_agent_saves_terminal_conversation(tmp_path, monkeypatch):- from browser_use.rust import Agent-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(- task='start',- llm=type('LLM', (), {'model': 'gpt-test'})(),- task_id='task-1',- save_conversation_path=tmp_path,- )-- async def fake_run_process(argv, timeout_seconds=None):- assert timeout_seconds == agent.settings.step_timeout- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [- {'event_type': 'browser.state', 'payload': {'url': 'https://example.com', 'title': 'Example'}},- {'event_type': 'session.done', 'payload': {'result': 'saved transcript'}},- ]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- await agent.run(max_steps=3)- files = list(tmp_path.glob('conversation_task-1_*.json'))-- assert len(files) == 1- snapshot = json.loads(files[0].read_text(encoding='utf-8'))- assert snapshot['task_id'] == 'task-1'- assert snapshot['session_id'] == agent.session_id- assert snapshot['terminal_session_id'] == '12345678-1234-1234-1234-123456789abc'- assert snapshot['final_result'] == 'saved transcript'- assert snapshot['events'][0]['event_type'] == 'browser.state'- assert agent.state.n_steps == 2---async def test_rust_agent_resolves_conversation_path_like_browser_use(tmp_path, monkeypatch):- from browser_use.rust import Agent- from browser_use.utils import _log_pretty_path-- monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')-- class RecordingLogger:- def __init__(self):- self.infos = []-- def info(self, message, *args, **kwargs):- self.infos.append(message)-- def debug(self, message, *args, **kwargs):- pass-- def warning(self, message, *args, **kwargs):- pass-- def error(self, message, *args, **kwargs):- pass-- logger = RecordingLogger()- monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))- conversation_dir = tmp_path / 'conversations'- agent = Agent(- task='save resolved conversation path',- llm=type('LLM', (), {'model': 'gpt-test'})(),- task_id='task-path',- save_conversation_path=conversation_dir,- )-- assert agent.settings.save_conversation_path == conversation_dir.resolve()- assert logger.infos[0] == f'💬 Saving conversation to {_log_pretty_path(conversation_dir.resolve())}'-- async def fake_run_process(argv, timeout_seconds=None):- return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''-- async def fake_load_events():- return [{'event_type': 'session.done', 'payload': {'result': 'saved path transcript'}}]-- agent._run_process = fake_run_process- agent._load_events = fake_load_events-- await agent.run(max_steps=2)-- files = list(conversation_dir.resolve().glob('conversation_task-path_*.json'))- assert len(files) == 1- assert json.loads(files[0].read_text(encoding='utf-8'))['final_result'] == 'saved path transcript'---async def test_rust_agent_terminal_process_timeout():- from browser_use.rust import Agent-- agent = Agent(task='slow', step_timeout=1)-- returncode, stdout, stderr = await agent._run_process(- [sys.executable, '-c', 'import time; time.sleep(5)'],- timeout_seconds=0.01,- )-- assert returncode == 124- assert stdout == ''- assert 'timed out after 0.01 seconds' in stderr--def test_rust_history_marks_process_failure_not_done():from browser_use.rust.service import _history_from_events