Skip to content

Commit 34f82b4

Browse files
committed
Optimize UIA tree caching to minimize redundant COM calls
1 parent 3ae9b92 commit 34f82b4

1 file changed

Lines changed: 22 additions & 12 deletions

File tree

windows_use/agent/tree/cache_utils.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -139,21 +139,31 @@ def get_cached_children(node: Control, cache_request: Optional[CacheRequest] = N
139139
"""
140140
if cache_request is None:
141141
cache_request = CacheRequestFactory.create_tree_traversal_cache()
142+
143+
# Optimization: To avoid redundant COM property fetches for the parent node,
144+
# we only need the Children scope. If TreeScope_Element is omitted,
145+
# UI Automation only fetches the children and their properties.
146+
# We clone the request to avoid modifying shared cache request objects.
147+
req_clone = cache_request.Clone()
148+
req_clone.TreeScope = TreeScope.TreeScope_Children
142149

143-
# Ensure the cache request includes children
144-
# Note: We do NOT set this here to avoid modifying shared cache request objects
145-
# The caller is responsible for providing a CacheRequest with TreeScope_Children
146-
if (cache_request.TreeScope & TreeScope.TreeScope_Children) == 0:
147-
logger.warning("Cache request passed to get_cached_children does not have Children scope!")
148-
149-
# Try to use existing cache first if available
150150
try:
151-
# Build updated cache that includes children
152-
cached_node = node.BuildUpdatedCache(cache_request)
153-
children = cached_node.GetCachedChildren()
151+
# Bypass `Control.CreateControlFromElement` when building the cache.
152+
# When TreeScope_Element is omitted, BuildUpdatedCache returns a dummy element
153+
# which does not have valid properties (like CurrentControlType),
154+
# so our python wrapper would crash. We just use the raw IUIAutomationElement.
155+
updated_element = node.Element.BuildUpdatedCache(req_clone.check_request)
156+
element_array = updated_element.GetCachedChildren()
154157

155-
for child in children:
156-
child._is_cached = True
158+
children = []
159+
if element_array:
160+
length = element_array.Length
161+
for i in range(length):
162+
child_elem = element_array.GetElement(i)
163+
child_control = Control.CreateControlFromElement(child_elem)
164+
if child_control:
165+
child_control._is_cached = True
166+
children.append(child_control)
157167

158168
logger.debug(f"Retrieved {len(children)} cached children (newly built)")
159169
return children

0 commit comments

Comments
 (0)