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
perf: keep bracket trimming linear in sanitize_url_candidate
Aniket Wagh3c565af3e010
diff --git a/browser_use/utils.py b/browser_use/utils.pyindex eb1814123..92af31202 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -54,18 +54,25 @@ def sanitize_url_candidate(url: str) -> str:# Strip trailing prose punctuation, but keep a closing bracket the URL opened# itself, e.g. /wiki/Python_(programming_language). A closing bracket is only# prose when it has no opener inside the candidate, as in "(see https://x.com/a)".- while candidate:- last_char = candidate[-1]+ # Bracket totals are counted once and decremented as characters are trimmed, so+ # a candidate ending in many brackets stays linear.+ bracket_counts = {bracket: candidate.count(bracket) for bracket in '()[]'}+ end = len(candidate)+ while end:+ last_char = candidate[end - 1]if last_char in _TRAILING_PROSE_PUNCTUATION:- candidate = candidate[:-1]+ if last_char in bracket_counts:+ bracket_counts[last_char] -= 1+ end -= 1continueopening_bracket = _CLOSING_TO_OPENING_BRACKET.get(last_char)- if opening_bracket is not None and candidate.count(last_char) > candidate.count(opening_bracket):- candidate = candidate[:-1]+ if opening_bracket is not None and bracket_counts[last_char] > bracket_counts[opening_bracket]:+ bracket_counts[last_char] -= 1+ end -= 1continuebreak- return candidate+ return candidate[:end]# Lazy import for error typesdiff --git a/tests/ci/test_beta_agent.py b/tests/ci/test_beta_agent.pyindex 29f638856..fd831d4f9 100644--- a/tests/ci/test_beta_agent.py+++ b/tests/ci/test_beta_agent.py@@ -4310,8 +4310,9 @@ def test_beta_agent_exposes_task_helper_methods():assert agent._extract_start_url(wikipedia_task) == 'https://en.wikipedia.org/wiki/Python_(programming_language)'assert browser_use_agent._extract_start_url(wikipedia_task) == 'https://en.wikipedia.org/wiki/Python_(programming_language)'assert agent._extract_start_url('Check https://example.com/a[1] please') == 'https://example.com/a[1]'- # ...but one the prose opened is still dropped.+ # ...but one the prose opened is still dropped, however many there are.assert agent._extract_start_url('See the docs (https://example.com/guide) for details.') == 'https://example.com/guide'+ assert agent._extract_start_url('Read ((see https://example.com/a)) now') == 'https://example.com/a'def test_beta_agent_exposes_url_text_helper_methods():