Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

fixed the edge case for handling max index

Saurav Panda319d0acd45de
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 820e8cb7d..c1a58ed9a 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -2955,7 +2955,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
if not history_item.model_output or not history_item.model_output.action:
return 0
- max_index = 0
+ max_index = -1 # Use -1 to indicate no index found yet
for action in history_item.model_output.action:
# Get the element index this action targets
index = action.get_index()
@@ -2964,7 +2964,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Need at least max_index + 1 elements (indices are 0-based)
# Cap at 50 to avoid waiting forever for very high indices
- return min(max_index + 1, 50) if max_index > 0 else 0
+ # max_index >= 0 means we found at least one action with an index
+ return min(max_index + 1, 50) if max_index >= 0 else 0
async def _execute_history_step(
self,
diff --git a/tests/ci/test_rerun_ai_summary.py b/tests/ci/test_rerun_ai_summary.py
index 253395416..4840a5a05 100644
--- a/tests/ci/test_rerun_ai_summary.py
+++ b/tests/ci/test_rerun_ai_summary.py
@@ -963,6 +963,25 @@ async def test_count_expected_elements_from_history():
metadata=StepMetadata(step_start_time=0, step_end_time=1, step_number=5, step_interval=0.1),
)
+ # Test 6: Action with index 0 (edge case) -> needs at least 1 element
+ # Using input action because it allows index 0 (click requires ge=1)
+ step_index_zero = AgentHistory(
+ model_output=AgentOutput(
+ evaluation_previous_goal=None,
+ memory='Test',
+ next_goal=None,
+ action=[{'input': {'index': 0, 'text': 'test'}}], # type: ignore[arg-type]
+ ),
+ result=[ActionResult(long_term_memory='Done')],
+ state=BrowserStateHistory(
+ url='http://test.com',
+ title='Test',
+ tabs=[],
+ interacted_element=[None],
+ ),
+ metadata=StepMetadata(step_start_time=0, step_end_time=1, step_number=6, step_interval=0.1),
+ )
+
try:
# Test 1: Action index 5 -> needs 6 elements (index + 1)
assert agent._count_expected_elements_from_history(step_low_index) == 6
@@ -979,6 +998,9 @@ async def test_count_expected_elements_from_history():
# Test 5: Multiple actions -> uses max index (10) + 1 = 11
assert agent._count_expected_elements_from_history(step_multiple_actions) == 11
+ # Test 6: Action index 0 (edge case) -> needs 1 element (0 + 1)
+ assert agent._count_expected_elements_from_history(step_index_zero) == 1
+
finally:
await agent.close()