Skip to content

An AI Agent that interacts with Windows OS at GUI level.

Python

feat: add SelectorMap for label-to-xpath element lookup

jeomonada8503a41dc
diff --git a/windows_use/agent/tree/views.py b/windows_use/agent/tree/views.py
index d02012a..cd50da2 100644
--- a/windows_use/agent/tree/views.py
+++ b/windows_use/agent/tree/views.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass,field
-from typing import TYPE_CHECKING, Optional,Any
+from typing import TYPE_CHECKING, Optional,Any,Union
import json
WARNING_MESSAGE="The desktop UI services are temporarily unavailable. Please wait a few seconds and continue."
@@ -35,6 +35,11 @@ class TreeState:
parts.append("\n".join(rows))
return "\n".join(parts)
+ def build_selector_map(self) -> 'SelectorMap':
+ """Build a SelectorMap from all interactive and scrollable nodes in this tree state."""
+ nodes: list = list(self.interactive_nodes or []) + list(self.scrollable_nodes or [])
+ return SelectorMap(nodes)
+
def scrollable_elements_to_string(self) -> str:
parts = []
if not self.status:
@@ -149,3 +154,95 @@ class TextElementNode:
text:str
ElementNode=TreeElementNode|ScrollElementNode|TextElementNode
+
+_SelectorNode = Union[TreeElementNode, ScrollElementNode]
+
+class SelectorMap:
+ """Maps element labels to their TreeElementNodes for cursor-free element lookup.
+
+ Provides fast access to interactive and scrollable elements by name,
+ with optional control_type filtering for disambiguation when multiple
+ elements share the same label.
+
+ Usage:
+ selector = tree_state.build_selector_map()
+
+ # Exact label lookup
+ node = selector['Submit'] # first element named 'Submit'
+ node = selector.get('Submit') # same, returns None if not found
+ node = selector.get('OK', control_type='ButtonControl') # disambiguate
+
+ # All matches for a label
+ nodes = selector.get_all('File') # e.g. File menu + File tab
+
+ # Partial / case-insensitive search
+ nodes = selector.find('save') # finds 'Save', 'Save As', 'Autosave'
+
+ # Resolve to live UIA element (cursor-free)
+ element = desktop.get_element_from_window_xpath(node.hwnd, node.xpath)
+ """
+
+ def __init__(self, nodes: list[_SelectorNode]):
+ # name → all nodes with that name (preserves insertion order)
+ self._by_name: dict[str, list[_SelectorNode]] = {}
+ # (name, control_type) → nodes, for disambiguation
+ self._by_label_type: dict[tuple[str, str], list[_SelectorNode]] = {}
+
+ for node in nodes:
+ name = (node.name or '').strip()
+ if not name:
+ continue
+ ct = node.control_type
+ self._by_name.setdefault(name, []).append(node)
+ self._by_label_type.setdefault((name, ct), []).append(node)
+
+ def get(self, label: str, control_type: str | None = None) -> _SelectorNode | None:
+ """Return the first element matching label, optionally filtered by control_type."""
+ if control_type:
+ nodes = self._by_label_type.get((label, control_type), [])
+ else:
+ nodes = self._by_name.get(label, [])
+ return nodes[0] if nodes else None
+
+ def get_all(self, label: str, control_type: str | None = None) -> list[_SelectorNode]:
+ """Return all elements matching label, optionally filtered by control_type."""
+ if control_type:
+ return list(self._by_label_type.get((label, control_type), []))
+ return list(self._by_name.get(label, []))
+
+ def find(self, label: str) -> list[_SelectorNode]:
+ """Case-insensitive partial label match. Useful when exact name is unknown."""
+ label_lower = label.lower()
+ results = []
+ for name, nodes in self._by_name.items():
+ if label_lower in name.lower():
+ results.extend(nodes)
+ return results
+
+ def xpath_of(self, label: str, control_type: str | None = None) -> str | None:
+ """Shortcut: return xpath of first matching element, or None."""
+ node = self.get(label, control_type)
+ return node.xpath if node else None
+
+ def hwnd_of(self, label: str, control_type: str | None = None) -> int | None:
+ """Shortcut: return hwnd of first matching element, or None."""
+ node = self.get(label, control_type)
+ return node.hwnd if node else None
+
+ def __getitem__(self, label: str) -> _SelectorNode:
+ node = self.get(label)
+ if node is None:
+ raise KeyError(f'No element with label {label!r}')
+ return node
+
+ def __contains__(self, label: str) -> bool:
+ return label in self._by_name
+
+ def __len__(self) -> int:
+ return sum(len(v) for v in self._by_name.values())
+
+ def keys(self) -> list[str]:
+ return list(self._by_name.keys())
+
+ def __repr__(self) -> str:
+ return f'SelectorMap({len(self._by_name)} labels, {len(self)} elements)'