Skip to content

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

Action Loop detection

Saurav Pandabd4ead5d2e04
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 837af18d1..c0ba0e779 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -199,6 +199,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
enable_planning: bool = True,
planning_replan_on_stall: int = 3,
planning_exploration_limit: int = 5,
+ loop_detection_window: int = 10,
+ loop_detection_enabled: bool = True,
llm_screenshot_size: tuple[int, int] | None = None,
_url_shortening_limit: int = 25,
**kwargs,
@@ -399,6 +401,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
enable_planning=enable_planning,
planning_replan_on_stall=planning_replan_on_stall,
planning_exploration_limit=planning_exploration_limit,
+ loop_detection_window=loop_detection_window,
+ loop_detection_enabled=loop_detection_enabled,
)
# Token cost service
@@ -410,6 +414,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Initialize state
self.state = injected_agent_state or AgentState()
+ # Configure loop detector window size from settings
+ self.state.loop_detector.window_size = self.settings.loop_detection_window
+
# Initialize history
self.history = AgentHistoryList(history=[], usage=None)
@@ -1082,6 +1089,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
await self._inject_budget_warning(step_info)
self._inject_replan_nudge()
self._inject_exploration_nudge()
+ self._inject_loop_detection_nudge()
+ self._update_loop_detector_page_state(browser_state_summary)
await self._force_done_after_last_step(step_info)
await self._force_done_after_failure()
return browser_state_summary
@@ -1141,6 +1150,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):
if self.state.last_model_output is not None:
self._update_plan_from_model_output(self.state.last_model_output)
+ # Record executed actions for loop detection
+ self._update_loop_detector_actions()
+
# check for action errors and len more than 1
if self.state.last_result and len(self.state.last_result) == 1 and self.state.last_result[-1].error:
self.state.consecutive_failures += 1
@@ -1337,6 +1349,47 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self.logger.info(f'πŸ“‹ Exploration nudge injected after {self.state.n_steps} steps without a plan')
self._message_manager._add_context_message(UserMessage(content=msg))
+ def _inject_loop_detection_nudge(self) -> None:
+ """Inject an escalating nudge when behavioral loops are detected."""
+ if not self.settings.loop_detection_enabled:
+ return
+ nudge = self.state.loop_detector.get_nudge_message()
+ if nudge:
+ self.logger.info(
+ f'πŸ” Loop detection nudge injected (repetition={self.state.loop_detector.max_repetition_count}, '
+ f'stagnation={self.state.loop_detector.consecutive_stagnant_pages})'
+ )
+ self._message_manager._add_context_message(UserMessage(content=nudge))
+
+ def _update_loop_detector_actions(self) -> None:
+ """Record the actions from the latest step into the loop detector."""
+ if not self.settings.loop_detection_enabled:
+ return
+ if self.state.last_model_output is None:
+ return
+ for action in self.state.last_model_output.action:
+ action_data = action.model_dump(exclude_unset=True)
+ action_name = next(iter(action_data.keys()), 'unknown')
+ params = action_data.get(action_name, {})
+ if not isinstance(params, dict):
+ params = {}
+ self.state.loop_detector.record_action(action_name, params)
+
+ def _update_loop_detector_page_state(self, browser_state_summary: BrowserStateSummary) -> None:
+ """Record the current page state for stagnation detection."""
+ if not self.settings.loop_detection_enabled:
+ return
+ url = browser_state_summary.url or ''
+ element_count = len(browser_state_summary.dom_state.selector_map) if browser_state_summary.dom_state else 0
+ # Use the DOM text representation for fingerprinting
+ dom_text = ''
+ if browser_state_summary.dom_state:
+ try:
+ dom_text = browser_state_summary.dom_state.llm_representation()
+ except Exception:
+ dom_text = ''
+ self.state.loop_detector.record_page_state(url, dom_text, element_count)
+
async def _inject_budget_warning(self, step_info: AgentStepInfo | None = None) -> None:
"""Inject a prominent budget warning when the agent has used >= 75% of its step budget.
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 016a3a6b4..69fe59379 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -1,7 +1,9 @@
from __future__ import annotations
+import hashlib
import json
import logging
+import re
import traceback
from dataclasses import dataclass
from pathlib import Path
@@ -58,6 +60,169 @@ class AgentSettings(BaseModel):
step_timeout: int = 180 # Timeout in seconds for each step
final_response_after_failure: bool = True # If True, attempt one final recovery call after max_failures
+ # Loop detection settings
+ loop_detection_window: int = 10 # Rolling window size for action similarity tracking
+ loop_detection_enabled: bool = True # Whether to enable loop detection nudges
+
+
+class PageFingerprint(BaseModel):
+ """Lightweight fingerprint of the browser page state."""
+
+ model_config = ConfigDict(frozen=True)
+
+ url: str
+ element_count: int
+ text_hash: str # First 16 chars of SHA-256 of the DOM text representation
+
+ @staticmethod
+ def from_browser_state(url: str, dom_text: str, element_count: int) -> PageFingerprint:
+ text_hash = hashlib.sha256(dom_text.encode('utf-8', errors='replace')).hexdigest()[:16]
+ return PageFingerprint(url=url, element_count=element_count, text_hash=text_hash)
+
+
+def _normalize_action_for_hash(action_name: str, params: dict[str, Any]) -> str:
+ """Normalize action parameters for similarity hashing.
+
+ For search actions: strip minor keyword variations by sorting tokens.
+ For click actions: hash by element type + rough text content, ignoring index.
+ For navigate: hash by URL domain only.
+ For others: hash by action_name + sorted params.
+ """
+ if action_name == 'search':
+ query = str(params.get('query', ''))
+ # Normalize search: lowercase, sort tokens, collapse whitespace
+ tokens = sorted(set(re.sub(r'[^\w\s]', ' ', query.lower()).split()))
+ engine = params.get('engine', 'google')
+ return f'search|{engine}|{"|".join(tokens)}'
+
+ if action_name in ('click_element', 'input_text'):
+ # For element-interaction actions, we only use the index (element identity).
+ # Two clicks on the same element index are the same action.
+ index = params.get('index')
+ if action_name == 'input_text':
+ text = str(params.get('text', ''))
+ # Normalize input text: lowercase, strip whitespace
+ return f'input_text|{index}|{text.strip().lower()}'
+ return f'click_element|{index}'
+
+ if action_name == 'navigate':
+ url = str(params.get('url', ''))
+ # Hash by domain only β€” navigating to same domain with different paths is still exploration
+ try:
+ from urllib.parse import urlparse
+
+ domain = urlparse(url).netloc
+ return f'navigate|{domain}'
+ except Exception:
+ return f'navigate|{url}'
+
+ if action_name == 'scroll':
+ direction = 'down' if params.get('down', True) else 'up'
+ return f'scroll|{direction}'
+
+ # Default: hash by action name + sorted params (excluding None values)
+ filtered = {k: v for k, v in sorted(params.items()) if v is not None}
+ return f'{action_name}|{json.dumps(filtered, sort_keys=True, default=str)}'
+
+
+def compute_action_hash(action_name: str, params: dict[str, Any]) -> str:
+ """Compute a stable hash string for an action based on type + normalized parameters."""
+ normalized = _normalize_action_for_hash(action_name, params)
+ return hashlib.sha256(normalized.encode('utf-8')).hexdigest()[:12]
+
+
+class ActionLoopDetector(BaseModel):
+ """Tracks action repetition and page stagnation to detect behavioral loops.
+
+ This is a soft detection system β€” it generates context messages for the LLM
+ but never blocks actions. The agent can still repeat if it wants to.
+ """
+
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
+ # Rolling window of recent action hashes
+ window_size: int = 10
+ recent_action_hashes: list[str] = Field(default_factory=list)
+
+ # Page fingerprint tracking for stagnation detection
+ recent_page_fingerprints: list[PageFingerprint] = Field(default_factory=list)
+
+ # Current repetition state
+ max_repetition_count: int = 0 # Highest count of any single hash in the window
+ most_repeated_hash: str | None = None
+ consecutive_stagnant_pages: int = 0 # How many consecutive steps had the same page fingerprint
+
+ def record_action(self, action_name: str, params: dict[str, Any]) -> None:
+ """Record an action and update repetition statistics."""
+ h = compute_action_hash(action_name, params)
+ self.recent_action_hashes.append(h)
+ # Trim to window size
+ if len(self.recent_action_hashes) > self.window_size:
+ self.recent_action_hashes = self.recent_action_hashes[-self.window_size :]
+ self._update_repetition_stats()
+
+ def record_page_state(self, url: str, dom_text: str, element_count: int) -> None:
+ """Record the current page fingerprint and update stagnation count."""
+ fp = PageFingerprint.from_browser_state(url, dom_text, element_count)
+ if self.recent_page_fingerprints and self.recent_page_fingerprints[-1] == fp:
+ self.consecutive_stagnant_pages += 1
+ else:
+ self.consecutive_stagnant_pages = 0
+ self.recent_page_fingerprints.append(fp)
+ # Keep only last few fingerprints (no need for a large window)
+ if len(self.recent_page_fingerprints) > 5:
+ self.recent_page_fingerprints = self.recent_page_fingerprints[-5:]
+
+ def _update_repetition_stats(self) -> None:
+ """Recompute max_repetition_count from the current window."""
+ if not self.recent_action_hashes:
+ self.max_repetition_count = 0
+ self.most_repeated_hash = None
+ return
+ counts: dict[str, int] = {}
+ for h in self.recent_action_hashes:
+ counts[h] = counts.get(h, 0) + 1
+ self.most_repeated_hash = max(counts, key=lambda k: counts[k])
+ self.max_repetition_count = counts[self.most_repeated_hash]
+
+ def get_nudge_message(self) -> str | None:
+ """Return an escalating nudge message based on repetition severity, or None if no loop detected."""
+ messages: list[str] = []
+
+ # Action repetition nudges (escalating at 3, 5, 8)
+ if self.max_repetition_count >= 8:
+ messages.append(
+ f'CRITICAL LOOP DETECTED: You have repeated a similar action {self.max_repetition_count} times '
+ f'in the last {len(self.recent_action_hashes)} actions. '
+ 'Your remaining action budget is low. Extract what you can and report results using the done action. '
+ 'Continuing to repeat the same action will not yield different results.'
+ )
+ elif self.max_repetition_count >= 5:
+ messages.append(
+ f'STRONG LOOP WARNING: You have repeated a similar action {self.max_repetition_count} times '
+ f'in the last {len(self.recent_action_hashes)} actions. '
+ 'Strongly consider abandoning this approach. Try a fundamentally different strategy '
+ 'or report that the task cannot be completed with the current approach.'
+ )
+ elif self.max_repetition_count >= 3:
+ messages.append(
+ f'LOOP DETECTED: You have repeated a similar action {self.max_repetition_count} times '
+ f'in the last {len(self.recent_action_hashes)} actions without meaningful progress. '
+ 'Try a fundamentally different approach or report that the task cannot be completed on this site.'
+ )
+
+ # Page stagnation nudge
+ if self.consecutive_stagnant_pages >= 3:
+ messages.append(
+ f'PAGE STAGNATION: The page content has not changed across {self.consecutive_stagnant_pages} '
+ 'consecutive actions. Your actions are not affecting the page state. '
+ 'Try a different element, navigate to a different page, or conclude the task.'
+ )
+
+ if messages:
+ return '\n\n'.join(messages)
+ return None
+
class AgentState(BaseModel):
"""Holds all state information for an Agent"""
@@ -82,6 +247,9 @@ class AgentState(BaseModel):
message_manager_state: MessageManagerState = Field(default_factory=MessageManagerState)
file_system_state: FileSystemState | None = None
+ # Loop detection state
+ loop_detector: ActionLoopDetector = Field(default_factory=ActionLoopDetector)
+
@dataclass
class AgentStepInfo:
diff --git a/tests/ci/test_action_loop_detection.py b/tests/ci/test_action_loop_detection.py
new file mode 100644
index 000000000..4b21f6b9d
--- /dev/null
+++ b/tests/ci/test_action_loop_detection.py
@@ -0,0 +1,343 @@
+"""Tests for action loop detection β€” behavioral cycle breaking (PR #4)."""
+
+from browser_use.agent.service import Agent
+from browser_use.agent.views import (
+ ActionLoopDetector,
+ PageFingerprint,
+ compute_action_hash,
+)
+from browser_use.llm.messages import UserMessage
+from tests.ci.conftest import create_mock_llm
+
+
+def _get_context_messages(agent: Agent) -> list[str]:
+ """Extract text content from the agent's context messages."""
+ msgs = agent._message_manager.state.history.context_messages
+ return [m.content for m in msgs if isinstance(m, UserMessage) and isinstance(m.content, str)]
+
+
+# ─── Action hash normalization tests ─────────────────────────────────────────
+
+
+def test_search_normalization_ignores_keyword_order():
+ """Two searches with the same keywords in different order should produce the same hash."""
+ h1 = compute_action_hash('search', {'query': 'site:example.com answers votes'})
+ h2 = compute_action_hash('search', {'query': 'votes answers site:example.com'})
+ assert h1 == h2
+
+
+def test_search_normalization_ignores_case():
+ """Search normalization is case-insensitive."""
+ h1 = compute_action_hash('search', {'query': 'Python Tutorial'})
+ h2 = compute_action_hash('search', {'query': 'python tutorial'})
+ assert h1 == h2
+
+
+def test_search_normalization_ignores_punctuation():
+ """Search normalization strips punctuation."""
+ h1 = compute_action_hash('search', {'query': 'site:hinative.com "answers" votes'})
+ h2 = compute_action_hash('search', {'query': 'site:hinative.com answers, votes'})
+ assert h1 == h2
+
+
+def test_search_normalization_deduplicates_tokens():
+ """Duplicate tokens in a search query produce the same hash as single tokens."""
+ h1 = compute_action_hash('search', {'query': 'python python tutorial'})
+ h2 = compute_action_hash('search', {'query': 'python tutorial'})
+ assert h1 == h2
+
+
+def test_search_different_queries_produce_different_hashes():
+ """Fundamentally different search queries should NOT match."""
+ h1 = compute_action_hash('search', {'query': 'python web scraping'})
+ h2 = compute_action_hash('search', {'query': 'javascript testing framework'})
+ assert h1 != h2
+
+
+def test_click_element_same_index_same_hash():
+ """Clicking the same element index produces the same hash."""
+ h1 = compute_action_hash('click_element', {'index': 5})
+ h2 = compute_action_hash('click_element', {'index': 5})
+ assert h1 == h2
+
+
+def test_click_element_different_index_different_hash():
+ """Clicking different element indices produces different hashes."""
+ h1 = compute_action_hash('click_element', {'index': 5})
+ h2 = compute_action_hash('click_element', {'index': 12})
+ assert h1 != h2
+
+
+def test_input_text_same_element_same_text():
+ """Same element + same text = same hash."""
+ h1 = compute_action_hash('input_text', {'index': 3, 'text': 'hello world', 'clear': True})
+ h2 = compute_action_hash('input_text', {'index': 3, 'text': 'hello world', 'clear': False})
+ assert h1 == h2 # clear flag doesn't affect hash
+
+
+def test_input_text_different_text_different_hash():
+ """Same element but different text = different hash."""
+ h1 = compute_action_hash('input_text', {'index': 3, 'text': 'hello'})
+ h2 = compute_action_hash('input_text', {'index': 3, 'text': 'goodbye'})
+ assert h1 != h2
+
+
+def test_navigate_same_domain_same_hash():
+ """Navigate to same domain with different paths produces the same hash."""
+ h1 = compute_action_hash('navigate', {'url': 'https://example.com/page1'})
+ h2 = compute_action_hash('navigate', {'url': 'https://example.com/page2'})
+ assert h1 == h2
+
+
+def test_navigate_different_domain_different_hash():
+ """Navigate to different domains produces different hashes."""
+ h1 = compute_action_hash('navigate', {'url': 'https://example.com/page1'})
+ h2 = compute_action_hash('navigate', {'url': 'https://other.com/page1'})
+ assert h1 != h2
+
+
+def test_scroll_direction_matters():
+ """Scroll up and scroll down are different actions."""
+ h1 = compute_action_hash('scroll', {'down': True})
+ h2 = compute_action_hash('scroll', {'down': False})
+ assert h1 != h2
+
+
+def test_different_action_types_different_hashes():
+ """Different action types always produce different hashes."""
+ h1 = compute_action_hash('click_element', {'index': 5})
+ h2 = compute_action_hash('scroll', {'down': True})
+ h3 = compute_action_hash('search', {'query': 'test'})
+ assert len({h1, h2, h3}) == 3
+
+
+# ─── ActionLoopDetector unit tests ───────────────────────────────────────────
+
+
+def test_detector_no_nudge_for_diverse_actions():
+ """No nudge when actions are all different."""
+ detector = ActionLoopDetector(window_size=10)
+ detector.record_action('click_element', {'index': 1})
+ detector.record_action('scroll', {'down': True})
+ detector.record_action('click_element', {'index': 2})
+ detector.record_action('search', {'query': 'something'})
+ detector.record_action('navigate', {'url': 'https://example.com'})
+ assert detector.get_nudge_message() is None
+
+
+def test_detector_nudge_at_3_repeats():
+ """Nudge triggers at 3 repetitions of the same action."""
+ detector = ActionLoopDetector(window_size=10)
+ for _ in range(3):
+ detector.record_action('search', {'query': 'site:hinative.com answers votes'})
+ msg = detector.get_nudge_message()
+ assert msg is not None
+ assert 'LOOP DETECTED' in msg
+ assert '3 times' in msg
+
+
+def test_detector_nudge_escalates_at_5_repeats():
+ """Stronger nudge at 5 repetitions."""
+ detector = ActionLoopDetector(window_size=10)
+ for _ in range(5):
+ detector.record_action('search', {'query': 'site:hinative.com answers votes'})
+ msg = detector.get_nudge_message()
+ assert msg is not None
+ assert 'STRONG LOOP WARNING' in msg
+ assert '5 times' in msg
+
+
+def test_detector_nudge_escalates_at_8_repeats():
+ """Critical nudge at 8 repetitions."""
+ detector = ActionLoopDetector(window_size=10)
+ for _ in range(8):
+ detector.record_action('search', {'query': 'site:hinative.com answers votes'})
+ msg = detector.get_nudge_message()
+ assert msg is not None
+ assert 'CRITICAL LOOP DETECTED' in msg
+ assert '8 times' in msg
+
+
+def test_detector_window_slides():
+ """Old actions fall out of the window."""
+ detector = ActionLoopDetector(window_size=5)
+ # Fill window with repeated actions
+ for _ in range(3):
+ detector.record_action('click_element', {'index': 7})
+ assert detector.max_repetition_count == 3
+
+ # Push them out with diverse actions
+ for i in range(5):
+ detector.record_action('click_element', {'index': 100 + i})
+ # The 3 old repeated actions should have been pushed out
+ assert detector.max_repetition_count < 3
+ assert detector.get_nudge_message() is None
+
+
+def test_detector_search_variations_detected_as_same():
+ """Minor variations of the same search (the hinative pattern) are detected as repetition."""
+ detector = ActionLoopDetector(window_size=10)
+ # These are the kind of variations the agent produces
+ queries = [
+ 'site:hinative.com answers votes questions',
+ 'site:hinative.com questions answers votes',
+ 'site:hinative.com votes answers questions',
+ ]
+ for q in queries:
+ detector.record_action('search', {'query': q})
+ assert detector.max_repetition_count == 3
+ assert detector.get_nudge_message() is not None
+
+
+# ─── Page stagnation detection tests ─────────────────────────────────────────
+
+
+def test_page_stagnation_no_nudge_when_pages_change():
+ """No stagnation nudge when page content changes each step."""
+ detector = ActionLoopDetector(window_size=10)
+ detector.record_page_state('https://example.com', 'page content 1', 50)
+ detector.record_page_state('https://example.com', 'page content 2', 55)
+ detector.record_page_state('https://example.com', 'page content 3', 60)
+ assert detector.consecutive_stagnant_pages == 0
+ assert detector.get_nudge_message() is None
+
+
+def test_page_stagnation_nudge_at_3_identical_pages():
+ """Stagnation nudge fires after 3 consecutive identical page states."""
+ detector = ActionLoopDetector(window_size=10)
+ # First recording establishes baseline (doesn't count as stagnant)
+ detector.record_page_state('https://example.com', 'same content', 50)
+ detector.record_page_state('https://example.com', 'same content', 50)
+ detector.record_page_state('https://example.com', 'same content', 50)
+ detector.record_page_state('https://example.com', 'same content', 50)
+ assert detector.consecutive_stagnant_pages >= 3
+ msg = detector.get_nudge_message()
+ assert msg is not None
+ assert 'PAGE STAGNATION' in msg
+
+
+def test_page_stagnation_resets_on_change():
+ """Stagnation counter resets when page content changes."""
+ detector = ActionLoopDetector(window_size=10)
+ detector.record_page_state('https://example.com', 'same content', 50)
+ detector.record_page_state('https://example.com', 'same content', 50)
+ detector.record_page_state('https://example.com', 'same content', 50)
+ assert detector.consecutive_stagnant_pages == 2
+ # Page changes
+ detector.record_page_state('https://example.com', 'different content', 55)
+ assert detector.consecutive_stagnant_pages == 0
+
+
+def test_combined_loop_and_stagnation():
+ """Both action loop and page stagnation messages appear together."""
+ detector = ActionLoopDetector(window_size=10)
+ # Create action repetition
+ for _ in range(5):
+ detector.record_action('click_element', {'index': 7})
+ # Create page stagnation
+ detector.record_page_state('https://example.com', 'same', 50)
+ for _ in range(3):
+ detector.record_page_state('https://example.com', 'same', 50)
+ msg = detector.get_nudge_message()
+ assert msg is not None
+ assert 'STRONG LOOP WARNING' in msg
+ assert 'PAGE STAGNATION' in msg
+
+
+# ─── PageFingerprint tests ───────────────────────────────────────────────────
+
+
+def test_page_fingerprint_same_content_equal():
+ """Same content produces equal fingerprints."""
+ fp1 = PageFingerprint.from_browser_state('https://example.com', 'hello world', 50)
+ fp2 = PageFingerprint.from_browser_state('https://example.com', 'hello world', 50)
+ assert fp1 == fp2
+
+
+def test_page_fingerprint_different_content_not_equal():
+ """Different content produces different fingerprints."""
+ fp1 = PageFingerprint.from_browser_state('https://example.com', 'hello world', 50)
+ fp2 = PageFingerprint.from_browser_state('https://example.com', 'goodbye world', 50)
+ assert fp1 != fp2
+
+
+def test_page_fingerprint_different_url_not_equal():
+ """Different URL produces different fingerprint even with same content."""
+ fp1 = PageFingerprint.from_browser_state('https://example.com', 'hello world', 50)
+ fp2 = PageFingerprint.from_browser_state('https://other.com', 'hello world', 50)
+ assert fp1 != fp2
+
+
+def test_page_fingerprint_different_element_count_not_equal():
+ """Different element count produces different fingerprint."""
+ fp1 = PageFingerprint.from_browser_state('https://example.com', 'hello world', 50)
+ fp2 = PageFingerprint.from_browser_state('https://example.com', 'hello world', 51)
+ assert fp1 != fp2
+
+
+# ─── Agent integration tests ─────────────────────────────────────────────────
+
+
+async def test_loop_nudge_injected_into_context():
+ """Loop detection nudge is injected as a context message in the agent."""
+ llm = create_mock_llm()
+ agent = Agent(task='Test task', llm=llm)
+
+ # Simulate 3 repeated actions
+ for _ in range(3):
+ agent.state.loop_detector.record_action('search', {'query': 'site:example.com answers'})
+
+ agent._inject_loop_detection_nudge()
+
+ messages = _get_context_messages(agent)
+ assert len(messages) == 1
+ assert 'LOOP DETECTED' in messages[0]
+
+
+async def test_no_loop_nudge_when_disabled():
+ """No loop nudge when loop_detection_enabled is False."""
+ llm = create_mock_llm()
+ agent = Agent(
+ task='Test task',
+ llm=llm,
+ loop_detection_enabled=False,
+ )
+
+ # Simulate 5 repeated actions
+ for _ in range(5):
+ agent.state.loop_detector.record_action('search', {'query': 'site:example.com answers'})
+
+ agent._inject_loop_detection_nudge()
+
+ messages = _get_context_messages(agent)
+ assert len(messages) == 0
+
+
+async def test_no_loop_nudge_for_diverse_actions():
+ """No loop nudge when actions are diverse."""
+ llm = create_mock_llm()
+ agent = Agent(task='Test task', llm=llm)
+
+ agent.state.loop_detector.record_action('click_element', {'index': 1})
+ agent.state.loop_detector.record_action('scroll', {'down': True})
+ agent.state.loop_detector.record_action('click_element', {'index': 2})
+
+ agent._inject_loop_detection_nudge()
+
+ messages = _get_context_messages(agent)
+ assert len(messages) == 0
+
+
+async def test_loop_detector_initialized_from_settings():
+ """Loop detector window size is set from agent settings."""
+ llm = create_mock_llm()
+ agent = Agent(task='Test task', llm=llm, loop_detection_window=20)
+ assert agent.state.loop_detector.window_size == 20
+
+
+async def test_loop_detector_default_enabled():
+ """Loop detection is enabled by default."""
+ llm = create_mock_llm()
+ agent = Agent(task='Test task', llm=llm)
+ assert agent.settings.loop_detection_enabled is True
+ assert agent.state.loop_detector.window_size == 10