An AI Agent that interacts with Windows OS at GUI level.
Python
feat: add loop detection to prevent agent from repeating stuck behaviors
jeomon63db47c8567d
diff --git a/windows_use/agent/context/prompt/state.md b/windows_use/agent/context/prompt/state.mdindex de95431..72c9774 100644--- a/windows_use/agent/context/prompt/state.md+++ b/windows_use/agent/context/prompt/state.md@@ -1,7 +1,7 @@[Begin of Agent State]Steps: {steps}/{max_steps}[End of Agent State]-+{loop_warning}[Begin of Desktop]Active Desktop: {active_desktop}diff --git a/windows_use/agent/context/service.py b/windows_use/agent/context/service.pyindex 0e5d68c..7a03ed3 100644--- a/windows_use/agent/context/service.py+++ b/windows_use/agent/context/service.py@@ -89,6 +89,7 @@ class Context:step: int,max_steps: int,desktop: Desktop,+ nudge: str = "",) -> HumanMessage | ImageMessage:desktop_state = desktop.get_state() # Populates desktop.desktop_statecontent = self._build_state_prompt(@@ -96,20 +97,23 @@ class Context:step=step,max_steps=max_steps,desktop=desktop,+ nudge=nudge,)if desktop.use_vision and desktop_state.screenshot:return ImageMessage(images=[desktop_state.screenshot], content=content)return HumanMessage(content=content)def _build_state_prompt(- self, query: str, step: int, max_steps: int, desktop: Desktop+ self, query: str, step: int, max_steps: int, desktop: Desktop, nudge: str = "") -> str:desktop_state = desktop.desktop_statecursor_x, cursor_y = uia.GetCursorPos()template = _load_template("state.md")+ loop_warning = f"[Loop Warning]\n{nudge}\n[End of Loop Warning]\n" if nudge else ""return template.format(**{"steps": step,"max_steps": max_steps,+ "loop_warning": loop_warning,"active_window": desktop_state.active_window_to_string(),"windows": desktop_state.windows_to_string(),"cursor_location": f"({cursor_x},{cursor_y})",diff --git a/windows_use/agent/loop.py b/windows_use/agent/loop.pynew file mode 100644index 0000000..3d62e2b--- /dev/null+++ b/windows_use/agent/loop.py@@ -0,0 +1,154 @@+from __future__ import annotations++import hashlib+import json+from collections import Counter, deque+from windows_use.agent.desktop.views import DesktopState++_EXEMPT = {'done_tool', 'wait_tool'}+_IGNORE_PARAMS = {'thought'}++_REPEAT_NUDGES = {+ 3: 'You have repeated the same action {n} times — make sure it is actually making progress.',+ 5: 'Same action repeated {n} times. If you are stuck, try a different approach.',+ 8: 'Same action repeated {n} times. Stop and take a completely different strategy.',+}+++class LoopGuard:+ """Watches for signs that the agent is looping:++ - **Action repetition**: the same tool + params appearing too often+ in the last `window` steps.+ - **UI stagnation**: the desktop state (active window, interactive elements)+ not changing across consecutive steps, meaning actions have no visible effect.+ - **State cycle**: the agent returning to a UI state it has already+ visited (e.g. A→B→A), which consecutive-stagnation cannot catch.+ - **Failed action retry**: the agent calling the exact same action+ that just failed, unchanged, which will produce the same failure.++ Call ``check()`` before each LLM step to get a warning string (or+ None), ``record_action()`` after executing a tool, and+ ``record_state()`` after capturing desktop state.+ """++ def __init__(self, window: int = 15) -> None:+ self._hashes: deque[str] = deque(maxlen=window)+ self._last_state: tuple[str, str] | None = None # (window_id, content_hash)+ self._stagnant = 0+ # State cycle detection+ self._visited_states: dict[str, int] = {} # fingerprint → visit count+ self._cycle_warning: str = ''+ # Failed action retry detection+ self._last_action_key: str | None = None+ self._last_action_failed: bool = False+ self._failed_retry_warning: str = ''++ def record_action(self, tool: str, params: dict, is_success: bool = True) -> None:+ if tool in _EXEMPT:+ return+ filtered = {k: v for k, v in params.items() if k not in _IGNORE_PARAMS}+ normalised = {+ k: v.strip().lower() if isinstance(v, str) else v+ for k, v in filtered.items()+ }+ raw = json.dumps({tool: normalised}, sort_keys=True).encode()+ key = hashlib.sha256(raw).hexdigest()[:12]+ self._hashes.append(key)++ # Failed action retry: same key as last action and last action failed+ if not is_success and self._last_action_key == key and self._last_action_failed:+ self._failed_retry_warning = (+ f"You are retrying '{tool}' with the same parameters after it already failed. "+ 'The same action will produce the same failure — change your approach, '+ 'try different parameters, or use a different tool.'+ )+ else:+ self._failed_retry_warning = ''++ self._last_action_key = key+ self._last_action_failed = not is_success++ def record_state(self, desktop_state: DesktopState) -> None:+ """Record the current desktop state as a fingerprint.++ Uses window handle (HWND) as the window identity and interactive elements+ string as the content indicator.+ """+ # Window identity: use HWND (handle) as stable window identifier+ if desktop_state.active_window:+ window_id = f"{desktop_state.active_window.handle}"+ else:+ window_id = "no_window"++ # Content indicator: use interactive elements string if available+ if desktop_state.tree_state:+ content_text = desktop_state.tree_state.interactive_elements_to_string()+ elif desktop_state.active_window:+ content_text = desktop_state.active_window.name+ else:+ content_text = "no_content"++ digest = hashlib.sha256(content_text.encode('utf-8', errors='replace')).hexdigest()[:16]+ state = (window_id, digest)++ if state == self._last_state:+ self._stagnant += 1+ else:+ self._stagnant = 0+ self._last_state = state++ # State cycle detection: track all-time visits to this state+ fingerprint = f'{window_id}|{digest}'+ count = self._visited_states.get(fingerprint, 0) + 1+ self._visited_states[fingerprint] = count+ if count == 2:+ self._cycle_warning = (+ 'You have returned to a UI state you already visited. '+ 'You may be cycling between states. Try a completely different approach '+ 'instead of repeating the same steps.'+ )+ elif count >= 3:+ self._cycle_warning = (+ f'You have returned to this state {count} times. '+ 'You are stuck in a loop — stop and reconsider your strategy entirely. '+ 'Try an alternative method or approach.'+ )+ else:+ self._cycle_warning = ''++ def check(self) -> str | None:+ warnings: list[str] = []++ if self._hashes:+ top = Counter(self._hashes).most_common(1)[0][1]+ for threshold in sorted(_REPEAT_NUDGES, reverse=True):+ if top >= threshold:+ warnings.append(_REPEAT_NUDGES[threshold].format(n=top))+ break++ if self._stagnant >= 4:+ warnings.append(+ f'The UI has not changed for {self._stagnant} steps. '+ 'Your actions may not be having any effect. '+ 'If waiting for something external (OTP, email, slow load) '+ 'use wait_tool first, then re-check.'+ )++ if self._cycle_warning:+ warnings.append(self._cycle_warning)++ if self._failed_retry_warning:+ warnings.append(self._failed_retry_warning)++ return '\n\n'.join(warnings) or None++ def reset(self) -> None:+ self._hashes.clear()+ self._last_state = None+ self._stagnant = 0+ self._visited_states = {}+ self._cycle_warning = ''+ self._last_action_key = None+ self._last_action_failed = False+ self._failed_retry_warning = ''diff --git a/windows_use/agent/service.py b/windows_use/agent/service.pyindex 1d50d2f..d72109c 100644--- a/windows_use/agent/service.py+++ b/windows_use/agent/service.py@@ -8,6 +8,7 @@ from windows_use.agent.registry.service import Registryfrom windows_use.agent.watchdog.service import WatchDogfrom windows_use.agent.desktop.service import Desktopfrom windows_use.agent.desktop.views import Browser+from windows_use.agent.loop import LoopGuardfrom windows_use.providers.events import LLMEventTypefrom typing import Callable, Literal, TYPE_CHECKINGfrom windows_use.agent.context import Context@@ -106,6 +107,7 @@ class Agent(BaseAgent):self.log_to_file = log_to_fileself.log_to_console = log_to_consoleself.llm = llm+ self._loop_guard = LoopGuard()self.event = Event()if event_subscriber is not None:@@ -158,10 +160,28 @@ class Agent(BaseAgent):self.state.messages.insert(0, self.system_message)self.state.messages.append(self.task_message)consecutive_failures = 0+ self._loop_guard.reset()for step in range(self.state.max_steps):self.state.step = step- self.state.messages.append(self.state_message)++ # Check for loops and build state message with nudge+ nudge = self._loop_guard.check()+ state_msg = self.context.state(+ query=self.state.task,+ step=step,+ max_steps=self.state.max_steps,+ desktop=self.desktop,+ nudge=nudge or "",+ )+ if nudge:+ self.event.emit(+ AgentEvent(type=EventType.ERROR, data={"step": step, "error": f"Loop detected: {nudge}"})+ )+ self.state.messages.append(state_msg)++ # Record current desktop state for loop detection+ self._loop_guard.record_state(self.desktop.desktop_state)# Reason: call LLM, retry on failure, return ToolMessagemessage: ToolMessage | None = None@@ -241,6 +261,9 @@ class Agent(BaseAgent):# Act: execute tool via registrytool_result = self.registry.execute(tool_name=tool_name, tool_params=tool_params, desktop=self.desktop)+ # Record action for loop detection+ self._loop_guard.record_action(tool_name, tool_params, tool_result.is_success)+if tool_result.is_success:content = tool_result.contentmessage.content = content@@ -336,10 +359,28 @@ class Agent(BaseAgent):self.state.messages.insert(0, self.system_message)self.state.messages.append(self.task_message)consecutive_failures = 0+ self._loop_guard.reset()for step in range(self.state.max_steps):self.state.step = step- self.state.messages.append(self.state_message)++ # Check for loops and build state message with nudge+ nudge = self._loop_guard.check()+ state_msg = self.context.state(+ query=self.state.task,+ step=step,+ max_steps=self.state.max_steps,+ desktop=self.desktop,+ nudge=nudge or "",+ )+ if nudge:+ self.event.emit(+ AgentEvent(type=EventType.ERROR, data={"step": step, "error": f"Loop detected: {nudge}"})+ )+ self.state.messages.append(state_msg)++ # Record current desktop state for loop detection+ self._loop_guard.record_state(self.desktop.desktop_state)message: ToolMessage | None = Nonelast_error: Exception | None = None@@ -418,6 +459,9 @@ class Agent(BaseAgent):# Act: execute tool via registry asynchronouslytool_result = await self.registry.aexecute(tool_name=tool_name, tool_params=tool_params, desktop=self.desktop)+ # Record action for loop detection+ self._loop_guard.record_action(tool_name, tool_params, tool_result.is_success)+if tool_result.is_success:content = tool_result.contentmessage.content = content