An AI Agent that interacts with Windows OS at GUI level.
Python
Replace xpath lookups with selector map
jeomone7f18917e48b
diff --git a/tests/unit/tree/test_tree_views.py b/tests/unit/tree/test_tree_views.pyindex b82fbe6..fa99a0a 100644--- a/tests/unit/tree/test_tree_views.py+++ b/tests/unit/tree/test_tree_views.py@@ -21,8 +21,7 @@ def sample_interactive_node(sample_bbox, sample_center):control_type="Button",window_name="App",bounding_box=sample_bbox,- center=sample_center,- is_focused=True+ center=sample_center)@pytest.fixture@@ -31,14 +30,8 @@ def sample_scrollable_node(sample_bbox, sample_center):name="Pane",control_type="Pane",window_name="App",- xpath="/path",bounding_box=sample_bbox,- center=sample_center,- horizontal_scrollable=False,- horizontal_scroll_percent=0.0,- vertical_scrollable=True,- vertical_scroll_percent=50.0,- is_focused=False+ center=sample_center)class TestTreeViews:@@ -53,8 +46,8 @@ class TestTreeViews:def test_tree_state_interactive_string(self, sample_interactive_node):state = TreeState(interactive_nodes=[sample_interactive_node])s = state.interactive_elements_to_string()- assert "0|App|Button|Button|(100,200)|True" in s- assert "# id|window|control_type|name|coords|focus" in s+ assert "0|App|Button|Button|(100,200)|{}" in s+ assert "# id|window|control_type|name|coords|metadata" in sdef test_tree_state_scrollable_string(self, sample_interactive_node, sample_scrollable_node):state = TreeState(@@ -63,5 +56,15 @@ class TestTreeViews:)s = state.scrollable_elements_to_string()# id should be 1 since there is 1 interactive node- assert "1|App|Pane|Pane|(100,200)|False|0.0|True|50.0|False" in s- assert "# id|window|control_type|name|coords|h_scroll|h_pct|v_scroll|v_pct|focus" in s\ No newline at end of file+ assert "1|App|Pane|Pane|(100,200)|{}" in s+ assert "# id|window|control_type|name|coords|metadata" in s++ def test_selector_map(self, sample_interactive_node, sample_scrollable_node):+ state = TreeState(+ interactive_nodes=[sample_interactive_node],+ scrollable_nodes=[sample_scrollable_node]+ )+ selector = state.build_selector_map()+ assert selector.node_of(0) is sample_interactive_node+ assert selector.node_of(1) is sample_scrollable_node+ assert selector.center_of(0).to_string() == "(100,200)"diff --git a/windows_use/agent/desktop/service.py b/windows_use/agent/desktop/service.pyindex de1b6fe..a93f124 100644--- a/windows_use/agent/desktop/service.py+++ b/windows_use/agent/desktop/service.py@@ -361,10 +361,16 @@ class Desktop:def get_element_handle_from_label(self,label:int)->uia.Control:tree_state=self.desktop_state.tree_state- element_node=tree_state.interactive_nodes[label]- xpath=element_node.xpath- element_handle=self.get_element_from_xpath(xpath)- return element_handle+ selector=tree_state.build_selector_map()+ element_node=selector.node_of(label)+ if element_node is None:+ raise ValueError(f'No element found for label {label}')+ control=selector.control_of(label)+ if control is not None:+ return control+ if element_node.hwnd:+ return uia.ControlFromHandle(element_node.hwnd)+ raise ValueError(f'No live control available for label {label}')def get_coordinates_from_label(self,label:int)->tuple[int,int]:element_handle=self.get_element_handle_from_label(label)@@ -597,72 +603,6 @@ class Desktop:windows = []return windows,window_handles- def get_xpath_from_element(self,element:uia.Control):- current=element- if current is None:- return ""- path_parts=[]- while current is not None:- parent=current.GetParentControl()- if parent is None:- # we are at the root node- path_parts.append(f'{current.ControlTypeName}')- break- children=parent.GetChildren()- same_type_children=["-".join(map(lambda x:str(x),child.GetRuntimeId())) for child in children if child.ControlType==current.ControlType]- index=same_type_children.index("-".join(map(lambda x:str(x),current.GetRuntimeId())))- if same_type_children:- path_parts.append(f'{current.ControlTypeName}[{index+1}]')- else:- path_parts.append(f'{current.ControlTypeName}')- current=parent- path_parts.reverse()- xpath="/".join(path_parts)- return xpath-- def get_element_from_window_xpath(self, handle: int, xpath: str) -> uia.Control:- """Resolve a window-relative xpath (as stored in TreeElementNode.xpath) to a live UIA Control.-- Starts traversal from ControlFromHandle(handle) and skips the first xpath- component (the window's own ControlTypeName), making it faster and independent- of the window's position in the global desktop tree.- """- pattern = re.compile(r'(\w+)(?:\[(\d+)\])?')- parts = xpath.split('/')- element = uia.ControlFromHandle(handle)- for part in parts[1:]: # skip first component (window's own type)- match = pattern.fullmatch(part)- if match is None:- continue- control_type, index = match.groups()- index = int(index) if index else None- children = element.GetChildren()- same_type_children = [x for x in children if x.ControlTypeName == control_type]- if not same_type_children:- raise ValueError(f'No child of type {control_type!r} found at xpath step {part!r}')- element = same_type_children[(index - 1) if index else 0]- return element-- def get_element_from_xpath(self,xpath:str)->uia.Control:- ROOT_CONTROL_TYPE="PaneControl"- pattern = re.compile(r'(\w+)(?:\[(\d+)\])?')- parts=[ROOT_CONTROL_TYPE]+xpath.split("/")- root=uia.GetRootControl()- element=root- for part in parts[1:]:- match=pattern.fullmatch(part)- if match is None:- continue- control_type, index=match.groups()- index=int(index) if index else None- children=element.GetChildren()- same_type_children=list(filter(lambda x:x.ControlTypeName==control_type,children))- if index:- element=same_type_children[index-1]- else:- element=same_type_children[0]- return element-def get_windows_version(self)->str:if self._cached_windows_version is not None:return self._cached_windows_versiondiff --git a/windows_use/agent/tree/service.py b/windows_use/agent/tree/service.pyindex 5c83a06..faed0f0 100644--- a/windows_use/agent/tree/service.py+++ b/windows_use/agent/tree/service.py@@ -217,8 +217,8 @@ class Tree:'bounding_box':bounding_box,'center':center,'window_name':window_name,- 'xpath':popped.xpath,'hwnd':popped.hwnd,+ 'control':node,'metadata':metadata}))elif self.element_has_child_element(node,'link','heading'):@@ -239,8 +239,8 @@ class Tree:'bounding_box':bounding_box,'center':center,'window_name':window_name,- 'xpath':popped.xpath,'hwnd':popped.hwnd,+ 'control':node,'metadata':metadata}))@@ -250,7 +250,7 @@ class Tree:dom_interactive_nodes:Optional[list[TreeElementNode]]=None, dom_informative_nodes:Optional[list[TextElementNode]]=None,is_dom:bool=False, is_dialog:bool=False,element_cache_req:Optional[Any]=None, children_cache_req:Optional[Any]=None,- current_xpath:str='', hwnd:int=0):+ hwnd:int=0):try:# Build cached control if caching is enabledif not hasattr(node, '_is_cached') and element_cache_req:@@ -292,8 +292,8 @@ class Tree:'vertical_scrollable':scroll_pattern.VerticallyScrollable,'vertical_scroll_percent':round(scroll_pattern.VerticalScrollPercent,2) if scroll_pattern.VerticallyScrollable else 0,'window_name':window_name,- 'xpath':current_xpath,'hwnd':hwnd,+ 'control':node,'metadata':metadata}))except Exception:@@ -474,8 +474,8 @@ class Tree:'bounding_box':bounding_box,'center':center,'window_name':window_name,- 'xpath':current_xpath,'hwnd':hwnd,+ 'control':node,'metadata':metadata})dom_interactive_nodes.append(tree_node)@@ -489,8 +489,8 @@ class Tree:'bounding_box':bounding_box,'center':center,'window_name':window_name,- 'xpath':current_xpath,'hwnd':hwnd,+ 'control':node,'metadata':metadata})interactive_nodes.append(tree_node)@@ -526,29 +526,12 @@ class Tree:# Phase 3: Cached Children Retrievalchildren = CachedControlHelper.get_cached_children(node, children_cache_req)- # Incrementally build xpath for each child in natural order,- # then iterate in traversal order (reversed for non-DOM apps).- type_counts: dict[str, int] = {}- for child in children:- t = child.CachedControlTypeName- type_counts[t] = type_counts.get(t, 0) + 1-- type_position: dict[str, int] = {}- child_xpaths: list[str] = []- for child in children:- t = child.CachedControlTypeName- type_position[t] = type_position.get(t, 0) + 1- suffix = f'[{type_position[t]}]' if type_counts[t] > 1 else ''- child_xpaths.append(f'{current_xpath}/{t}{suffix}')-# enumerate preserves original index so reversed iteration still maps correctlytraversal = list(enumerate(children))if not is_dom:traversal = list(reversed(traversal))for orig_idx, child in traversal:- child_xpath = child_xpaths[orig_idx]-# Check if the child is a DOM elementif is_browser and child.CachedAutomationId=="RootWebArea":bounding_box=child.CachedBoundingRectangle@@ -557,7 +540,7 @@ class Tree:height=bounding_box.height())self.dom=child# enter DOM subtree- self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=True, is_dialog=is_dialog, element_cache_req=element_cache_req, children_cache_req=children_cache_req, current_xpath=child_xpath, hwnd=hwnd)+ self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=True, is_dialog=is_dialog, element_cache_req=element_cache_req, children_cache_req=children_cache_req, hwnd=hwnd)# Check if the child is a dialogelif isinstance(child,WindowControl):if not child.CachedIsOffscreen:@@ -577,10 +560,10 @@ class Tree:if is_modal:interactive_nodes.clear()# enter dialog subtree- self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=is_dom, is_dialog=True, element_cache_req=element_cache_req, children_cache_req=children_cache_req, current_xpath=child_xpath, hwnd=hwnd)+ self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=is_dom, is_dialog=True, element_cache_req=element_cache_req, children_cache_req=children_cache_req, hwnd=hwnd)else:# normal non-dialog children- self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=is_dom, is_dialog=is_dialog, element_cache_req=element_cache_req, children_cache_req=children_cache_req, current_xpath=child_xpath, hwnd=hwnd)+ self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=is_dom, is_dialog=is_dialog, element_cache_req=element_cache_req, children_cache_req=children_cache_req, hwnd=hwnd)except Exception as e:logger.error(f"Error in tree_traversal: {e}", exc_info=True)raise@@ -616,9 +599,8 @@ class Tree:interactive_nodes, dom_interactive_nodes, dom_informative_nodes, scrollable_nodes = [], [], [], []window_name=(node.Name or '').strip()window_name=self.window_name_correction(window_name)- current_xpath=node.ControlTypeName- self.tree_traversal(node, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=False, is_dialog=False, element_cache_req=element_cache_req, children_cache_req=children_cache_req, current_xpath=current_xpath, hwnd=handle)+ self.tree_traversal(node, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=False, is_dialog=False, element_cache_req=element_cache_req, children_cache_req=children_cache_req, hwnd=handle)logger.debug(f'Window name:{window_name}')logger.debug(f'Interactive nodes:{len(interactive_nodes)}')if is_browser:diff --git a/windows_use/agent/tree/views.py b/windows_use/agent/tree/views.pyindex bac6628..5c46e9d 100644--- a/windows_use/agent/tree/views.py+++ b/windows_use/agent/tree/views.py@@ -7,6 +7,7 @@ EMPTY_MESSAGE="No elements found"if TYPE_CHECKING:from windows_use.uia.core import Rect+ from windows_use.uia.controls import Control@dataclassclass TreeState:@@ -109,8 +110,8 @@ class TreeElementNode:name: str=''control_type: str=''window_name: str=''- xpath: str=''hwnd: int=0+ control: Optional['Control']=Nonemetadata:dict[str,Any]=field(default_factory=dict)def update_from_node(self,node:'TreeElementNode'):@@ -134,8 +135,8 @@ class ScrollElementNode:window_name: strbounding_box: BoundingBoxcenter: Center- xpath: str=''hwnd: int=0+ control: Optional['Control']=Nonemetadata:dict[str,Any]=field(default_factory=dict)# Legacy method kept for compatibility@@ -167,13 +168,21 @@ class SelectorMap(dict):Usage:selector = tree_state.build_selector_map()node = selector[0]- xpath = selector.xpath_of(0)+ control = selector.control_of(0)hwnd = selector.hwnd_of(0)"""- def xpath_of(self, index: int) -> str | None:+ def node_of(self, index: int) -> _SelectorNode | None:node = self.get(index)- return node.xpath if node else None+ return node++ def control_of(self, index: int) -> Optional['Control']:+ node = self.get(index)+ return node.control if node else None++ def center_of(self, index: int) -> Optional[Center]:+ node = self.get(index)+ return node.center if node else Nonedef hwnd_of(self, index: int) -> int | None:node = self.get(index)