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(tools): report failed tab switches as errors instead of silent success
Faseehc45b85023141
diff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex 2eb65e809..915690ff1 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -1014,18 +1014,24 @@ class Tools(Generic[Context]):event = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=target_id))await eventnew_target_id = await event.event_result(raise_if_any=False, raise_if_none=False) # Don't raise on errors-- if new_target_id:- memory = f'Switched to tab #{new_target_id[-4:]}'- else:- memory = f'Switched to tab #{params.tab_id}'-- logger.info(f'🔄 {memory}')- return ActionResult(extracted_content=memory, long_term_memory=memory)except Exception as e:- logger.warning(f'Tab switch may have failed: {e}')- memory = f'Attempted to switch to tab #{params.tab_id}'- return ActionResult(extracted_content=memory, long_term_memory=memory)+ logger.warning(f'Tab switch failed: {e}')+ # Preserve the concrete cause (e.g. a stale tab_id) instead of a generic+ # message, so the agent gets actionable failure info in both memories.+ memory = f'Failed to switch to tab #{params.tab_id}: {e}'+ raise BrowserError(memory, short_term_memory=memory, long_term_memory=memory)++ # on_SwitchTabEvent returns the newly focused TargetID on every success path, so a+ # missing result means the handler failed rather than having quietly succeeded+ # (raise_if_any=False above only suppresses the exception, it doesn't mean success).+ if not new_target_id:+ memory = f'Failed to switch to tab #{params.tab_id}: tab switch produced no result'+ logger.warning(memory)+ raise BrowserError(memory, short_term_memory=memory, long_term_memory=memory)++ memory = f'Switched to tab #{new_target_id[-4:]}'+ logger.info(f'🔄 {memory}')+ return ActionResult(extracted_content=memory, long_term_memory=memory)@self.registry.action('Close a tab by tab_id. Tab IDs are shown in browser state tabs list (last 4 chars of target_id). Use to clean up tabs you no longer need.',diff --git a/tests/ci/browser/test_tabs.py b/tests/ci/browser/test_tabs.pyindex a0372b92a..e08633f6b 100644--- a/tests/ci/browser/test_tabs.py+++ b/tests/ci/browser/test_tabs.py@@ -26,6 +26,7 @@ from pytest_httpserver import HTTPServerfrom browser_use.agent.service import Agentfrom browser_use.browser import BrowserSessionfrom browser_use.browser.profile import BrowserProfile+from browser_use.tools.service import Toolsfrom tests.ci.conftest import create_mock_llm@@ -669,3 +670,50 @@ class TestMultiTabOperations:assert 'Successfully' in final_result, 'Agent should report success'except TimeoutError:pytest.fail('Test timed out after 2 minutes - agent hung during multiple tab operations')+++class TestSwitchTabFailureReporting:+ """A failed `switch` must surface as ActionResult.error rather than a fake success.++ Previously both failure paths (a stale/unknown tab_id, and a missing SwitchTabEvent+ result) returned a non-error ActionResult claiming the switch succeeded. The false+ claim was written into long_term_memory, so subsequent steps reasoned from a tab the+ agent never actually reached.+ """++ async def test_switch_to_nonexistent_tab_reports_error(self, browser_session):+ tools = Tools()+ ActionModel = tools.registry.create_action_model()++ tabs_before = await browser_session.get_tabs()+ live_ids = {tab.target_id[-4:] for tab in tabs_before}+ bogus_tab_id = 'zzzz'+ assert bogus_tab_id not in live_ids++ result = await tools.act(ActionModel(switch={'tab_id': bogus_tab_id}), browser_session=browser_session)++ assert result.error is not None, 'a failed tab switch must set ActionResult.error'+ assert bogus_tab_id in result.error+ assert 'Switched to tab' not in (result.extracted_content or '')+ assert 'Switched to tab' not in (result.long_term_memory or '')++ tabs_after = await browser_session.get_tabs()+ assert {tab.target_id[-4:] for tab in tabs_after} == live_ids, 'no tab switch should have happened'++ async def test_switch_to_open_tab_still_succeeds(self, browser_session, base_url):+ tools = Tools()+ ActionModel = tools.registry.create_action_model()++ original_tab_id = (await browser_session.get_tabs())[0].target_id[-4:]++ open_result = await tools.act(+ ActionModel(navigate={'url': f'{base_url}/page1', 'new_tab': True}),+ browser_session=browser_session,+ )+ assert open_result.error is None, f'opening a new tab should not error: {open_result.error}'++ result = await tools.act(ActionModel(switch={'tab_id': original_tab_id}), browser_session=browser_session)++ assert result.error is None, f'switching to a live tab must not error: {result.error}'+ assert result.long_term_memory is not None+ assert 'Switched to tab' in result.long_term_memory