Skip to content

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

Python

Apply ruff fixes across codebase (excluding uia module)

jeomonf00e1d384dd6
diff --git a/tests/test_agent_startup.py b/tests/test_agent_startup.py
index 97262b0..0478d23 100644
--- a/tests/test_agent_startup.py
+++ b/tests/test_agent_startup.py
@@ -1,43 +1,39 @@
-import os
-import sys
import time
+
def log(msg):
print(f"[DEBUG] {time.time():.3f}: {msg}", flush=True)
log("Starting main.py debug...")
log("Importing load_dotenv...")
-from dotenv import load_dotenv
+from dotenv import load_dotenv # noqa: E402
+
log("Calling load_dotenv...")
load_dotenv()
log("Importing ChatGoogle...")
-from windows_use.providers.google import ChatGoogle
+from windows_use.providers.google import ChatGoogle # noqa: E402
+
log("Importing ChatAnthropic...")
-from windows_use.providers.anthropic import ChatAnthropic
log("Importing ChatOllama...")
-from windows_use.providers.ollama import ChatOllama
log("Importing ChatMistral...")
-from windows_use.providers.mistral import ChatMistral
log("Importing ChatAzureOpenAI...")
-from windows_use.providers.azure_openai import ChatAzureOpenAI
log("Importing ChatOpenRouter...")
-from windows_use.providers.open_router import ChatOpenRouter
log("Importing ChatGroq...")
-from windows_use.providers.groq import ChatGroq
log("Importing Agent and Browser...")
-from windows_use.agent import Agent, Browser
+from windows_use.agent import Agent, Browser # noqa: E402
+
def main():
log("Inside main()...")
log("Initializing ChatGoogle...")
llm=ChatGoogle(model="gemini-2.5-flash-lite",thinking_budget=0, temperature=0.7)
-
+
log("Initializing Agent...")
agent = Agent(llm=llm, browser=Browser.EDGE, use_vision=False,use_annotation=False, auto_minimize=False)
-
+
log("Agent initialized. Calling input()...")
# In a real run, this would be input()
# But for our test, we'll just simulate it or read from a pipe if needed.
@@ -46,7 +42,7 @@ def main():
# query = sys.stdin.readline()
query = "test"
log(f"Received query: {query}")
-
+
log("Calling agent.print_response...")
agent.print_response(query=query)
log("Done.")
diff --git a/tests/test_imports.py b/tests/test_imports.py
index 05a3508..7552bbe 100644
--- a/tests/test_imports.py
+++ b/tests/test_imports.py
@@ -1,7 +1,8 @@
-import sys
import time
+
import pytest
+
def check_import(module_name, from_list=None):
print(f"Importing {module_name}...", end=" ", flush=True)
start = time.time()
diff --git a/tests/test_uia_caching_integration.py b/tests/test_uia_caching_integration.py
index 92fe011..5c2b0af 100644
--- a/tests/test_uia_caching_integration.py
+++ b/tests/test_uia_caching_integration.py
@@ -5,10 +5,11 @@ This script tests the caching implementation.
Note: enable_caching and other_apps/active_app arguments have been removed in latest Tree API.
"""
-import time
import logging
-from windows_use.agent.tree.service import Tree
+import time
+
from windows_use.agent.desktop.service import Desktop
+from windows_use.agent.tree.service import Tree
# Configure logging to see cache performance stats
logging.basicConfig(
@@ -20,29 +21,29 @@ logger = logging.getLogger(__name__)
def test_caching_performance():
"""Test Tree.get_state with current API."""
-
+
logger.info("=" * 70)
logger.info("UIA TREE STATE TEST")
logger.info("=" * 70)
-
+
# Create desktop instance
desktop = Desktop()
-
+
# Test get_state
logger.info("\n" + "=" * 70)
logger.info("TESTING Tree.get_state")
logger.info("=" * 70)
-
+
tree = Tree(desktop)
start_time = time.perf_counter()
-
+
try:
# Get actual handles from desktop to make a real call if possible
# or just use dummy handles for a unit-like integration test.
# the Desktop.get_state uses get_controls_handles etc.
state = tree.get_state(active_window_handle=None, other_windows_handles=[])
duration = time.perf_counter() - start_time
-
+
logger.info(f"Time: {duration:.3f}s")
if state.interactive_nodes is not None:
logger.info(f"Interactive elements found: {len(state.interactive_nodes)}")
diff --git a/tests/test_uia_implementation.py b/tests/test_uia_implementation.py
index ac3be94..de1dd97 100644
--- a/tests/test_uia_implementation.py
+++ b/tests/test_uia_implementation.py
@@ -3,43 +3,43 @@ Quick test to verify the implementation of FindAll, FindFirst, and cache methods
This is a simple smoke test to ensure the methods are callable and don't crash.
"""
-import sys
import os
+import sys
# Add the parent directory to the path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from windows_use.uia import core
from windows_use.uia.controls import Control
-from windows_use.uia.enums import TreeScope, PropertyId, ControlType
+from windows_use.uia.enums import ControlType, PropertyId, TreeScope
def test_condition_creation():
"""Test that condition creation functions work."""
print("Testing condition creation...")
-
+
try:
# Test basic conditions
true_cond = core.CreateTrueCondition()
assert true_cond is not None, "CreateTrueCondition failed"
-
+
false_cond = core.CreateFalseCondition()
assert false_cond is not None, "CreateFalseCondition failed"
-
+
# Test property condition
prop_cond = core.CreatePropertyCondition(PropertyId.ControlTypeProperty, ControlType.WindowControl)
assert prop_cond is not None, "CreatePropertyCondition failed"
-
+
# Test logical conditions
and_cond = core.CreateAndCondition(true_cond, prop_cond)
assert and_cond is not None, "CreateAndCondition failed"
-
+
or_cond = core.CreateOrCondition(true_cond, false_cond)
assert or_cond is not None, "CreateOrCondition failed"
-
+
not_cond = core.CreateNotCondition(false_cond)
assert not_cond is not None, "CreateNotCondition failed"
-
+
print(" ✓ All condition creation functions work")
return True
except Exception as e:
@@ -50,26 +50,26 @@ def test_condition_creation():
def test_find_methods():
"""Test FindAll and FindFirst methods."""
print("Testing Find methods...")
-
+
try:
# Get root element (desktop) properly
from windows_use.uia.core import _AutomationClient
root_element = _AutomationClient.instance().IUIAutomation.GetRootElement()
root = Control.CreateControlFromElement(root_element)
-
+
# Test FindAll
condition = core.CreatePropertyCondition(PropertyId.ControlTypeProperty, ControlType.WindowControl)
windows = root.FindAll(TreeScope.TreeScope_Children, condition)
assert isinstance(windows, list), "FindAll should return a list"
print(f" ✓ FindAll works - found {len(windows)} windows")
-
+
# Test FindFirst
first_window = root.FindFirst(TreeScope.TreeScope_Children, condition)
if first_window:
print(f" ✓ FindFirst works - found window: {first_window.Name}")
else:
print(" ✓ FindFirst works - no window found (this is ok)")
-
+
return True
except Exception as e:
print(f" ✗ Find methods failed: {e}")
@@ -81,24 +81,24 @@ def test_find_methods():
def test_cache_methods():
"""Test cache-related methods."""
print("Testing cache methods...")
-
+
try:
# Get root element (desktop) properly
from windows_use.uia.core import _AutomationClient
root_element = _AutomationClient.instance().IUIAutomation.GetRootElement()
root = Control.CreateControlFromElement(root_element)
-
+
# Create a cache request
cache_request = core.CreateCacheRequest()
cache_request.TreeScope = TreeScope.TreeScope_Element
cache_request.AddProperty(PropertyId.NameProperty)
-
+
# Test FindAllBuildCache
condition = core.CreatePropertyCondition(PropertyId.ControlTypeProperty, ControlType.WindowControl)
windows = root.FindAllBuildCache(TreeScope.TreeScope_Children, condition, cache_request)
assert isinstance(windows, list), "FindAllBuildCache should return a list"
print(f" ✓ FindAllBuildCache works - found {len(windows)} windows")
-
+
# Test FindFirstBuildCache
first_window = root.FindFirstBuildCache(TreeScope.TreeScope_Children, condition, cache_request)
if first_window:
@@ -107,21 +107,21 @@ def test_cache_methods():
print(f" ✓ FindFirstBuildCache works - cached name: {cached_name}")
else:
print(" ✓ FindFirstBuildCache works - no window found (this is ok)")
-
+
# Test GetCachedChildren (may fail if not cached, which is expected)
try:
children = root.GetCachedChildren()
print(f" ✓ GetCachedChildren works - found {len(children)} children")
- except:
+ except Exception:
print(" ✓ GetCachedChildren works (no cached children, as expected)")
-
+
# Test GetCachedParent (may return None, which is expected)
parent = root.GetCachedParent()
if parent:
- print(f" ✓ GetCachedParent works - found parent")
+ print(" ✓ GetCachedParent works - found parent")
else:
print(" ✓ GetCachedParent works (no cached parent, as expected)")
-
+
return True
except Exception as e:
print(f" ✗ Cache methods failed: {e}")
@@ -135,35 +135,35 @@ def main():
print("UI Automation Implementation Test")
print("=" * 60)
print()
-
+
results = []
-
+
# Run tests
results.append(("Condition Creation", test_condition_creation()))
print()
-
+
results.append(("Find Methods", test_find_methods()))
print()
-
+
results.append(("Cache Methods", test_cache_methods()))
print()
-
+
# Summary
print("=" * 60)
print("Test Summary")
print("=" * 60)
-
+
passed = sum(1 for _, result in results if result)
total = len(results)
-
+
for name, result in results:
status = "PASSED" if result else "FAILED"
symbol = "✓" if result else "✗"
print(f"{symbol} {name}: {status}")
-
+
print()
print(f"Total: {passed}/{total} tests passed")
-
+
if passed == total:
print("\n🎉 All tests passed!")
return 0
diff --git a/tests/test_uia_init.py b/tests/test_uia_init.py
index e0fb82e..e606e8c 100644
--- a/tests/test_uia_init.py
+++ b/tests/test_uia_init.py
@@ -1,6 +1,7 @@
-import comtypes.client
import time
+import comtypes.client
+
print("Attempting to get UIAutomationCore module...")
start = time.time()
try:
diff --git a/tests/unit/agent/agent_prompt/test_agent_prompt_service.py b/tests/unit/agent/agent_prompt/test_agent_prompt_service.py
index e67a49e..817e5ec 100644
--- a/tests/unit/agent/agent_prompt/test_agent_prompt_service.py
+++ b/tests/unit/agent/agent_prompt/test_agent_prompt_service.py
@@ -1,9 +1,11 @@
# tests/unit/agent/agent_prompt/test_agent_prompt_service.py
-import pytest
from unittest.mock import MagicMock, patch
+
+import pytest
+
from windows_use.agent.context.service import Context
-from windows_use.agent.desktop.views import DesktopState, Browser
+from windows_use.agent.desktop.views import Browser, DesktopState
class TestContext:
@@ -91,4 +93,4 @@ class TestContext:
assert "Human:" in msg.content
assert "test query" in msg.content
assert "(100,200)" in msg.content
- assert "Interactive elements" in msg.content
\ No newline at end of file
+ assert "Interactive elements" in msg.content
diff --git a/tests/unit/agent/agent_registry/test_agent_registry_service.py b/tests/unit/agent/agent_registry/test_agent_registry_service.py
index 64160a1..4ce228a 100644
--- a/tests/unit/agent/agent_registry/test_agent_registry_service.py
+++ b/tests/unit/agent/agent_registry/test_agent_registry_service.py
@@ -1,11 +1,13 @@
# tests/unit/agent/agent_registry/test_agent_registry_service.py
-import pytest
from unittest.mock import MagicMock
+
+import pytest
+
from windows_use.agent.registry.service import Registry
-from windows_use.agent.registry.views import ToolResult
from windows_use.tools import Tool
+
class TestRegistry:
"""Tests for the Registry service class."""
diff --git a/tests/unit/agent/agent_registry/test_agent_registry_views.py b/tests/unit/agent/agent_registry/test_agent_registry_views.py
index a240de9..35b8849 100644
--- a/tests/unit/agent/agent_registry/test_agent_registry_views.py
+++ b/tests/unit/agent/agent_registry/test_agent_registry_views.py
@@ -1,8 +1,10 @@
# tests/unit/agent/agent_registry/test_agent_registry_views.py
import pytest
+
from windows_use.agent.registry.views import ToolResult
+
class TestAgentRegistryViews:
"""
Tests for the data models in windows_use.agent.registry.views.
diff --git a/tests/unit/agent/agent_tools/test_agent_tools_service.py b/tests/unit/agent/agent_tools/test_agent_tools_service.py
index 2c51760..891ce2e 100644
--- a/tests/unit/agent/agent_tools/test_agent_tools_service.py
+++ b/tests/unit/agent/agent_tools/test_agent_tools_service.py
@@ -1,28 +1,29 @@
# tests/unit/agent/agent_tools/test_agent_tools_service.py
-import pytest
-from unittest.mock import MagicMock, patch, mock_open
-from typing import Literal
from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+from windows_use.agent.desktop.service import Desktop
from windows_use.agent.tools.service import (
- done_tool,
app_tool,
- shell_tool,
click_tool,
- type_tool,
- scroll_tool,
- move_tool,
- shortcut_tool,
- wait_tool,
- scrape_tool,
desktop_tool,
- memory_tool,
+ done_tool,
file_tool,
+ memory_tool,
+ move_tool,
+ multi_edit_tool,
multi_select_tool,
- multi_edit_tool
+ scrape_tool,
+ scroll_tool,
+ shell_tool,
+ shortcut_tool,
+ type_tool,
+ wait_tool,
)
-from windows_use.agent.desktop.service import Desktop
+
class TestAgentToolsService:
"""
@@ -73,16 +74,16 @@ class TestAgentToolsService:
"""Test type_tool delegation."""
type_tool.invoke(**{"loc": [10, 20], "text": "hello", "clear": "true", "caret_position": "start", "press_enter": "true", "desktop": mock_desktop})
mock_desktop.type.assert_called_once_with(
- loc=[10, 20],
- text="hello",
- caret_position="start",
- clear="true",
+ loc=[10, 20],
+ text="hello",
+ caret_position="start",
+ clear="true",
press_enter="true"
)
def test_scroll_tool(self, mock_desktop):
"""Test scroll_tool delegation."""
- mock_desktop.scroll.return_value = None
+ mock_desktop.scroll.return_value = None
scroll_tool.invoke(**{"loc": [10, 20], "type": "vertical", "direction": "up", "wheel_times": 3, "desktop": mock_desktop})
mock_desktop.scroll.assert_called_once_with([10, 20], "vertical", "up", 3)
diff --git a/tests/unit/agent/agent_tools/test_agent_tools_views.py b/tests/unit/agent/agent_tools/test_agent_tools_views.py
index 56430bb..a9eadb1 100644
--- a/tests/unit/agent/agent_tools/test_agent_tools_views.py
+++ b/tests/unit/agent/agent_tools/test_agent_tools_views.py
@@ -1,26 +1,24 @@
# tests/unit/agent/agent_tools/test_agent_tools_views.py
+
import pytest
from pydantic import ValidationError
-from typing import Literal
-from windows_use.agent.tools.views import SharedBaseModel
from windows_use.agent.tools.service import (
App,
+ Click,
+ Desktop,
Done,
Memory,
- Click,
- Shell,
- Type,
- MultiSelect,
- MultiEdit,
- Scroll,
Move,
+ Scrape,
+ Scroll,
+ Shell,
Shortcut,
+ Type,
Wait,
- Scrape,
- Desktop,
)
+from windows_use.agent.tools.views import SharedBaseModel
THOUGHT = "test thought"
diff --git a/tests/unit/agent/test_agent_service.py b/tests/unit/agent/test_agent_service.py
index 001e232..5d3184e 100644
--- a/tests/unit/agent/test_agent_service.py
+++ b/tests/unit/agent/test_agent_service.py
@@ -1,14 +1,15 @@
# tests/unit/agent/test_agent_service.py
-import pytest
from unittest.mock import MagicMock, patch
-import json
+
+import pytest
+
from windows_use.agent.service import Agent
from windows_use.agent.views import AgentResult
-from windows_use.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
from windows_use.providers.events import LLMEvent, LLMEventType, ToolCall
from windows_use.providers.views import TokenUsage
+
class TestAgent:
"""
Tests for the Agent class in windows_use.agent.service.
diff --git a/tests/unit/agent/test_agent_utils.py b/tests/unit/agent/test_agent_utils.py
index ab5aba8..4d2eb48 100644
--- a/tests/unit/agent/test_agent_utils.py
+++ b/tests/unit/agent/test_agent_utils.py
@@ -6,8 +6,9 @@
import pytest
try:
- from windows_use.agent.utils import read_file, json_parser
- from windows_use.agent.views import AgentData, Action
+ from windows_use.agent.utils import json_parser, read_file
+
+ from windows_use.agent.views import Action, AgentData # noqa: F401
from windows_use.messages import AIMessage
_UTILS_AVAILABLE = True
except ImportError:
@@ -15,8 +16,8 @@ except ImportError:
pytestmark = pytest.mark.skipif(not _UTILS_AVAILABLE, reason="agent.utils and AgentData/Action not in current codebase")
-import json
-from unittest.mock import MagicMock, patch
+import json # noqa: E402
+from unittest.mock import MagicMock, patch # noqa: E402
class TestAgentUtils:
@@ -43,7 +44,7 @@ class TestAgentUtils:
}
message = AIMessage(content=json.dumps(data))
agent_data = json_parser(message)
-
+
assert agent_data.thought == data["thought"]
assert agent_data.action.name == data["action"]["name"]
assert agent_data.action.params == data["action"]["params"]
@@ -57,7 +58,7 @@ class TestAgentUtils:
content = f"Here is the JSON:\n```json\n{json.dumps(data)}\n```"
message = AIMessage(content=content)
agent_data = json_parser(message)
-
+
assert agent_data.action.name == "done_tool"
def test_json_parser_invalid_json(self):
diff --git a/tests/unit/agent/test_agent_views.py b/tests/unit/agent/test_agent_views.py
index eb4739d..4728823 100644
--- a/tests/unit/agent/test_agent_views.py
+++ b/tests/unit/agent/test_agent_views.py
@@ -1,8 +1,8 @@
# tests/unit/agent/test_agent_views.py
-import pytest
from windows_use.agent.views import AgentResult
+
class TestAgentViews:
"""
Tests for the data models in windows_use.agent.views.
diff --git a/tests/unit/desktop/test_desktop_config.py b/tests/unit/desktop/test_desktop_config.py
index 9393f00..2b3a253 100644
--- a/tests/unit/desktop/test_desktop_config.py
+++ b/tests/unit/desktop/test_desktop_config.py
@@ -1,8 +1,8 @@
# tests/unit/desktop/test_desktop_config.py
-import pytest
from windows_use.agent.desktop.config import AVOIDED_APPS, EXCLUDED_APPS
+
class TestDesktopConfig:
def test_avoided_apps_type(self):
assert isinstance(AVOIDED_APPS, set)
diff --git a/tests/unit/desktop/test_desktop_init.py b/tests/unit/desktop/test_desktop_init.py
index 3c4924c..03c71c4 100644
--- a/tests/unit/desktop/test_desktop_init.py
+++ b/tests/unit/desktop/test_desktop_init.py
@@ -1,11 +1,14 @@
# tests/unit/desktop/test_desktop_init.py
-import pytest
from unittest.mock import MagicMock, patch
+
+import pytest
+
from windows_use.agent.desktop.service import Desktop
-from windows_use.agent.desktop.views import DesktopState, Window, Size, Status
+from windows_use.agent.desktop.views import DesktopState, Status, Window
from windows_use.agent.tree.views import BoundingBox
+
class TestDesktopService:
@pytest.fixture
def desktop(self):
@@ -24,12 +27,12 @@ class TestDesktopService:
def test_get_controls_handles(self, mock_text, mock_visible, mock_enum, desktop):
mock_visible.return_value = True
mock_text.return_value = "Some Window"
-
+
def side_effect(callback, lparam):
callback(12345, lparam)
return True
mock_enum.side_effect = side_effect
-
+
handles = desktop.get_controls_handles()
assert 12345 in handles
@@ -39,16 +42,16 @@ class TestDesktopService:
name="Notepad", is_browser=False, depth=0, status=Status.NORMAL,
bounding_box=BoundingBox(0,0,100,100,100,100), handle=123, process_id=456
)
-
+
with patch.object(desktop, 'get_controls_handles', return_value={123, 456}), \
patch.object(desktop, 'get_windows', return_value=([mock_window], {123})), \
patch.object(desktop, 'get_active_window', return_value=mock_window), \
patch.object(desktop.tree, 'get_state', return_value=MagicMock()), \
patch("windows_use.agent.desktop.service.get_current_desktop", return_value={"name": "Desktop 1"}), \
patch("windows_use.agent.desktop.service.get_all_desktops", return_value=[{"name": "Desktop 1"}]):
-
+
state = desktop.get_state()
-
+
assert isinstance(state, DesktopState)
assert state.active_window.handle == 123
- assert len(state.windows) == 0
\ No newline at end of file
+ assert len(state.windows) == 0
diff --git a/tests/unit/desktop/test_desktop_views.py b/tests/unit/desktop/test_desktop_views.py
index 702e635..963dec5 100644
--- a/tests/unit/desktop/test_desktop_views.py
+++ b/tests/unit/desktop/test_desktop_views.py
@@ -1,9 +1,11 @@
# tests/unit/desktop/test_desktop_views.py
import pytest
-from windows_use.agent.desktop.views import Window, DesktopState, Status, Size
+
+from windows_use.agent.desktop.views import DesktopState, Size, Status, Window
from windows_use.agent.tree.views import BoundingBox
+
@pytest.fixture
def sample_window():
return Window(
@@ -32,12 +34,12 @@ class TestDesktopViews:
windows=[sample_window],
active_window=sample_window
)
-
+
assert "Desktop 1" in state.active_desktop_to_string()
assert "Desktop 2" in state.desktops_to_string()
assert "Notepad" in state.active_window_to_string()
assert "Notepad" in state.windows_to_string()
-
+
# Test tabulate output roughly
assert "Name" in state.windows_to_string()
assert "Handle" in state.windows_to_string()
diff --git a/tests/unit/test_llm_events.py b/tests/unit/test_llm_events.py
index 7ec8e6b..5726848 100644
--- a/tests/unit/test_llm_events.py
+++ b/tests/unit/test_llm_events.py
@@ -1,16 +1,15 @@
-import pytest
-import json
-from unittest.mock import MagicMock, AsyncMock, patch
+from unittest.mock import MagicMock
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall
-from windows_use.providers.openai.llm import ChatOpenAI
from windows_use.messages import HumanMessage
+from windows_use.providers.events import LLMStreamEvent, LLMStreamEventType
+from windows_use.providers.openai.llm import ChatOpenAI
+
def create_mock_chunk(content=None, tool_calls=None, reasoning=None):
delta = MagicMock()
delta.content = content
delta.reasoning_content = reasoning
-
+
if tool_calls:
delta.tool_calls = []
for tc in tool_calls:
@@ -33,17 +32,17 @@ def create_mock_chunk(content=None, tool_calls=None, reasoning=None):
def test_stream_text_only():
provider = ChatOpenAI(model="gpt-4o")
-
+
mock_chunks = [
create_mock_chunk(content="Hello"),
create_mock_chunk(content=" world"),
create_mock_chunk(content="!")
]
-
+
provider.client.chat.completions.create = MagicMock(return_value=mock_chunks)
-
+
events = list(provider.stream([HumanMessage(content="test")]))
-
+
assert len(events) == 5
assert events[0] == LLMStreamEvent(type=LLMStreamEventType.TEXT_START)
assert events[1] == LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content="Hello")
@@ -53,17 +52,17 @@ def test_stream_text_only():
def test_stream_tool_only():
provider = ChatOpenAI(model="gpt-4o")
-
+
mock_chunks = [
create_mock_chunk(tool_calls=[{"id": "call_123", "name": "my_tool", "arguments": '{"arg"'} ]),
create_mock_chunk(tool_calls=[{"id": None, "name": None, "arguments": ':"val"'} ]),
create_mock_chunk(tool_calls=[{"id": None, "name": None, "arguments": '}'} ])
]
-
+
provider.client.chat.completions.create = MagicMock(return_value=mock_chunks)
-
+
events = list(provider.stream([HumanMessage(content="test")]))
-
+
assert len(events) == 1
assert events[0].type == LLMStreamEventType.TOOL_CALL
assert events[0].tool_call is not None
@@ -73,17 +72,17 @@ def test_stream_tool_only():
def test_stream_thinking_then_text():
provider = ChatOpenAI(model="o3-mini")
-
+
mock_chunks = [
create_mock_chunk(reasoning="Thinking"),
create_mock_chunk(reasoning="..."),
create_mock_chunk(content="Done thinking."),
]
-
+
provider.client.chat.completions.create = MagicMock(return_value=mock_chunks)
-
+
events = list(provider.stream([HumanMessage(content="test")]))
-
+
assert len(events) == 7
assert events[0] == LLMStreamEvent(type=LLMStreamEventType.THINK_START)
assert events[1] == LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content="Thinking")
diff --git a/tests/unit/test_openai_events.py b/tests/unit/test_openai_events.py
index 4711da1..2e07715 100644
--- a/tests/unit/test_openai_events.py
+++ b/tests/unit/test_openai_events.py
@@ -1,16 +1,14 @@
import asyncio
-import os
-import sys
+
import pytest
+from pydantic import BaseModel
-from windows_use.providers.openai.llm import ChatOpenAI
+from windows_use.messages import HumanMessage
from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType
-from windows_use.messages import HumanMessage, AIMessage, ToolMessage
+from windows_use.providers.openai.llm import ChatOpenAI
from windows_use.tools import Tool
-from pydantic import BaseModel
-
class DummyToolModel(BaseModel):
dummy: str
@@ -24,7 +22,7 @@ dummy_tool = Tool(
async def test_streaming_text():
print("=== Testing Streaming Text ===")
llm = ChatOpenAI(model="gpt-4o-mini", max_retries=1)
-
+
# MOCK OPENAI STREAM
from unittest.mock import MagicMock
class MockDelta:
@@ -52,10 +50,10 @@ async def test_streaming_text():
llm._is_reasoning_model = lambda: True
events_received = []
-
+
# Simple message
messages = [HumanMessage(content="Explain what a computer is in 2 short sentences.")]
-
+
for chunk in llm.stream(messages=messages):
assert isinstance(chunk, LLMStreamEvent), f"Expected LLMStreamEvent, got {type(chunk).__name__}"
print(f"[EVENT] {chunk.type.value}: {chunk.content}")
@@ -71,7 +69,7 @@ async def test_streaming_text():
async def test_streaming_tools():
print("\n=== Testing Streaming Tools ===")
llm = ChatOpenAI(model="gpt-4o-mini", max_retries=1)
-
+
# MOCK OPENAI STREAM
from unittest.mock import MagicMock
class MockToolFunction:
@@ -107,11 +105,11 @@ async def test_streaming_tools():
llm.client.chat.completions.create = mock_stream
llm._is_reasoning_model = lambda: False
-
+
events_received = []
-
+
messages = [HumanMessage(content="Call the dummy tool with the argument 'hello'.")]
-
+
for chunk in llm.stream(messages=messages, tools=[dummy_tool]):
assert isinstance(chunk, LLMStreamEvent), f"Expected LLMStreamEvent, got {type(chunk).__name__}"
print(f"[EVENT] {chunk.type.value}: {chunk.tool_call}")
@@ -125,7 +123,7 @@ async def test_streaming_tools():
async def test_invoke_text():
print("\n=== Testing Invoke Text ===")
llm = ChatOpenAI(model="gpt-4o-mini", max_retries=1)
-
+
# MOCK OPENAI INVOKE
from unittest.mock import MagicMock
class MockMessage:
@@ -147,7 +145,7 @@ async def test_invoke_text():
llm.client.chat.completions.create = mock_create
llm._is_reasoning_model = lambda: False
-
+
messages = [HumanMessage(content="Say Hello via invoke")]
result = llm.invoke(messages=messages)
@@ -161,7 +159,7 @@ async def test_invoke_text():
async def test_ainvoke_tools():
print("\n=== Testing Ainvoke Tools ===")
llm = ChatOpenAI(model="gpt-4o-mini", max_retries=1)
-
+
# MOCK OPENAI AINVOKE
from unittest.mock import MagicMock
class MockToolFunction:
@@ -194,10 +192,10 @@ async def test_ainvoke_tools():
llm.aclient.chat.completions.create = mock_acreate
llm._is_reasoning_model = lambda: False
-
+
messages = [HumanMessage(content="Call the dummy tool with 'world'")]
result = await llm.ainvoke(messages=messages, tools=[dummy_tool])
-
+
assert isinstance(result, LLMEvent), f"Expected LLMEvent from ainvoke, got {type(result).__name__}"
assert result.type == LLMEventType.TOOL_CALL
assert result.tool_call.name == "dummy_tool"
diff --git a/tests/unit/tree/test_tree_config.py b/tests/unit/tree/test_tree_config.py
index 27029b3..a0af152 100644
--- a/tests/unit/tree/test_tree_config.py
+++ b/tests/unit/tree/test_tree_config.py
@@ -1,12 +1,12 @@
# tests/unit/tree/test_tree_config.py
-import pytest
from windows_use.agent.tree.config import (
- INTERACTIVE_CONTROL_TYPE_NAMES,
DEFAULT_ACTIONS,
INFORMATIVE_CONTROL_TYPE_NAMES,
+ INTERACTIVE_CONTROL_TYPE_NAMES,
)
+
class TestTreeConfig:
def test_interactive_control_type_names_type(self):
assert isinstance(INTERACTIVE_CONTROL_TYPE_NAMES, set)
diff --git a/tests/unit/tree/test_tree_init.py b/tests/unit/tree/test_tree_init.py
index 1521072..f08fd1e 100644
--- a/tests/unit/tree/test_tree_init.py
+++ b/tests/unit/tree/test_tree_init.py
@@ -1,10 +1,13 @@
# tests/unit/tree/test_tree_init.py
-import pytest
from unittest.mock import MagicMock, patch
-from windows_use.agent.tree.service import Tree
-from windows_use.agent.tree.views import TreeState, BoundingBox
+
+import pytest
+
from windows_use.agent.desktop.views import Size
+from windows_use.agent.tree.service import Tree
+from windows_use.agent.tree.views import TreeState
+
class TestTreeService:
@pytest.fixture
diff --git a/tests/unit/tree/test_tree_utils.py b/tests/unit/tree/test_tree_utils.py
index 64abd38..0d928ea 100644
--- a/tests/unit/tree/test_tree_utils.py
+++ b/tests/unit/tree/test_tree_utils.py
@@ -1,9 +1,10 @@
# tests/unit/tree/test_tree_utils.py
-import pytest
from unittest.mock import MagicMock, patch
+
from windows_use.agent.tree.utils import random_point_within_bounding_box
+
class TestTreeUtils:
@patch("windows_use.agent.tree.utils.random.randint")
def test_random_point_within_bounding_box(self, mock_randint):
@@ -14,16 +15,16 @@ class TestTreeUtils:
mock_box.left = 0
mock_box.top = 0
mock_node.BoundingRectangle = mock_box
-
+
mock_randint.side_effect = [50, 60]
-
+
x, y = random_point_within_bounding_box(mock_node, scale_factor=1.0)
-
+
assert x == 50
assert y == 60
# For 1.0 scale, range is (0, 100)
mock_randint.assert_any_call(0, 100)
-
+
@patch("windows_use.agent.tree.utils.random.randint")
def test_random_point_within_bounding_box_scaled(self, mock_randint):
mock_node = MagicMock()
@@ -33,11 +34,11 @@ class TestTreeUtils:
mock_box.left = 0
mock_box.top = 0
mock_node.BoundingRectangle = mock_box
-
+
# scale_factor = 0.5 -> scaled_width = 50, scaled_height = 50
# scaled_left = 0 + (100 - 50) // 2 = 25
# scaled_top = 0 + (100 - 50) // 2 = 25
# range = (25, 25+50=75)
-
+
random_point_within_bounding_box(mock_node, scale_factor=0.5)
mock_randint.assert_any_call(25, 75)
diff --git a/tests/unit/tree/test_tree_views.py b/tests/unit/tree/test_tree_views.py
index a3cdf24..2a3ac70 100644
--- a/tests/unit/tree/test_tree_views.py
+++ b/tests/unit/tree/test_tree_views.py
@@ -1,11 +1,16 @@
# tests/unit/tree/test_tree_views.py
import pytest
+
from windows_use.agent.tree.views import (
- TreeElementNode, TextElementNode, ScrollElementNode,
- Center, BoundingBox, TreeState
+ BoundingBox,
+ Center,
+ ScrollElementNode,
+ TreeElementNode,
+ TreeState,
)
+
@pytest.fixture
def sample_center():
return Center(x=100, y=200)
diff --git a/uv.lock b/uv.lock
index 551da79..49098d4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4315,7 +4315,7 @@ wheels = [
[[package]]
name = "windows-use"
-version = "0.7.66"
+version = "0.7.7"
source = { editable = "." }
dependencies = [
{ name = "anthropic" },
diff --git a/windows_use/__init__.py b/windows_use/__init__.py
index 2d5b84d..afbb552 100644
--- a/windows_use/__init__.py
+++ b/windows_use/__init__.py
@@ -1,11 +1,11 @@
from windows_use.agent import (
Agent,
- Browser,
AgentEvent,
- EventType,
- Event,
BaseEventSubscriber,
+ Browser,
ConsoleEventSubscriber,
+ Event,
+ EventType,
FileEventSubscriber,
)
diff --git a/windows_use/agent/__init__.py b/windows_use/agent/__init__.py
index 1de0a8d..5e5f046 100644
--- a/windows_use/agent/__init__.py
+++ b/windows_use/agent/__init__.py
@@ -1,13 +1,13 @@
from windows_use.agent.desktop.views import Browser
-from windows_use.agent.service import Agent
from windows_use.agent.events import (
AgentEvent,
- EventType,
- Event,
BaseEventSubscriber,
ConsoleEventSubscriber,
+ Event,
+ EventType,
FileEventSubscriber,
)
+from windows_use.agent.service import Agent
__all__ = [
"Agent",
diff --git a/windows_use/agent/base.py b/windows_use/agent/base.py
index 767c2eb..24b7f89 100644
--- a/windows_use/agent/base.py
+++ b/windows_use/agent/base.py
@@ -1,6 +1,7 @@
-from windows_use.agent.views import AgentResult
from abc import ABC, abstractmethod
-from typing import Optional
+
+from windows_use.agent.views import AgentResult
+
class BaseAgent(ABC):
"""
diff --git a/windows_use/agent/context/service.py b/windows_use/agent/context/service.py
index ce55e3b..7febc5e 100644
--- a/windows_use/agent/context/service.py
+++ b/windows_use/agent/context/service.py
@@ -1,15 +1,22 @@
-from windows_use.messages import SystemMessage, HumanMessage, ImageMessage, AIMessage, ToolMessage, BaseMessage
-from windows_use.providers import BaseChatLLM,TokenUsage
-from windows_use.agent.desktop.views import Browser
-from windows_use.agent.desktop.service import Desktop
from concurrent.futures import ThreadPoolExecutor
-from importlib.resources import files
from datetime import datetime
from getpass import getuser
+from importlib.resources import files
from pathlib import Path
from typing import Literal
import windows_use.uia as uia
+from windows_use.agent.desktop.service import Desktop
+from windows_use.agent.desktop.views import Browser
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from windows_use.providers import BaseChatLLM, TokenUsage
_template_cache: dict[str, str] = {}
@@ -29,7 +36,7 @@ class Context:
def __init__(self,llm: BaseChatLLM):
self.token_usage:TokenUsage=TokenUsage()
self.llm = llm
-
+
def _build_system_prompt(self,
mode: Literal["flash", "normal"],
desktop: Desktop,
@@ -88,7 +95,12 @@ class Context:
params=message.params
if 'thought' in params:
lines.append(f'THOUGHT: {params["thought"]}')
- lines.append(f'TOOL CALL {id}: {name}({', '.join([f'{k}={v[:2000]+'...[TRUNCATED]' if len(v)>2000 else v}' for k,v in params.items() if k not in _NON_TOOL_PARAMS])})')
+ parts = ", ".join(
+ f"{k}={v[:2000] + '...[TRUNCATED]' if len(v) > 2000 else v}"
+ for k, v in params.items()
+ if k not in _NON_TOOL_PARAMS
+ )
+ lines.append(f"TOOL CALL {id}: {name}({parts})")
lines.append(f'TOOL RESULT {id}: {content}')
else:
pass
@@ -197,4 +209,4 @@ Continue work from where the previous session left off. FOCUS only on the remain
return HumanMessage(content=f"TASK: {task}")
def update_token_usage(self,token_usage:TokenUsage):
- self.token_usage=token_usage
\ No newline at end of file
+ self.token_usage=token_usage
diff --git a/windows_use/agent/desktop/config.py b/windows_use/agent/desktop/config.py
index 0363b5c..079aecf 100644
--- a/windows_use/agent/desktop/config.py
+++ b/windows_use/agent/desktop/config.py
@@ -1,4 +1,3 @@
-from typing import Set
# Key name aliases for shortcut keys that differ from UIA SpecialKeyNames
KEY_ALIASES: dict[str, str] = {
@@ -10,14 +9,14 @@ KEY_ALIASES: dict[str, str] = {
"option": "Alt",
}
-AVOIDED_APPS: Set[str] = set([
+AVOIDED_APPS: set[str] = set([
'AgentUI'
])
-EXCLUDED_APPS:Set[str]=set([
+EXCLUDED_APPS:set[str]=set([
'Progman',
'Shell_TrayWnd',
'Shell_SecondaryTrayWnd',
'Microsoft.UI.Content.PopupWindowSiteBridge',
'Windows.UI.Core.CoreWindow',
-])
\ No newline at end of file
+])
diff --git a/windows_use/agent/desktop/service.py b/windows_use/agent/desktop/service.py
index 69e3840..34bd857 100644
--- a/windows_use/agent/desktop/service.py
+++ b/windows_use/agent/desktop/service.py
@@ -1,30 +1,32 @@
-from windows_use.vdm.core import get_all_desktops, get_current_desktop, is_window_on_current_desktop
-from windows_use.agent.desktop.views import DesktopState, Window, Browser, Status, Size
-from windows_use.agent.tree.views import BoundingBox, TreeElementNode, TreeState
-from windows_use.agent.desktop.utils import escape_text_for_sendkeys
-from windows_use.agent.desktop.config import KEY_ALIASES
-from PIL import ImageGrab, ImageFont, ImageDraw, Image
-from windows_use.agent.tree.service import Tree
-import windows_use.uia as uia
-from contextlib import contextmanager
-from typing import Optional,Literal
-from time import sleep,perf_counter
-from markdownify import markdownify
-from fuzzywuzzy import process
-from psutil import Process
-import win32process
-import subprocess
-import win32gui
-import win32con
-import requests
-import logging
import base64
-import random
-import ctypes
import csv
-import re
-import os
+import ctypes
import io
+import logging
+import os
+import random
+import re
+import subprocess
+from contextlib import contextmanager
+from time import perf_counter, sleep
+from typing import Literal
+
+import requests
+import win32con
+import win32gui
+import win32process
+from fuzzywuzzy import process
+from markdownify import markdownify
+from PIL import Image, ImageDraw, ImageFont, ImageGrab
+from psutil import Process
+
+import windows_use.uia as uia
+from windows_use.agent.desktop.config import KEY_ALIASES
+from windows_use.agent.desktop.utils import escape_text_for_sendkeys
+from windows_use.agent.desktop.views import Browser, DesktopState, Size, Status, Window
+from windows_use.agent.tree.service import Tree
+from windows_use.agent.tree.views import BoundingBox, TreeElementNode, TreeState
+from windows_use.vdm.core import get_all_desktops, get_current_desktop, is_window_on_current_desktop
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@@ -62,7 +64,7 @@ class Desktop:
executor.submit(self.get_default_language)
executor.submit(self.get_user_account_type)
executor.submit(_warm_uia)
-
+
def get_state(self,as_bytes:bool=False)->DesktopState:
start_time = perf_counter()
@@ -83,7 +85,7 @@ class Desktop:
logger.debug(f"Active window: {active_window or 'No Active Window Found'}")
logger.debug(f"Windows: {windows}")
-
+
#Preparing handles for Tree
other_windows_handles=list(controls_handles-windows_handles)
@@ -103,7 +105,7 @@ class Desktop:
screenshot=self.get_screenshot(as_bytes=as_bytes)
else:
screenshot=None
-
+
self.desktop_state=DesktopState(
active_window=active_window,
windows=windows,
@@ -116,7 +118,7 @@ class Desktop:
end_time = perf_counter()
logger.debug(f"[Desktop] Desktop State capture took {end_time - start_time:.2f} seconds")
return self.desktop_state
-
+
def get_window_status(self,control:uia.Control)->Status:
if uia.IsIconic(control.NativeWindowHandle):
return Status.MINIMIZED
@@ -126,17 +128,17 @@ class Desktop:
return Status.NORMAL
else:
return Status.HIDDEN
-
+
def get_cursor_location(self)->tuple[int,int]:
return uia.GetCursorPos()
-
+
def get_element_under_cursor(self)->uia.Control:
return uia.ControlFromCursor()
-
+
def get_apps_from_start_menu(self)->dict[str,str]:
command='Get-StartApps | ConvertTo-Csv -NoTypeInformation'
apps_info, status = self.execute_command(command)
-
+
if status != 0 or not apps_info:
logger.error(f"Failed to get apps from start menu: {apps_info}")
return {}
@@ -144,14 +146,14 @@ class Desktop:
try:
reader = csv.DictReader(io.StringIO(apps_info.strip()))
return {
- row.get('Name').lower(): row.get('AppID')
- for row in reader
+ row.get('Name').lower(): row.get('AppID')
+ for row in reader
if row.get('Name') and row.get('AppID')
}
except Exception as e:
logger.error(f"Error parsing start menu apps: {e}")
return {}
-
+
def execute_command(self, command: str,timeout:int=10) -> tuple[str, int]:
try:
utf8_command = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ' + command
@@ -169,12 +171,12 @@ class Desktop:
return ('Command execution timed out', 1)
except Exception as e:
return (f'Command execution failed: {type(e).__name__}: {e}', 1)
-
+
def is_window_browser(self,node:uia.Control):
'''Give any node of the app and it will return True if the app is a browser, False otherwise.'''
process=Process(node.ProcessId)
return Browser.has_process(process.name())
-
+
def get_default_language(self)->str:
if self._cached_default_language is not None:
return self._cached_default_language
@@ -184,7 +186,7 @@ class Desktop:
result = "".join([row.get('DisplayName') for row in reader])
self._cached_default_language = result
return result
-
+
def _find_window_by_name(self, name: str) -> tuple['Window | None', str]:
"""Find a window by fuzzy name match. Returns (window, error_msg).
If the returned window is None, error_msg describes the failure reason.
@@ -227,26 +229,26 @@ class Desktop:
width, height = size
app_control.MoveWindow(x, y, width, height)
return (f'{target_app.name} resized to {width}x{height} at {x},{y}.', 0)
-
+
def is_app_running(self,name:str)->bool:
apps, _ = self.get_windows()
apps_dict = {app.name: app for app in apps}
return process.extractOne(name,list(apps_dict.keys()),score_cutoff=60) is not None
-
- def app(self,mode:Literal['launch','switch','resize'],name:Optional[str]=None,loc:Optional[tuple[int,int]]=None,size:Optional[tuple[int,int]]=None):
+
+ def app(self,mode:Literal['launch','switch','resize'],name:str | None=None,loc:tuple[int, int] | None=None,size:tuple[int, int] | None=None):
match mode:
case 'launch':
response,status,pid=self.launch_app(name)
if status!=0:
return response
-
+
# Smart wait using UIA Exists (avoids manual Python loops)
launched = False
try:
if pid > 0:
if uia.WindowControl(ProcessId=pid).Exists(maxSearchSeconds=10):
launched = True
-
+
if not launched:
# Fallback: Regex search for the window title
safe_name = re.escape(name)
@@ -254,7 +256,7 @@ class Desktop:
launched = True
except Exception as e:
logger.warning(f"Error verifying app launch (likely transient COM error): {e}")
- # Assume launched if we got this far without launch_app failing,
+ # Assume launched if we got this far without launch_app failing,
# as the subprocess call succeeded.
launched = True
@@ -273,7 +275,7 @@ class Desktop:
return response
else:
return response
-
+
def launch_app(self,name:str)->tuple[str,int,int]:
apps_map=self.get_apps_from_start_menu()
matched_app=process.extractOne(name,apps_map.keys(),score_cutoff=70)
@@ -283,7 +285,7 @@ class Desktop:
appid=apps_map.get(app_name)
if appid is None:
return (name,f'{name.title()} not found in start menu.',1,0)
-
+
pid = 0
if os.path.exists(appid) or "\\" in appid:
# It's a file path, we can try to get the PID using PassThru
@@ -295,9 +297,9 @@ class Desktop:
# It's an AUMID (Store App)
command = f'Start-Process "shell:AppsFolder\\{appid}"'
response, status = self.execute_command(command)
-
+
return response, status, pid
-
+
def switch_app(self, name: str):
app, error = self._find_window_by_name(name)
if app is None:
@@ -311,7 +313,7 @@ class Desktop:
else:
content = f'Switched to {app.name.title()} window.'
return content, 0
-
+
def bring_window_to_top(self, target_handle: int):
if not win32gui.IsWindow(target_handle):
raise ValueError("Invalid window handle")
@@ -352,7 +354,7 @@ class Desktop:
except Exception as e:
logger.exception(f"Failed to bring window to top: {e}")
-
+
def get_element_handle_from_label(self,label:int)->uia.Control:
tree_state=self.desktop_state.tree_state
selector=tree_state.build_selector_map()
@@ -365,12 +367,12 @@ class Desktop:
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)
bounding_rectangle=element_handle.BoundingRectangle
return bounding_rectangle.xcenter(),bounding_rectangle.ycenter()
-
+
def click(self,loc:tuple[int,int],button:str='left',clicks:int=2):
x,y=loc
if clicks == 0:
@@ -428,7 +430,7 @@ class Desktop:
case _:
return 'Invalid type. Use "horizontal" or "vertical".'
return None
-
+
def drag(self,loc:tuple[int,int]):
x,y=loc
cx, cy = uia.GetCursorPos()
@@ -460,25 +462,25 @@ class Desktop:
uia.Click(x, y, waitTime=0.2)
sleep(0.5)
uia.ReleaseKey(uia.Keys.VK_CONTROL, waitTime=0.05)
-
+
def multi_edit(self,elements:list[tuple[int,int,str]|tuple[int,str]]):
for element in elements:
x,y,text=element
self.type((x,y),text=text,clear='true')
-
+
def scrape(self,url:str)->str:
response=requests.get(url,timeout=10)
html=response.text
content=markdownify(html=html)
return content
-
+
def is_window_visible(self,window:uia.Control)->bool:
is_minimized=self.get_window_status(window)!=Status.MINIMIZED
size=window.BoundingRectangle
area=size.width()*size.height()
is_overlay=self.is_overlay_window(window)
return not is_overlay and is_minimized and area>10
-
+
def is_overlay_window(self,element:uia.Control) -> bool:
no_children = element.GetFirstChildControl() is None
is_name = "Overlay" in element.Name.strip()
@@ -541,13 +543,13 @@ class Desktop:
def get_window_from_element_handle(self, element_handle: int) -> uia.Control:
current = uia.ControlFromHandle(element_handle)
root_handle = uia.GetRootControl().NativeWindowHandle
-
+
while True:
parent = current.GetParentControl()
if parent is None or parent.NativeWindowHandle == root_handle:
return current
current = parent
-
+
def get_windows(self,controls_handles:set[int]|None=None) -> tuple[list[Window],set[int]]:
try:
windows = []
@@ -558,7 +560,7 @@ class Desktop:
child = uia.ControlFromHandle(hwnd)
except Exception:
continue
-
+
# Filter out Overlays (e.g. NVIDIA, Steam)
if self.is_overlay_window(child):
continue
@@ -567,10 +569,10 @@ class Desktop:
window_pattern=child.GetPattern(uia.PatternId.WindowPattern)
if (window_pattern is None):
continue
-
+
if window_pattern.CanMinimize and window_pattern.CanMaximize:
status = self.get_window_status(child)
-
+
bounding_rect=child.BoundingRectangle
if bounding_rect.isempty() and status!=Status.MINIMIZED:
continue
@@ -596,7 +598,7 @@ class Desktop:
logger.error(f"Error in get_windows: {ex}")
windows = []
return windows,window_handles
-
+
def get_windows_version(self)->str:
if self._cached_windows_version is not None:
return self._cached_windows_version
@@ -604,7 +606,7 @@ class Desktop:
result = response.strip() if status == 0 else "Windows"
self._cached_windows_version = result
return result
-
+
def get_user_account_type(self)->str:
if self._cached_user_account_type is not None:
return self._cached_user_account_type
@@ -612,12 +614,12 @@ class Desktop:
result = "Local Account" if response.strip()=='Local' else "Microsoft Account" if status==0 else "Local Account"
self._cached_user_account_type = result
return result
-
+
def get_dpi_scaling(self):
user32 = ctypes.windll.user32
dpi = user32.GetDpiForSystem()
return dpi / 96.0
-
+
def get_screen_size(self)->Size:
width, height = uia.GetVirtualScreenSize()
return Size(width=width,height=height)
@@ -625,8 +627,8 @@ class Desktop:
def get_screenshot(self,as_bytes:bool=False)->bytes|Image.Image:
try:
screenshot = ImageGrab.grab(all_screens=True)
- except Exception as e:
- logger.warning(f"Failed to capture virtual screen, using primary screen")
+ except Exception:
+ logger.warning("Failed to capture virtual screen, using primary screen")
screenshot = ImageGrab.grab()
if as_bytes:
buffered = io.BytesIO()
@@ -648,11 +650,11 @@ class Desktop:
font_size = 12
try:
font = ImageFont.truetype('arial.ttf', font_size)
- except IOError:
+ except OSError:
font = ImageFont.load_default()
def get_random_color():
- return "#{:06x}".format(random.randint(0, 0xFFFFFF))
+ return f"#{random.randint(0, 0xFFFFFF):06x}"
left_offset, top_offset, _, _ = uia.GetVirtualScreenRect()
@@ -688,14 +690,14 @@ class Desktop:
for label,node in enumerate(nodes):
draw_annotation(label, node)
-
+
if as_bytes:
buffered = io.BytesIO()
padded_screenshot.save(buffered, format="PNG")
padded_screenshot = buffered.getvalue()
buffered.close()
return padded_screenshot
-
+
@contextmanager
def auto_minimize(self):
try:
diff --git a/windows_use/agent/desktop/views.py b/windows_use/agent/desktop/views.py
index da1615d..a3afc35 100644
--- a/windows_use/agent/desktop/views.py
+++ b/windows_use/agent/desktop/views.py
@@ -1,10 +1,12 @@
-from windows_use.agent.tree.views import TreeState, BoundingBox
from dataclasses import dataclass
-from tabulate import tabulate
-from typing import Optional
-from PIL.Image import Image
from enum import Enum
+from PIL.Image import Image
+from tabulate import tabulate
+
+from windows_use.agent.tree.views import BoundingBox, TreeState
+
+
class Browser(Enum):
CHROME='chrome'
EDGE='msedge'
@@ -32,7 +34,7 @@ class Window:
bounding_box:BoundingBox
handle: int
process_id:int
-
+
def to_row(self):
return [self.name, self.depth, self.status.value, self.bounding_box.width, self.bounding_box.height, self.handle]
@@ -49,9 +51,9 @@ class DesktopState:
active_desktop:dict
all_desktops:list[dict]
windows:list[Window]
- active_window:Optional[Window]
- screenshot:Optional[Image]=None
- tree_state:Optional[TreeState]=None
+ active_window:Window | None
+ screenshot:Image | None=None
+ tree_state:TreeState | None=None
def active_desktop_to_string(self):
desktop_name=self.active_desktop.get('name')
diff --git a/windows_use/agent/events/__init__.py b/windows_use/agent/events/__init__.py
index 2fbb352..5f977e1 100644
--- a/windows_use/agent/events/__init__.py
+++ b/windows_use/agent/events/__init__.py
@@ -1,10 +1,10 @@
-from windows_use.agent.events.views import AgentEvent, EventType
+from windows_use.agent.events.service import Event
from windows_use.agent.events.subscriber import (
BaseEventSubscriber,
ConsoleEventSubscriber,
FileEventSubscriber,
)
-from windows_use.agent.events.service import Event
+from windows_use.agent.events.views import AgentEvent, EventType
__all__ = [
"AgentEvent",
diff --git a/windows_use/agent/events/service.py b/windows_use/agent/events/service.py
index 869474a..9e11c12 100644
--- a/windows_use/agent/events/service.py
+++ b/windows_use/agent/events/service.py
@@ -2,12 +2,12 @@
from __future__ import annotations
-from typing import Callable, Union
+from collections.abc import Callable
-from windows_use.agent.events.views import AgentEvent, EventType
from windows_use.agent.events.subscriber import BaseEventSubscriber
+from windows_use.agent.events.views import AgentEvent
-EventSubscriber = Union[BaseEventSubscriber, Callable[[AgentEvent], None]]
+EventSubscriber = BaseEventSubscriber | Callable[[AgentEvent], None]
class Event:
diff --git a/windows_use/agent/loop.py b/windows_use/agent/loop.py
index 3d62e2b..2a7de09 100644
--- a/windows_use/agent/loop.py
+++ b/windows_use/agent/loop.py
@@ -3,6 +3,7 @@ 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'}
diff --git a/windows_use/agent/registry/service.py b/windows_use/agent/registry/service.py
index 4212a2c..9221fe7 100644
--- a/windows_use/agent/registry/service.py
+++ b/windows_use/agent/registry/service.py
@@ -1,7 +1,8 @@
-from windows_use.agent.registry.views import ToolResult
from windows_use.agent.desktop.service import Desktop
+from windows_use.agent.registry.views import ToolResult
from windows_use.agent.tools import Tool
+
class Registry:
def __init__(self,tools:list[Tool]=[]):
self.tools=tools
@@ -9,7 +10,7 @@ class Registry:
def registry(self)->dict[str,Tool]:
return {tool.name: tool for tool in self.tools}
-
+
def get_tools(self,exclude_tools:list[str]=[])->list[Tool]:
if not exclude_tools:
return self.tools
@@ -17,11 +18,11 @@ class Registry:
def get_tool(self,tool_name:str)->Tool|None:
return self.tools_registry.get(tool_name,None)
-
+
def get_tools_schema(self) -> list[dict]:
tools = [tool.json_schema for tool in self.tools]
return tools
-
+
def execute(self, tool_name: str, tool_params: dict, desktop: Desktop|None=None) -> ToolResult:
tool = self.get_tool(tool_name)
if not tool:
diff --git a/windows_use/agent/registry/views.py b/windows_use/agent/registry/views.py
index 97488f1..a4a1072 100644
--- a/windows_use/agent/registry/views.py
+++ b/windows_use/agent/registry/views.py
@@ -1,6 +1,7 @@
from pydantic import BaseModel
+
class ToolResult(BaseModel):
is_success: bool
content: str | None = None
- error: str | None = None
\ No newline at end of file
+ error: str | None = None
diff --git a/windows_use/agent/service.py b/windows_use/agent/service.py
index 3e8d58e..cd8152d 100644
--- a/windows_use/agent/service.py
+++ b/windows_use/agent/service.py
@@ -1,23 +1,32 @@
-from windows_use.messages import SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
-from windows_use.agent.events import AgentEvent, Event, EventType, ConsoleEventSubscriber, FileEventSubscriber
+import logging
+import time
+from collections.abc import Callable
+from contextlib import nullcontext
+from itertools import chain
+from typing import TYPE_CHECKING, Literal
+
+from rich.console import Console
+
+from windows_use.agent.base import BaseAgent
+from windows_use.agent.context import Context
+from windows_use.agent.desktop.service import Desktop
+from windows_use.agent.desktop.views import Browser
+from windows_use.agent.events import (
+ AgentEvent,
+ ConsoleEventSubscriber,
+ Event,
+ EventType,
+ FileEventSubscriber,
+)
+from windows_use.agent.loop import LoopGuard
+from windows_use.agent.registry.service import Registry
from windows_use.agent.tools import BUILTIN_TOOLS, EXPERIMENTAL_TOOLS
from windows_use.agent.views import AgentResult, AgentState
+from windows_use.agent.watchdog.service import WatchDog
+from windows_use.messages import AIMessage, HumanMessage, ImageMessage, SystemMessage, ToolMessage
+from windows_use.providers.events import LLMEventType
from windows_use.telemetry.service import ProductTelemetry
from windows_use.telemetry.views import AgentTelemetryEvent
-from windows_use.agent.registry.service import Registry
-from windows_use.agent.watchdog.service import WatchDog
-from windows_use.agent.desktop.service import Desktop
-from windows_use.agent.desktop.views import Browser
-from windows_use.agent.loop import LoopGuard
-from windows_use.providers.events import LLMEventType, LLMStreamEventType
-from typing import Callable, Literal, TYPE_CHECKING
-from windows_use.agent.context import Context
-from windows_use.agent.base import BaseAgent
-from contextlib import nullcontext
-from rich.console import Console
-from itertools import chain
-import logging
-import time
if TYPE_CHECKING:
from windows_use.providers.base import BaseChatLLM
@@ -134,7 +143,7 @@ class Agent(BaseAgent):
instructions=self.instructions,
)
return self._cached_system_message
-
+
@property
def task_message(self) -> HumanMessage:
return self.context.task(task=self.state.task)
diff --git a/windows_use/agent/tools/__init__.py b/windows_use/agent/tools/__init__.py
index e790076..c3bcba9 100644
--- a/windows_use/agent/tools/__init__.py
+++ b/windows_use/agent/tools/__init__.py
@@ -1,27 +1,41 @@
-from windows_use.agent.tools.service import (click_tool, type_tool, app_tool, shell_tool, done_tool,
-shortcut_tool, scroll_tool, move_tool, wait_tool,
-scrape_tool, desktop_tool, memory_tool, file_tool, multi_select_tool, multi_edit_tool)
+from windows_use.agent.tools.service import (
+ app_tool,
+ click_tool,
+ desktop_tool,
+ done_tool,
+ file_tool,
+ memory_tool,
+ move_tool,
+ multi_edit_tool,
+ multi_select_tool,
+ scrape_tool,
+ scroll_tool,
+ shell_tool,
+ shortcut_tool,
+ type_tool,
+ wait_tool,
+)
from windows_use.tools import Tool
BUILTIN_TOOLS = [
- click_tool,
- type_tool,
- app_tool,
- shell_tool,
+ click_tool,
+ type_tool,
+ app_tool,
+ shell_tool,
done_tool,
- shortcut_tool,
- scroll_tool,
- move_tool,
+ shortcut_tool,
+ scroll_tool,
+ move_tool,
wait_tool,
scrape_tool,
desktop_tool
]
EXPERIMENTAL_TOOLS = [
- multi_select_tool,
+ multi_select_tool,
multi_edit_tool,
file_tool,
- memory_tool,
+ memory_tool,
]
__all__ = [
diff --git a/windows_use/agent/tools/service.py b/windows_use/agent/tools/service.py
index 67e64ca..c386624 100644
--- a/windows_use/agent/tools/service.py
+++ b/windows_use/agent/tools/service.py
@@ -1,12 +1,31 @@
-from windows_use.agent.tools.views import Click, Type, Scroll, Move, Shortcut, Wait, Scrape, Done, Shell, Memory, App, MultiSelect, MultiEdit, Desktop, File
-from windows_use.vdm.core import create_desktop as vdm_create, remove_desktop as vdm_remove, rename_desktop as vdm_rename, switch_desktop as vdm_switch
-from windows_use.agent.desktop.service import Desktop as _Desktop
-from windows_use.tools import Tool
-from typing import Literal,Optional
+import shutil
from datetime import datetime
from pathlib import Path
-from time import sleep
-import shutil
+from typing import Literal
+
+from windows_use.agent.desktop.service import Desktop as _Desktop
+from windows_use.agent.tools.views import (
+ App,
+ Click,
+ Desktop,
+ Done,
+ File,
+ Memory,
+ Move,
+ MultiEdit,
+ MultiSelect,
+ Scrape,
+ Scroll,
+ Shell,
+ Shortcut,
+ Type,
+ Wait,
+)
+from windows_use.tools import Tool
+from windows_use.vdm.core import create_desktop as vdm_create
+from windows_use.vdm.core import remove_desktop as vdm_remove
+from windows_use.vdm.core import rename_desktop as vdm_rename
+from windows_use.vdm.core import switch_desktop as vdm_switch
MAX_FILE_READ_SIZE = 1 * 1024 * 1024 # 1 MB
@@ -46,7 +65,7 @@ async def done_tool(answer:str,**kwargs):
return answer
@Tool('app_tool',model=App)
-async def app_tool(mode:Literal['launch','resize','switch']='launch',name:Optional[str]=None,loc:Optional[list[int]]=None,size:Optional[list[int]]=None,**kwargs)->str:
+async def app_tool(mode:Literal['launch','resize','switch']='launch',name:str | None=None,loc:list[int] | None=None,size:list[int] | None=None,**kwargs)->str:
'''
Manages application windows: launch new apps, switch between open windows, or resize/reposition the active window.
@@ -60,10 +79,10 @@ async def app_tool(mode:Literal['launch','resize','switch']='launch',name:Option
@Tool('memory_tool', model=Memory)
-async def memory_tool(mode: Literal['view', 'read', 'write', 'delete', 'update'], path: Optional[str] = None,
- content: Optional[str] = None, operation: Optional[Literal['replace', 'insert']] = 'replace',
- old_str: Optional[str] = None, new_str: Optional[str] = None, line_number: Optional[int] = None,
- read_range: Optional[list[int]] = None, **kwargs) -> str:
+async def memory_tool(mode: Literal['view', 'read', 'write', 'delete', 'update'], path: str | None = None,
+ content: str | None = None, operation: Literal['replace', 'insert'] | None = 'replace',
+ old_str: str | None = None, new_str: str | None = None, line_number: int | None = None,
+ read_range: list[int] | None = None, **kwargs) -> str:
'''
Persistent file-based storage for saving and retrieving information across steps. Files are stored as markdown in the .windows-use/memories directory (user home).
@@ -187,8 +206,8 @@ def _resolve_file_path(path: str) -> Path:
async def file_tool(
mode: Literal["read", "write", "list", "delete", "move", "copy", "exists"],
path: str,
- destination: Optional[str] = None,
- content: Optional[str] = None,
+ destination: str | None = None,
+ content: str | None = None,
encoding: str = "utf-8",
**kwargs,
) -> str:
@@ -288,7 +307,7 @@ async def file_tool(
if not destination:
return "Error: destination is required for copy action."
if resolved.is_dir():
- return f"Error: copy does not support directories. Use move for directories."
+ return "Error: copy does not support directories. Use move for directories."
try:
dest = _resolve_file_path(destination)
shutil.copy2(str(resolved), str(dest))
@@ -301,7 +320,7 @@ async def file_tool(
case "exists":
return f"Path exists: {resolved.exists()}"
- return f"Error: Unknown action '{action}'."
+ return f"Error: Unknown action '{mode}'."
@Tool('shell_tool',model=Shell)
@@ -316,7 +335,7 @@ async def shell_tool(command: str,timeout:int=10,**kwargs) -> str:
return f'Response: {response}\nStatus Code: {status}'
@Tool('click_tool',model=Click)
-async def click_tool(loc:Optional[list[int]]=None,button:Literal['left','right','middle']='left',clicks:int=1,**kwargs)->str:
+async def click_tool(loc:list[int] | None=None,button:Literal['left','right','middle']='left',clicks:int=1,**kwargs)->str:
'''
Clicks at the specified pixel coordinates on screen.
@@ -334,7 +353,7 @@ async def click_tool(loc:Optional[list[int]]=None,button:Literal['left','right',
return f'{num_clicks.get(clicks)} {button} clicked at ({x},{y}).'
@Tool('type_tool',model=Type)
-async def type_tool(loc:Optional[list[int]]=None,text:str='',clear:Literal['true','false']='false',caret_position:Literal['start','idle','end']='idle',press_enter:Literal['true','false']='false',**kwargs):
+async def type_tool(loc:list[int] | None=None,text:str='',clear:Literal['true','false']='false',caret_position:Literal['start','idle','end']='idle',press_enter:Literal['true','false']='false',**kwargs):
'''
Clicks an input field and types text into it. Do NOT pre-click with click_tool — this tool handles focusing automatically.
@@ -350,7 +369,7 @@ async def type_tool(loc:Optional[list[int]]=None,text:str='',clear:Literal['true
return f'Typed {text} at ({x},{y}).'
@Tool('scroll_tool',model=Scroll)
-async def scroll_tool(loc:Optional[list[int]]=None,type:Literal['horizontal','vertical']='vertical',direction:Literal['up','down','left','right']='down',wheel_times:int=1,**kwargs)->str:
+async def scroll_tool(loc:list[int] | None=None,type:Literal['horizontal','vertical']='vertical',direction:Literal['up','down','left','right']='down',wheel_times:int=1,**kwargs)->str:
'''
Scrolls content at the specified location or at the current cursor position.
@@ -450,7 +469,7 @@ async def scrape_tool(url:str,**kwargs)->str:
return f'URL:{url}\nContent:\n{header_status}\n{content}\n{footer_status}'
@Tool('desktop_tool', model=Desktop)
-async def desktop_tool(action: Literal['create', 'remove', 'rename', 'switch'], desktop_name: Optional[str] = None, new_name: Optional[str] = None, **kwargs) -> str:
+async def desktop_tool(action: Literal['create', 'remove', 'rename', 'switch'], desktop_name: str | None = None, new_name: str | None = None, **kwargs) -> str:
'''
Manages Windows virtual desktops for workspace organization.
@@ -459,7 +478,7 @@ async def desktop_tool(action: Literal['create', 'remove', 'rename', 'switch'],
- rename: Renames desktop_name to new_name.
- switch: Activates the desktop specified by desktop_name. Verify success in the next Desktop State.
'''
- try:
+ try:
match action:
case 'create':
# create_desktop(name) returns the name
diff --git a/windows_use/agent/tools/views.py b/windows_use/agent/tools/views.py
index ac3803b..6d5b284 100644
--- a/windows_use/agent/tools/views.py
+++ b/windows_use/agent/tools/views.py
@@ -1,5 +1,7 @@
-from pydantic import BaseModel, Field, ConfigDict
-from typing import Literal, Optional
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+
class SharedBaseModel(BaseModel):
@@ -16,17 +18,17 @@ class App(SharedBaseModel):
description="Operation mode: 'launch' opens the application from Start Menu, 'resize' adjusts the active window's size and position, 'switch' brings a specific open window into the foreground",
examples=['launch']
)
- name: Optional[str] = Field(
+ name: str | None = Field(
description="Application name as it appears in Start Menu (for launch) or the window title as shown in the taskbar (for switch/resize). Example: 'Notepad' to launch, 'Untitled - Notepad' to switch.",
examples=['Notepad', 'Google Chrome', 'Untitled - Notepad'],
default=None
)
- loc: Optional[list[int]] = Field(
+ loc: list[int] | None = Field(
description="Target [x, y] pixel coordinates for the window's top-left corner. Required for resize mode only.",
examples=[[0, 0]],
default=None
)
- size: Optional[list[int]] = Field(
+ size: list[int] | None = Field(
description="Target [width, height] in pixels for the window dimensions. Required for resize mode only.",
examples=[[1920, 1080]],
default=None
@@ -43,31 +45,31 @@ class Memory(SharedBaseModel):
mode: Literal['view', 'read', 'write', 'delete', 'update'] = Field(
description="Operation mode: 'view' lists all stored files, 'read' retrieves file content, 'write' creates a new file, 'update' modifies an existing file, 'delete' removes a file"
)
- path: Optional[str] = Field(
+ path: str | None = Field(
None,
description="Relative file path from the .windows-use/memories directory (e.g., 'notes.md', 'project/data.md'). Required for read, write, update, and delete."
)
- content: Optional[str] = Field(
+ content: str | None = Field(
None,
description="Text content to write into the file. Required for 'write' mode and 'insert' operation in 'update' mode."
)
- operation: Optional[Literal['replace', 'insert']] = Field(
+ operation: Literal['replace', 'insert'] | None = Field(
'replace',
description="Update strategy: 'replace' finds old_str and substitutes it with new_str, 'insert' adds content at a specific line number. Only used in 'update' mode."
)
- old_str: Optional[str] = Field(
+ old_str: str | None = Field(
None,
description="Exact string to find in the file. Required when operation='replace'."
)
- new_str: Optional[str] = Field(
+ new_str: str | None = Field(
None,
description="Replacement string. Required when operation='replace'."
)
- line_number: Optional[int] = Field(
+ line_number: int | None = Field(
None,
description="0-indexed line number where content will be inserted. Required when operation='insert'."
)
- read_range: Optional[list[int]] = Field(
+ read_range: list[int] | None = Field(
None,
description="Optional [start, end] line range for partial reads (0-indexed, end exclusive). Example: [0, 10] reads lines 0 through 9."
)
@@ -100,7 +102,7 @@ class Shell(SharedBaseModel):
'echo "Hello World"'
]
)
- timeout: Optional[int] = Field(
+ timeout: int | None = Field(
description="Maximum seconds to wait for command completion. Increase for long-running operations.",
default=10,
examples=[10, 30, 60]
@@ -153,7 +155,7 @@ class MultiEdit(SharedBaseModel):
)
class Scroll(SharedBaseModel):
- loc: Optional[list[int]] = Field(
+ loc: list[int] | None = Field(
description="[x, y] pixel coordinates where scrolling occurs. If omitted, scrolls at the current cursor position.",
default=None,
examples=[[640, 360], [800, 400]]
@@ -218,17 +220,17 @@ class File(SharedBaseModel):
description="Absolute path or path relative to user home directory. Examples: 'C:\\Users\\me\\file.txt', 'Desktop\\notes.txt', 'Documents\\config.json'",
examples=["C:\\Users\\me\\file.txt", "Desktop\\notes.txt", "Documents\\data.json"],
)
- destination: Optional[str] = Field(
+ destination: str | None = Field(
None,
description="Target path for move or copy actions. Required when action is 'move' or 'copy'.",
examples=["C:\\Users\\me\\backup\\file.txt", "Desktop\\copy.txt"],
)
- content: Optional[str] = Field(
+ content: str | None = Field(
None,
description="Text content to write. Required when action is 'write'.",
examples=["Hello world", "{\"key\": \"value\"}"],
)
- encoding: Optional[str] = Field(
+ encoding: str | None = Field(
"utf-8",
description="Character encoding for read and write. Defaults to utf-8.",
examples=["utf-8", "utf-16", "latin-1"],
@@ -241,12 +243,12 @@ class Desktop(SharedBaseModel):
description="Virtual desktop action: 'create' adds a new desktop, 'remove' deletes a desktop by name, 'rename' changes a desktop's name, 'switch' activates a desktop by name",
examples=['create', 'switch', 'rename', 'remove']
)
- desktop_name: Optional[str] = Field(
+ desktop_name: str | None = Field(
description="Name of the target desktop. Required for remove, rename, and switch. Optional for create (auto-named if omitted).",
default=None,
examples=["Desktop 1", "Work", "Research"]
)
- new_name: Optional[str] = Field(
+ new_name: str | None = Field(
description="New name for the desktop. Required for rename only.",
default=None,
examples=["My Workspace", "Project Alpha"]
diff --git a/windows_use/agent/tree/cache_utils.py b/windows_use/agent/tree/cache_utils.py
index 1399334..ce7b790 100644
--- a/windows_use/agent/tree/cache_utils.py
+++ b/windows_use/agent/tree/cache_utils.py
@@ -5,34 +5,34 @@ This module provides utilities for implementing UI Automation caching
to reduce cross-process COM calls during tree traversal.
"""
-from windows_use.uia import CacheRequest, PropertyId, PatternId, TreeScope, Control
-from typing import Optional, Any
import logging
+from windows_use.uia import CacheRequest, Control, PatternId, PropertyId, TreeScope
+
logger = logging.getLogger(__name__)
class CacheRequestFactory:
"""Factory for creating optimized cache requests for different scenarios."""
-
+
@staticmethod
def create_tree_traversal_cache() -> CacheRequest:
"""
Creates a cache request optimized for tree traversal.
Caches all commonly accessed properties and patterns.
-
+
This cache request is designed to minimize COM calls during
the tree_traversal() operation in tree/service.py.
-
+
Returns:
CacheRequest configured for tree traversal
"""
cache_request = CacheRequest()
-
+
# Set scope to cache element and its children
# This allows us to get children with pre-cached properties
cache_request.TreeScope = TreeScope.TreeScope_Element | TreeScope.TreeScope_Children
-
+
# Basic identification properties
cache_request.AddProperty(PropertyId.NameProperty)
cache_request.AddProperty(PropertyId.AutomationIdProperty)
@@ -40,7 +40,7 @@ class CacheRequestFactory:
cache_request.AddProperty(PropertyId.AcceleratorKeyProperty)
cache_request.AddProperty(PropertyId.ClassNameProperty)
cache_request.AddProperty(PropertyId.ControlTypeProperty)
-
+
# State properties for visibility and interaction checks
cache_request.AddProperty(PropertyId.IsEnabledProperty)
cache_request.AddProperty(PropertyId.IsOffscreenProperty)
@@ -48,16 +48,16 @@ class CacheRequestFactory:
cache_request.AddProperty(PropertyId.HasKeyboardFocusProperty)
cache_request.AddProperty(PropertyId.IsKeyboardFocusableProperty)
cache_request.AddProperty(PropertyId.IsPasswordProperty)
-
+
# Layout properties
cache_request.AddProperty(PropertyId.BoundingRectangleProperty)
cache_request.AddProperty(PropertyId.HelpTextProperty)
-
+
# Patterns
cache_request.AddPattern(PatternId.LegacyIAccessiblePattern)
cache_request.AddPattern(PatternId.ScrollPattern)
cache_request.AddPattern(PatternId.WindowPattern)
-
+
# LegacyIAccessible properties
cache_request.AddProperty(PropertyId.LegacyIAccessibleRoleProperty)
cache_request.AddProperty(PropertyId.LegacyIAccessibleValueProperty)
@@ -92,27 +92,27 @@ class CacheRequestFactory:
cache_request.AddProperty(PropertyId.RangeValueValueProperty)
cache_request.AddProperty(PropertyId.RangeValueMinimumProperty)
cache_request.AddProperty(PropertyId.RangeValueMaximumProperty)
-
+
return cache_request
class CachedControlHelper:
"""Helper class for working with cached controls."""
-
+
@staticmethod
- def build_cached_control(node: Control, cache_request: Optional[CacheRequest] = None) -> Control:
+ def build_cached_control(node: Control, cache_request: CacheRequest | None = None) -> Control:
"""
Build a cached version of a control.
-
+
Args:
node: The control to cache
cache_request: Optional custom cache request. If None, uses tree traversal cache.
-
+
Returns:
A control with cached properties, or the original control if caching fails
"""
if cache_request is None:
cache_request = CacheRequestFactory.create_tree_traversal_cache()
-
+
try:
cached_node = node.BuildUpdatedCache(cache_request)
cached_node._is_cached = True
@@ -120,41 +120,41 @@ class CachedControlHelper:
except Exception as e:
logger.debug(f"Failed to build cached control: {e}")
return node
-
+
@staticmethod
- def get_cached_children(node: Control, cache_request: Optional[CacheRequest] = None) -> list[Control]:
+ def get_cached_children(node: Control, cache_request: CacheRequest | None = None) -> list[Control]:
"""
Get children with pre-cached properties.
-
+
This is the most significant optimization - it retrieves all children
with their properties already cached, eliminating the need for individual
property access calls on each child.
-
+
Args:
node: The parent control
cache_request: Optional custom cache request. If None, uses tree traversal cache.
-
+
Returns:
List of children with cached properties
"""
if cache_request is None:
cache_request = CacheRequestFactory.create_tree_traversal_cache()
-
+
# Optimization: To avoid redundant COM property fetches for the parent node,
# we only need the Children scope. If TreeScope_Element is omitted,
# UI Automation only fetches the children and their properties.
# We clone the request to avoid modifying shared cache request objects.
req_clone = cache_request.Clone()
req_clone.TreeScope = TreeScope.TreeScope_Children
-
+
try:
# Bypass `Control.CreateControlFromElement` when building the cache.
# When TreeScope_Element is omitted, BuildUpdatedCache returns a dummy element
- # which does not have valid properties (like CurrentControlType),
+ # which does not have valid properties (like CurrentControlType),
# so our python wrapper would crash. We just use the raw IUIAutomationElement.
updated_element = node.Element.BuildUpdatedCache(req_clone.check_request)
element_array = updated_element.GetCachedChildren()
-
+
children = []
if element_array:
length = element_array.Length
@@ -164,10 +164,10 @@ class CachedControlHelper:
if child_control:
child_control._is_cached = True
children.append(child_control)
-
+
logger.debug(f"Retrieved {len(children)} cached children (newly built)")
return children
-
+
except Exception as e:
logger.debug(f"Failed to get cached children, falling back to regular access: {e}")
return node.GetChildren()
diff --git a/windows_use/agent/tree/config.py b/windows_use/agent/tree/config.py
index 72822ad..e191632 100644
--- a/windows_use/agent/tree/config.py
+++ b/windows_use/agent/tree/config.py
@@ -21,25 +21,25 @@ INTERACTIVE_CONTROL_TYPE_NAMES=set([
INTERACTIVE_ROLES = {
# Buttons
- 'PushButton', 'SplitButton', 'ButtonDropDown', 'ButtonMenu',
+ 'PushButton', 'SplitButton', 'ButtonDropDown', 'ButtonMenu',
'ButtonDropDownGrid', 'OutlineButton',
-
+
# Links
'Link',
-
+
# Inputs & Selection
'Text', 'IpAddress', 'HotkeyField', 'ComboBox', 'DropList',
'CheckButton', 'RadioButton',
-
+
# Menus & Tabs
'MenuItem', 'ListItem', 'PageTab',
-
+
# Trees
'OutlineItem',
-
+
# Values
'Slider', 'SpinButton', 'Dial', 'ScrollBar', 'Grip',
-
+
# Grids
'ColumnHeader', 'RowHeader', 'Cell',
@@ -80,4 +80,4 @@ DEFAULT_ACTIONS=set([
'Collapse'
])
-THREAD_MAX_RETRIES = 3
\ No newline at end of file
+THREAD_MAX_RETRIES = 3
diff --git a/windows_use/agent/tree/service.py b/windows_use/agent/tree/service.py
index ca9ff09..c6acaa9 100644
--- a/windows_use/agent/tree/service.py
+++ b/windows_use/agent/tree/service.py
@@ -1,26 +1,61 @@
-from windows_use.uia import Control, ComboBoxControl, CheckBoxControl, EditControl, ButtonControl, SliderControl, ScrollPattern, WindowControl, Rect, ExpandCollapseState, ToggleState, PatternId, PropertyId, AccessibleRoleNames, TreeScope, ControlFromHandle, UIAException, UIADeadElementError, UIARetryableError, from_com_error
-from _ctypes import COMError
-from windows_use.agent.tree.config import INTERACTIVE_CONTROL_TYPE_NAMES, DOCUMENT_CONTROL_TYPE_NAMES, INFORMATIVE_CONTROL_TYPE_NAMES, DEFAULT_ACTIONS, INTERACTIVE_ROLES, THREAD_MAX_RETRIES
-from windows_use.agent.tree.views import TreeElementNode, ScrollElementNode, TextElementNode, Center, BoundingBox, TreeState
-from windows_use.agent.tree.cache_utils import CacheRequestFactory, CachedControlHelper
-from windows_use.agent.tree.utils import random_point_within_bounding_box
-from typing import TYPE_CHECKING,Optional,Any
-from time import sleep,perf_counter
+import ctypes
import logging
import weakref
-import ctypes
+from _ctypes import COMError
+from time import perf_counter, sleep
+from typing import TYPE_CHECKING, Any
+
+from windows_use.agent.tree.cache_utils import CachedControlHelper, CacheRequestFactory
+from windows_use.agent.tree.config import (
+ DEFAULT_ACTIONS,
+ DOCUMENT_CONTROL_TYPE_NAMES,
+ INFORMATIVE_CONTROL_TYPE_NAMES,
+ INTERACTIVE_CONTROL_TYPE_NAMES,
+ INTERACTIVE_ROLES,
+ THREAD_MAX_RETRIES,
+)
+from windows_use.agent.tree.utils import random_point_within_bounding_box
+from windows_use.agent.tree.views import (
+ BoundingBox,
+ Center,
+ ScrollElementNode,
+ TextElementNode,
+ TreeElementNode,
+ TreeState,
+)
+from windows_use.uia import (
+ AccessibleRoleNames,
+ ButtonControl,
+ CheckBoxControl,
+ ComboBoxControl,
+ Control,
+ ControlFromHandle,
+ EditControl,
+ ExpandCollapseState,
+ PatternId,
+ PropertyId,
+ Rect,
+ ScrollPattern,
+ SliderControl,
+ ToggleState,
+ TreeScope,
+ UIADeadElementError,
+ UIAException,
+ WindowControl,
+ from_com_error,
+)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if TYPE_CHECKING:
from windows_use.agent.desktop.service import Desktop
-
+
class Tree:
def __init__(self,desktop:'Desktop'):
self.desktop=weakref.proxy(desktop)
self.screen_size=desktop.get_screen_size()
- self.dom:Optional[Control]=None
+ self.dom:Control | None=None
self.dom_bounding_box:BoundingBox=None
self.screen_box=BoundingBox(
top=0, left=0, bottom=self.screen_size.height, right=self.screen_size.width,
@@ -41,7 +76,7 @@ class Tree:
windows_handles=[active_window_handle]+other_windows_handles
else:
windows_handles=other_windows_handles
-
+
interactive_nodes,scrollable_nodes,dom_informative_nodes,failed_handles=self.get_window_wise_nodes(windows_handles=windows_handles,active_window_flag=active_window_flag)
root_node=TreeElementNode(
name="Desktop",
@@ -139,7 +174,7 @@ class Tree:
break
return interactive_nodes, scrollable_nodes, dom_informative_nodes, failed_handles
-
+
def iou_bounding_box(self, window_box: Rect, element_box: Rect) -> BoundingBox:
clipped = element_box.intersect(window_box).intersect(self.screen_box)
if clipped.right > clipped.left and clipped.bottom > clipped.top:
@@ -207,7 +242,7 @@ class Tree:
metadata['value']=value.strip() if value else '(empty)'
except Exception:
pass
-
+
try:
help_text = node.CachedHelpText
if help_text:
@@ -250,21 +285,21 @@ class Tree:
def tree_traversal(self, node: Control, window_bounding_box:Rect, window_name:str, is_browser:bool,
- interactive_nodes:Optional[list[TreeElementNode]]=None, scrollable_nodes:Optional[list[ScrollElementNode]]=None,
- dom_interactive_nodes:Optional[list[TreeElementNode]]=None, dom_informative_nodes:Optional[list[TextElementNode]]=None,
+ interactive_nodes:list[TreeElementNode] | None=None, scrollable_nodes:list[ScrollElementNode] | None=None,
+ dom_interactive_nodes:list[TreeElementNode] | None=None, dom_informative_nodes:list[TextElementNode] | None=None,
is_dom:bool=False, is_dialog:bool=False,
- element_cache_req:Optional[Any]=None, children_cache_req:Optional[Any]=None,
+ element_cache_req:Any | None=None, children_cache_req:Any | None=None,
hwnd:int=0):
try:
# Build cached control if caching is enabled
if not hasattr(node, '_is_cached') and element_cache_req:
node = CachedControlHelper.build_cached_control(node, element_cache_req)
-
+
# Checks to skip the nodes that are not interactive
is_offscreen = node.CachedIsOffscreen
control_type_name = node.CachedControlTypeName
# class_name = node.CachedClassName
-
+
# Scrollable check
if scrollable_nodes is not None:
if (control_type_name not in (INTERACTIVE_CONTROL_TYPE_NAMES|INFORMATIVE_CONTROL_TYPE_NAMES)) and not is_offscreen:
@@ -302,7 +337,7 @@ class Tree:
}))
except Exception:
pass
-
+
# Interactive and Informative checks
# Pre-calculate common properties
is_control_element = node.CachedIsControlElement
@@ -310,10 +345,10 @@ class Tree:
width = element_bounding_box.width()
height = element_bounding_box.height()
area = width * height
-
+
# Is Visible Check
is_visible = (area > 0) and (not is_offscreen or control_type_name=="EditControl" or (control_type_name=="ListItemControl" and is_browser)) and is_control_element
-
+
if is_visible:
is_enabled = node.CachedIsEnabled
if is_enabled:
@@ -323,7 +358,7 @@ class Tree:
else:
#Experimentally, ListItemControl is keyboard focusable
is_keyboard_focusable = node.CachedIsKeyboardFocusable
-
+
# Interactive Check
if interactive_nodes is not None:
is_interactive = False
@@ -338,17 +373,17 @@ class Tree:
is_role_interactive = AccessibleRoleNames.get(role, "Default") in INTERACTIVE_ROLES
except Exception:
is_role_interactive = False
-
+
# Image check
is_image = False
if control_type_name == 'ImageControl': # approximated
localized = node.CachedLocalizedControlType
if localized == 'graphic' or not is_keyboard_focusable:
is_image = True
-
+
if is_role_interactive and (not is_image or is_keyboard_focusable):
is_interactive = True
-
+
elif control_type_name == 'GroupControl':
if is_browser:
try:
@@ -385,7 +420,7 @@ class Tree:
metadata['has_focused']=is_focused
if accelerator_key:
metadata['shortcut']=accelerator_key
-
+
try:
help_text = node.CachedHelpText
if help_text:
@@ -419,7 +454,7 @@ class Tree:
metadata['is_password']=True
except Exception:
pass
-
+
if isinstance(node,ComboBoxControl):
try:
control_state=node.GetCachedPropertyValue(PropertyId.ExpandCollapseExpandCollapseStateProperty)
@@ -435,7 +470,7 @@ class Tree:
except Exception:
pass
- try:
+ try:
can_select_multiple=node.GetCachedPropertyValue(PropertyId.SelectionCanSelectMultipleProperty)
metadata['is_selection_required']=can_select_multiple
except Exception:
@@ -515,25 +550,25 @@ class Tree:
is_image_check = False
if control_type_name == 'ImageControl':
localized = node.CachedLocalizedControlType
-
+
if not is_keyboard_focusable:
if localized == 'graphic':
is_image_check = True
else:
is_image_check = True
- elif localized == 'graphic':
+ elif localized == 'graphic':
is_image_check = True
if not is_image_check:
is_text = True
-
+
if is_text:
if is_browser and is_dom:
name = node.CachedName
dom_informative_nodes.append(TextElementNode(
text=(name or '').strip(),
))
-
+
# Phase 3: Cached Children Retrieval
children = CachedControlHelper.get_cached_children(node, children_cache_req)
@@ -590,7 +625,7 @@ class Tree:
return "Context Menu"
case _:
return window_name
-
+
def get_nodes(self, handle: int, is_browser:bool=False, wait_time:float=0) -> tuple[list[TreeElementNode],list[ScrollElementNode],list[TextElementNode]]:
if wait_time > 0:
sleep(wait_time)
@@ -602,12 +637,12 @@ class Tree:
# Create fresh cache requests for this traversal session
element_cache_req = CacheRequestFactory.create_tree_traversal_cache()
element_cache_req.TreeScope = TreeScope.TreeScope_Element
-
+
children_cache_req = CacheRequestFactory.create_tree_traversal_cache()
children_cache_req.TreeScope = TreeScope.TreeScope_Element | TreeScope.TreeScope_Children
window_bounding_box=node.BoundingRectangle
-
+
interactive_nodes, dom_interactive_nodes, dom_informative_nodes, scrollable_nodes = [], [], [], []
window_name=(node.Name or '').strip()
window_name=self.window_name_correction(window_name)
diff --git a/windows_use/agent/tree/utils.py b/windows_use/agent/tree/utils.py
index 42ceba4..1c1a18e 100644
--- a/windows_use/agent/tree/utils.py
+++ b/windows_use/agent/tree/utils.py
@@ -1,6 +1,8 @@
import random
+
from windows_use.uia import Control
+
def random_point_within_bounding_box(node: Control, scale_factor: float = 1.0) -> tuple[int, int]:
"""
Generate a random point within a scaled-down bounding box.
diff --git a/windows_use/agent/tree/views.py b/windows_use/agent/tree/views.py
index affd480..7524d59 100644
--- a/windows_use/agent/tree/views.py
+++ b/windows_use/agent/tree/views.py
@@ -1,13 +1,13 @@
-from dataclasses import dataclass,field
-from typing import TYPE_CHECKING, Optional,Any,Union
import json
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Optional
WARNING_MESSAGE="The desktop UI services are temporarily unavailable. Please wait a few seconds and continue."
EMPTY_MESSAGE="No elements found"
if TYPE_CHECKING:
- from windows_use.uia.core import Rect
from windows_use.uia.controls import Control
+ from windows_use.uia.core import Rect
@dataclass
class TreeState:
@@ -59,7 +59,7 @@ class TreeState:
rows.append(row)
parts.append("\n".join(rows))
return "\n".join(parts)
-
+
@dataclass
class BoundingBox:
left:int
@@ -85,11 +85,11 @@ class BoundingBox:
def xywh_to_string(self):
return f'({self.left},{self.top},{self.width},{self.height})'
-
+
def xyxy_to_string(self):
x1,y1,x2,y2=self.convert_xywh_to_xyxy()
return f'({x1},{y1},{x2},{y2})'
-
+
def convert_xywh_to_xyxy(self)->tuple[int,int,int,int]:
x1,y1=self.left,self.top
x2,y2=self.left+self.width,self.top+self.height
@@ -156,7 +156,7 @@ class TextElementNode:
ElementNode=TreeElementNode|ScrollElementNode|TextElementNode
-_SelectorNode = Union[TreeElementNode, ScrollElementNode]
+_SelectorNode = TreeElementNode | ScrollElementNode
class SelectorMap(dict):
"""Maps element index (as shown in the tree output) to its node.
diff --git a/windows_use/agent/views.py b/windows_use/agent/views.py
index 599a680..917a3a8 100644
--- a/windows_use/agent/views.py
+++ b/windows_use/agent/views.py
@@ -1,6 +1,7 @@
-from windows_use.messages import BaseMessage
from dataclasses import dataclass, field
+from windows_use.messages import BaseMessage
+
@dataclass
class AgentResult:
diff --git a/windows_use/agent/watchdog/__init__.py b/windows_use/agent/watchdog/__init__.py
index 413c251..8cfb1aa 100644
--- a/windows_use/agent/watchdog/__init__.py
+++ b/windows_use/agent/watchdog/__init__.py
@@ -1 +1 @@
-from .service import WatchDog
+from .service import WatchDog as WatchDog
diff --git a/windows_use/agent/watchdog/event_handlers.py b/windows_use/agent/watchdog/event_handlers.py
index aed7386..feb110b 100644
--- a/windows_use/agent/watchdog/event_handlers.py
+++ b/windows_use/agent/watchdog/event_handlers.py
@@ -1,7 +1,9 @@
-from windows_use.uia.core import _AutomationClient
-import comtypes
import weakref
+import comtypes
+
+from windows_use.uia.core import _AutomationClient
+
# Get UIA Interface for COM definitions
uia_client = _AutomationClient.instance()
UIA = uia_client.UIAutomationCore
@@ -11,7 +13,7 @@ class FocusChangedEventHandler(comtypes.COMObject):
def __init__(self, parent):
self._parent = weakref.ref(parent)
- super(FocusChangedEventHandler, self).__init__()
+ super().__init__()
def HandleFocusChangedEvent(self, sender):
try:
@@ -27,7 +29,7 @@ class StructureChangedEventHandler(comtypes.COMObject):
def __init__(self, parent):
self._parent = weakref.ref(parent)
- super(StructureChangedEventHandler, self).__init__()
+ super().__init__()
def HandleStructureChangedEvent(self, sender, changeType, runtimeId):
try:
@@ -43,7 +45,7 @@ class PropertyChangedEventHandler(comtypes.COMObject):
def __init__(self, parent):
self._parent = weakref.ref(parent)
- super(PropertyChangedEventHandler, self).__init__()
+ super().__init__()
def HandlePropertyChangedEvent(self, sender, propertyId, newValue):
try:
diff --git a/windows_use/agent/watchdog/service.py b/windows_use/agent/watchdog/service.py
index b543458..25190d1 100644
--- a/windows_use/agent/watchdog/service.py
+++ b/windows_use/agent/watchdog/service.py
@@ -2,13 +2,14 @@
Unified WatchDog Service for monitoring UI Automation events.
Allows single instantiation to handle multiple monitors (Focus, Structure) safely in one STA thread.
"""
+import logging
+from threading import Event, Thread
+
+import comtypes
+import comtypes.client
+
from windows_use.uia.core import _AutomationClient
from windows_use.uia.enums import TreeScope
-from threading import Thread, Event
-import comtypes.client
-import comtypes
-import logging
-import weakref
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@@ -27,7 +28,7 @@ class WatchDog:
self._property_callback = None
self._property_element = None
self._property_ids = None
-
+
# Internal state for tracking active handlers
self._focus_handler = None
self._structure_handler = None
@@ -49,7 +50,7 @@ class WatchDog:
return
self.is_running.set()
self.thread = Thread(target=self._run, name="WatchDogThread")
- self.thread.daemon = True
+ self.thread.daemon = True
self.thread.start()
def stop(self):
@@ -75,7 +76,7 @@ class WatchDog:
def set_property_callback(self, callback, element=None, property_ids=None):
"""Set the callback for property changes. Pass None to disable.
- Optionally specify an element to watch (defaults to RootElement)
+ Optionally specify an element to watch (defaults to RootElement)
and a list of property IDs to monitor."""
self._property_callback = callback
self._property_element = element
@@ -159,8 +160,8 @@ class WatchDog:
try:
from .event_handlers import (
FocusChangedEventHandler,
+ PropertyChangedEventHandler,
StructureChangedEventHandler,
- PropertyChangedEventHandler
)
# Initialize UIA inside the thread
uia_client = _AutomationClient.instance()
@@ -179,12 +180,12 @@ class WatchDog:
# Cleanup handlers on exit
if self.uia:
if self._focus_handler:
- try:
+ try:
self.uia.RemoveFocusChangedEventHandler(self._focus_handler)
except Exception:
pass
self._focus_handler = None
-
+
if self._structure_handler:
try:
target = self._active_structure_element if self._active_structure_element else self.uia.GetRootElement()
@@ -203,5 +204,5 @@ class WatchDog:
self._property_handler = None
self._active_property_element = None
self._active_property_ids = None
-
+
comtypes.CoUninitialize()
diff --git a/windows_use/cli/__main__.py b/windows_use/cli/__main__.py
index c13ee10..67c0579 100644
--- a/windows_use/cli/__main__.py
+++ b/windows_use/cli/__main__.py
@@ -4,13 +4,11 @@ import logging
import os
import re
import sys
-import time
import threading
-
-from dotenv import load_dotenv
+import time
import typer
-
+from dotenv import load_dotenv
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import Completer, Completion
@@ -193,10 +191,15 @@ def _clear_screen() -> None:
def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = False) -> None:
"""Run the interactive task loop."""
- from windows_use.cli.setup import create_llm, run_llm_switch, run_speech_setup
- from windows_use.cli.setup import create_stt_provider, create_tts_provider
- from windows_use.cli.config import get_active_config
from windows_use.agent import Agent, Browser
+ from windows_use.cli.config import get_active_config
+ from windows_use.cli.setup import (
+ create_llm,
+ create_stt_provider,
+ create_tts_provider,
+ run_llm_switch,
+ run_speech_setup,
+ )
from windows_use.cli.subscriber import CLIEventSubscriber
agent = None
@@ -315,7 +318,11 @@ def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = Fa
if task.lower() in ("speech", "\\speech"):
try:
- from windows_use.cli.setup import run_speech_setup, create_stt_provider, create_tts_provider
+ from windows_use.cli.setup import (
+ create_stt_provider,
+ create_tts_provider,
+ run_speech_setup,
+ )
run_speech_setup(initial_setup=False)
stt_provider = create_stt_provider()
tts_provider = create_tts_provider()
@@ -399,8 +406,8 @@ def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = Fa
task = _prompt_task(default=task)
if not task:
continue
- except ImportError as e:
- typer.secho(f"Voice input requires pyaudio: uv add windows-use[speech]", fg="yellow")
+ except ImportError:
+ typer.secho("Voice input requires pyaudio: uv add windows-use[speech]", fg="yellow")
continue
except Exception as e:
typer.secho(f"Voice input failed: {e}", fg="red")
diff --git a/windows_use/cli/setup.py b/windows_use/cli/setup.py
index 646836b..6b7dd5c 100644
--- a/windows_use/cli/setup.py
+++ b/windows_use/cli/setup.py
@@ -21,13 +21,18 @@ from windows_use.cli.config import (
update_provider_base_url,
upsert_provider,
)
-from windows_use.cli.registry import get_provider_display, get_providers, get_models, provider_requires_api_key
+from windows_use.cli.registry import (
+ get_models,
+ get_provider_display,
+ get_providers,
+ provider_requires_api_key,
+)
from windows_use.cli.speech_registry import (
+ SPEECH_PROVIDERS_OWN_KEY,
get_stt_models,
get_stt_providers,
get_tts_models,
get_tts_providers,
- SPEECH_PROVIDERS_OWN_KEY,
speech_provider_requires_api_key,
)
diff --git a/windows_use/cli/subscriber.py b/windows_use/cli/subscriber.py
index a2687d7..dc04f55 100644
--- a/windows_use/cli/subscriber.py
+++ b/windows_use/cli/subscriber.py
@@ -4,12 +4,13 @@ CLI-specific event subscriber for simple terminal output.
from __future__ import annotations
-from typing import Callable
+from collections.abc import Callable
-from windows_use.agent.events.views import AgentEvent, EventType
-from windows_use.agent.events.subscriber import BaseEventSubscriber
-from rich.markdown import Markdown
from rich.console import Console
+from rich.markdown import Markdown
+
+from windows_use.agent.events.subscriber import BaseEventSubscriber
+from windows_use.agent.events.views import AgentEvent, EventType
def _format_tool_name(tool_name: str) -> str:
diff --git a/windows_use/messages/__init__.py b/windows_use/messages/__init__.py
index 1ea69d8..24af8b7 100644
--- a/windows_use/messages/__init__.py
+++ b/windows_use/messages/__init__.py
@@ -1,9 +1,9 @@
from .service import (
+ AIMessage,
BaseMessage,
- SystemMessage,
HumanMessage,
- AIMessage,
ImageMessage,
+ SystemMessage,
ToolMessage,
Usage,
)
diff --git a/windows_use/messages/service.py b/windows_use/messages/service.py
index 85900bd..1186ad2 100644
--- a/windows_use/messages/service.py
+++ b/windows_use/messages/service.py
@@ -1,11 +1,13 @@
"""Message models (BaseModel from views)."""
-from pydantic import BaseModel, ConfigDict
+import base64
+from io import BytesIO
from textwrap import shorten
from typing import Any, Literal
+
from PIL.Image import Image
-from io import BytesIO
-import base64
+from pydantic import BaseModel, ConfigDict
+
class Usage(BaseModel):
"""Token usage information from LLM responses."""
@@ -72,7 +74,6 @@ class ImageMessage(BaseMessage):
def _compress_image(img, mime_type: str, max_bytes: int = 4_800_000) -> tuple[bytes, str]:
if Image is None:
raise ImportError("Pillow is required for ImageMessage. Install with: pip install pillow")
- from PIL.Image import Image as PILImage
def _save(image, fmt: str, quality: int) -> bytes:
buf = BytesIO()
diff --git a/windows_use/providers/__init__.py b/windows_use/providers/__init__.py
index 60b93ed..36aebd5 100644
--- a/windows_use/providers/__init__.py
+++ b/windows_use/providers/__init__.py
@@ -12,29 +12,26 @@ Shared base protocols and data models:
"""
# Base protocols & data models
-from windows_use.providers.base import BaseChatLLM, BaseSTT, BaseTTS
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.providers.events import Thinking, LLMEvent, LLMStreamEvent, ToolCall
-
# LLM providers
from windows_use.providers.anthropic import ChatAnthropic
-from windows_use.providers.google import ChatGoogle
-from windows_use.providers.openai import ChatOpenAI
-from windows_use.providers.ollama import ChatOllama
-from windows_use.providers.groq import ChatGroq
-from windows_use.providers.mistral import ChatMistral
-from windows_use.providers.cerebras import ChatCerebras
-from windows_use.providers.open_router import ChatOpenRouter
from windows_use.providers.azure_openai import ChatAzureOpenAI
+from windows_use.providers.base import BaseChatLLM, BaseSTT, BaseTTS
+from windows_use.providers.cerebras import ChatCerebras
+from windows_use.providers.deepseek import ChatDeepSeek
+from windows_use.providers.events import LLMEvent, LLMStreamEvent, Thinking, ToolCall
+from windows_use.providers.google import ChatGoogle, STTGoogle
+from windows_use.providers.groq import ChatGroq, STTGroq
from windows_use.providers.litellm import ChatLiteLLM
-from windows_use.providers.vllm import ChatVLLM
+from windows_use.providers.mistral import ChatMistral
from windows_use.providers.nvidia import ChatNvidia
-from windows_use.providers.deepseek import ChatDeepSeek
+from windows_use.providers.ollama import ChatOllama
+from windows_use.providers.open_router import ChatOpenRouter
# STT providers
-from windows_use.providers.openai import STTOpenAI
-from windows_use.providers.google import STTGoogle
-from windows_use.providers.groq import STTGroq
+from windows_use.providers.openai import ChatOpenAI, STTOpenAI
+from windows_use.providers.views import Metadata, TokenUsage
+from windows_use.providers.vllm import ChatVLLM
+
try:
from windows_use.providers.elevenlabs import STTElevenLabs
except ImportError:
@@ -46,9 +43,9 @@ except ImportError:
pass
# TTS providers
-from windows_use.providers.openai import TTSOpenAI
from windows_use.providers.google import TTSGoogle
from windows_use.providers.groq import TTSGroq
+from windows_use.providers.openai import TTSOpenAI
try:
from windows_use.providers.elevenlabs import TTSElevenLabs
diff --git a/windows_use/providers/anthropic/llm.py b/windows_use/providers/anthropic/llm.py
index 5b6244e..f97565d 100644
--- a/windows_use/providers/anthropic/llm.py
+++ b/windows_use/providers/anthropic/llm.py
@@ -1,14 +1,31 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, Union, overload
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
from anthropic import Anthropic, AsyncAnthropic
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -16,16 +33,16 @@ class ChatAnthropic(BaseChatLLM):
"""
Anthropic LLM implementation following the BaseChatLLM protocol.
"""
-
+
def __init__(
self,
model: str = "claude-3-5-sonnet-latest",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
timeout: float = 600.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
- thinking_budget: Optional[int] = None,
+ temperature: float | None = None,
+ thinking_budget: int | None = None,
max_tokens: int = 4096,
enable_prompt_caching: bool = True,
cache_system_prompt: bool = True,
@@ -85,7 +102,7 @@ class ChatAnthropic(BaseChatLLM):
"temperature is ignored when extended thinking is enabled "
"(Anthropic requires temperature=1)."
)
-
+
self.client = Anthropic(
api_key=self.api_key,
base_url=self.base_url,
@@ -108,16 +125,16 @@ class ChatAnthropic(BaseChatLLM):
def provider(self) -> str:
return "anthropic"
- def _convert_messages(self, messages: List[BaseMessage]) -> tuple[Optional[Union[str, List[dict]]], List[dict]]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> tuple[str | list[dict] | None, list[dict]]:
"""
Convert BaseMessage objects to Anthropic-compatible message dictionaries.
Returns (system_prompt, messages).
-
+
Adds cache control breakpoints based on configuration.
"""
anthropic_messages = []
system_prompt = None
-
+
for msg in messages:
if isinstance(msg, SystemMessage):
system_prompt = msg.content
@@ -127,7 +144,7 @@ class ChatAnthropic(BaseChatLLM):
content = []
if msg.content:
content.append({"type": "text", "text": msg.content})
-
+
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
content.append({
@@ -143,8 +160,8 @@ class ChatAnthropic(BaseChatLLM):
content = []
if msg.thinking:
content.append({
- "type": "thinking",
- "thinking": msg.thinking,
+ "type": "thinking",
+ "thinking": msg.thinking,
"signature": msg.thinking_signature
})
if msg.content:
@@ -165,7 +182,7 @@ class ChatAnthropic(BaseChatLLM):
"name": msg.name,
"input": msg.params
})
-
+
# Anthropic requires a tool_use block followed by a tool_result block
if anthropic_messages and anthropic_messages[-1]["role"] == "assistant":
last_content = anthropic_messages[-1]["content"]
@@ -179,7 +196,7 @@ class ChatAnthropic(BaseChatLLM):
"role": "assistant",
"content": content_blocks
})
-
+
# Add the tool result
anthropic_messages.append({
"role": "user",
@@ -189,7 +206,7 @@ class ChatAnthropic(BaseChatLLM):
"content": msg.content or ""
}]
})
-
+
# Apply prompt caching to system prompt
if system_prompt and self.enable_prompt_caching and self.cache_system_prompt:
system_prompt = [
@@ -199,35 +216,35 @@ class ChatAnthropic(BaseChatLLM):
"cache_control": {"type": "ephemeral"}
}
]
-
+
# Apply prompt caching to recent messages
if self.enable_prompt_caching and self.cache_recent_messages > 0 and anthropic_messages:
# Cache the last N user messages (caching works best on user turns)
user_message_indices = [
- i for i, msg in enumerate(anthropic_messages)
+ i for i, msg in enumerate(anthropic_messages)
if msg["role"] == "user"
]
-
+
# Get the indices to cache (last N user messages)
indices_to_cache = user_message_indices[-self.cache_recent_messages:]
-
+
for idx in indices_to_cache:
msg = anthropic_messages[idx]
content = msg["content"]
-
+
# Convert string content to list format for cache control
if isinstance(content, str):
content = [{"type": "text", "text": content}]
-
+
# Add cache control to the last content block
if isinstance(content, list) and len(content) > 0:
# Only add cache control to the last block in the message
content[-1]["cache_control"] = {"type": "ephemeral"}
msg["content"] = content
-
+
return system_prompt, anthropic_messages
- def _build_params(self, anthropic_messages: List[dict], system_prompt: Any, anthropic_tools: Optional[List[dict]]) -> dict:
+ def _build_params(self, anthropic_messages: list[dict], system_prompt: Any, anthropic_tools: list[dict] | None) -> dict:
"""Build the common API parameters for all invoke/stream methods."""
params = {
"model": self._model,
@@ -254,7 +271,7 @@ class ChatAnthropic(BaseChatLLM):
return params
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Anthropic-compatible tool definitions.
Adds cache control to tools if enabled.
@@ -267,11 +284,11 @@ class ChatAnthropic(BaseChatLLM):
}
for tool in tools
]
-
+
# Add cache control to the last tool definition
if self.enable_prompt_caching and self.cache_tools and tool_defs:
tool_defs[-1]["cache_control"] = {"type": "ephemeral"}
-
+
return tool_defs
def _process_response(self, response: Any) -> LLMEvent:
@@ -345,7 +362,7 @@ class ChatAnthropic(BaseChatLLM):
system_prompt, anthropic_messages = self._convert_messages(messages)
anthropic_tools = self._convert_tools(tools) if tools else None
params = self._build_params(anthropic_messages, system_prompt, anthropic_tools)
-
+
if structured_output:
# Simulate structured output via tool calling
structured_tool = {
@@ -353,24 +370,24 @@ class ChatAnthropic(BaseChatLLM):
"description": f"Record the structured result: {structured_output.__name__}",
"input_schema": structured_output.model_json_schema()
}
-
+
# Add cache control to structured output tool if caching enabled
if self.enable_prompt_caching and self.cache_tools:
structured_tool["cache_control"] = {"type": "ephemeral"}
-
+
params["tools"] = [structured_tool]
params["tool_choice"] = {"type": "tool", "name": "record_result"}
# Forced tool_choice is incompatible with extended thinking
params.pop("thinking", None)
-
+
response = self.client.messages.create(**params)
tool_use = next(b for b in response.content if b.type == "tool_use")
parsed = structured_output(**tool_use.input)
-
+
# Extract cache metrics
cache_creation_tokens = getattr(response.usage, 'cache_creation_input_tokens', None) or 0
cache_read_tokens = getattr(response.usage, 'cache_read_input_tokens', None) or 0
-
+
usage = TokenUsage(
prompt_tokens=response.usage.input_tokens,
completion_tokens=response.usage.output_tokens,
@@ -394,29 +411,29 @@ class ChatAnthropic(BaseChatLLM):
system_prompt, anthropic_messages = self._convert_messages(messages)
anthropic_tools = self._convert_tools(tools) if tools else None
params = self._build_params(anthropic_messages, system_prompt, anthropic_tools)
-
+
if structured_output:
structured_tool = {
"name": "record_result",
"description": f"Record the structured result: {structured_output.__name__}",
"input_schema": structured_output.model_json_schema()
}
-
+
if self.enable_prompt_caching and self.cache_tools:
structured_tool["cache_control"] = {"type": "ephemeral"}
-
+
params["tools"] = [structured_tool]
params["tool_choice"] = {"type": "tool", "name": "record_result"}
# Forced tool_choice is incompatible with extended thinking
params.pop("thinking", None)
-
+
response = await self.aclient.messages.create(**params)
tool_use = next(b for b in response.content if b.type == "tool_use")
parsed = structured_output(**tool_use.input)
-
+
cache_creation_tokens = getattr(response.usage, 'cache_creation_input_tokens', None) or 0
cache_read_tokens = getattr(response.usage, 'cache_read_input_tokens', None) or 0
-
+
usage = TokenUsage(
prompt_tokens=response.usage.input_tokens,
completion_tokens=response.usage.output_tokens,
@@ -440,7 +457,7 @@ class ChatAnthropic(BaseChatLLM):
system_prompt, anthropic_messages = self._convert_messages(messages)
anthropic_tools = self._convert_tools(tools) if tools else None
params = self._build_params(anthropic_messages, system_prompt, anthropic_tools)
-
+
text_started = False
think_started = False
usage = None
@@ -501,7 +518,7 @@ class ChatAnthropic(BaseChatLLM):
system_prompt, anthropic_messages = self._convert_messages(messages)
anthropic_tools = self._convert_tools(tools) if tools else None
params = self._build_params(anthropic_messages, system_prompt, anthropic_tools)
-
+
text_started = False
think_started = False
usage = None
@@ -564,7 +581,7 @@ class ChatAnthropic(BaseChatLLM):
def get_cache_stats(self) -> dict:
"""
Return information about the current caching configuration.
-
+
Returns:
dict: Cache configuration details
"""
diff --git a/windows_use/providers/azure_openai/llm.py b/windows_use/providers/azure_openai/llm.py
index d545710..90c2f52 100644
--- a/windows_use/providers/azure_openai/llm.py
+++ b/windows_use/providers/azure_openai/llm.py
@@ -1,14 +1,31 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, Union, overload
-from openai import AzureOpenAI, AsyncAzureOpenAI
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
+from openai import AsyncAzureOpenAI, AzureOpenAI
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -16,16 +33,16 @@ class ChatAzureOpenAI(BaseChatLLM):
"""
Azure OpenAI LLM implementation following the BaseChatLLM protocol.
"""
-
+
def __init__(
self,
deployment_name: str,
- api_key: Optional[str] = None,
- azure_endpoint: Optional[str] = None,
+ api_key: str | None = None,
+ azure_endpoint: str | None = None,
api_version: str = "2024-02-01",
timeout: float = 600.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
**kwargs
):
"""
@@ -45,7 +62,7 @@ class ChatAzureOpenAI(BaseChatLLM):
self.api_key = api_key or os.environ.get("AZURE_OPENAI_API_KEY")
self.azure_endpoint = azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT")
self.temperature = temperature
-
+
self.client = AzureOpenAI(
api_key=self.api_key,
azure_endpoint=self.azure_endpoint,
@@ -74,7 +91,7 @@ class ChatAzureOpenAI(BaseChatLLM):
"""Check if the deployment is a reasoning model (o-series: o1, o3, o4, etc.)."""
return self._deployment.startswith(("o1", "o3", "o4"))
- def _convert_messages(self, messages: List[BaseMessage]) -> List[dict]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
Convert BaseMessage objects to Azure-compatible message dictionaries.
"""
@@ -88,7 +105,7 @@ class ChatAzureOpenAI(BaseChatLLM):
content_list = []
if msg.content:
content_list.append({"type": "text", "text": msg.content})
-
+
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
content_list.append({
@@ -123,7 +140,7 @@ class ChatAzureOpenAI(BaseChatLLM):
})
return openai_messages
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Azure-compatible tool definitions.
"""
@@ -202,21 +219,21 @@ class ChatAzureOpenAI(BaseChatLLM):
def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._deployment,
"messages": openai_messages,
**self.kwargs
}
-
+
# Only add tools if they exist
if openai_tools:
params["tools"] = openai_tools
-
+
# Reasoning models don't support temperature
if self.temperature is not None and not self._is_reasoning_model():
params["temperature"] = self.temperature
-
+
if structured_output:
# Use beta parse endpoint for structured outputs
response = self.client.beta.chat.completions.parse(
@@ -231,7 +248,7 @@ class ChatAzureOpenAI(BaseChatLLM):
) or getattr(
response.usage.completion_tokens_details, "thinking_tokens", None
)
- usage = TokenUsage(
+ TokenUsage(
prompt_tokens=response.usage.prompt_tokens,
completion_tokens=response.usage.completion_tokens,
total_tokens=response.usage.total_tokens,
@@ -241,10 +258,10 @@ class ChatAzureOpenAI(BaseChatLLM):
parsed = response.choices[0].message.parsed
content_dump = parsed.model_dump()
return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump))
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
return self._process_response(response)
@@ -255,20 +272,20 @@ class ChatAzureOpenAI(BaseChatLLM):
async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._deployment,
"messages": openai_messages,
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
# Reasoning models don't support temperature
if self.temperature is not None and not self._is_reasoning_model():
params["temperature"] = self.temperature
-
+
if structured_output:
response = await self.aclient.beta.chat.completions.parse(
**params,
@@ -292,10 +309,10 @@ class ChatAzureOpenAI(BaseChatLLM):
parsed = response.choices[0].message.parsed
content_dump = parsed.model_dump()
return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump), usage=usage)
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
return self._process_response(response)
@@ -306,7 +323,7 @@ class ChatAzureOpenAI(BaseChatLLM):
def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._deployment,
"messages": openai_messages,
@@ -314,24 +331,24 @@ class ChatAzureOpenAI(BaseChatLLM):
"stream_options": {"include_usage": True},
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None and not self._is_reasoning_model():
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
usage = None
@@ -353,9 +370,9 @@ class ChatAzureOpenAI(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
-
+
# Handle reasoning content for o-series models
if self._is_reasoning_model() and hasattr(delta, 'reasoning_content') and delta.reasoning_content:
if not think_started:
@@ -382,14 +399,14 @@ class ChatAzureOpenAI(BaseChatLLM):
tool_call_name = tc_delta.function.name
if tc_delta.function.arguments:
tool_call_args += tc_delta.function.arguments
-
+
# Yield accumulated tool call as final response
if tool_call_id and tool_call_name:
try:
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -411,7 +428,7 @@ class ChatAzureOpenAI(BaseChatLLM):
async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._deployment,
"messages": openai_messages,
@@ -419,24 +436,24 @@ class ChatAzureOpenAI(BaseChatLLM):
"stream_options": {"include_usage": True},
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None and not self._is_reasoning_model():
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
usage = None
@@ -458,9 +475,9 @@ class ChatAzureOpenAI(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
-
+
if self._is_reasoning_model() and hasattr(delta, 'reasoning_content') and delta.reasoning_content:
if not think_started:
think_started = True
@@ -486,14 +503,14 @@ class ChatAzureOpenAI(BaseChatLLM):
tool_call_name = tc_delta.function.name
if tc_delta.function.arguments:
tool_call_args += tc_delta.function.arguments
-
+
# Yield accumulated tool call as final response
if tool_call_id and tool_call_name:
try:
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
diff --git a/windows_use/providers/base.py b/windows_use/providers/base.py
index 50f283b..f4b78a0 100644
--- a/windows_use/providers/base.py
+++ b/windows_use/providers/base.py
@@ -1,10 +1,12 @@
-from typing import Protocol, runtime_checkable, overload, Iterator, AsyncIterator
+from collections.abc import AsyncIterator, Iterable, Iterator
+from typing import Protocol, overload, runtime_checkable
+
+from pydantic import BaseModel
+
+from windows_use.messages import BaseMessage
from windows_use.providers.events import LLMEvent, LLMStreamEvent
from windows_use.providers.views import Metadata
-from windows_use.messages import BaseMessage
-from collections.abc import Iterable
from windows_use.tools import Tool
-from pydantic import BaseModel
@runtime_checkable
diff --git a/windows_use/providers/cerebras/__init__.py b/windows_use/providers/cerebras/__init__.py
index b4063e1..41d9110 100644
--- a/windows_use/providers/cerebras/__init__.py
+++ b/windows_use/providers/cerebras/__init__.py
@@ -1,3 +1,3 @@
from windows_use.providers.cerebras.llm import ChatCerebras
-__all__ = ["ChatCerebras"]
\ No newline at end of file
+__all__ = ["ChatCerebras"]
diff --git a/windows_use/providers/cerebras/llm.py b/windows_use/providers/cerebras/llm.py
index 3904c01..1331aa4 100644
--- a/windows_use/providers/cerebras/llm.py
+++ b/windows_use/providers/cerebras/llm.py
@@ -1,14 +1,31 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, overload
-from cerebras.cloud.sdk import Cerebras, AsyncCerebras
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
+from cerebras.cloud.sdk import AsyncCerebras, Cerebras
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -16,15 +33,15 @@ class ChatCerebras(BaseChatLLM):
"""
Cerebras LLM implementation following the BaseChatLLM protocol.
"""
-
+
def __init__(
self,
model: str = "llama-3.3-70b",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
timeout: float = 60.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
**kwargs
):
"""
@@ -42,7 +59,7 @@ class ChatCerebras(BaseChatLLM):
self._model = model
self.api_key = api_key or os.environ.get("CEREBRAS_API_KEY")
self.temperature = temperature
-
+
self.client = Cerebras(
api_key=self.api_key,
base_url=base_url,
@@ -80,7 +97,7 @@ class ChatCerebras(BaseChatLLM):
return f"{thinking} {text}".strip() if text else thinking
return f"<think>{thinking}</think>{text}" if text else f"<think>{thinking}</think>"
- def _convert_messages(self, messages: List[BaseMessage]) -> List[dict]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
Convert BaseMessage objects to Cerebras-compatible message dictionaries.
"""
@@ -95,7 +112,7 @@ class ChatCerebras(BaseChatLLM):
content_list = []
if msg.content:
content_list.append({"type": "text", "text": msg.content})
-
+
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
content_list.append({
@@ -129,7 +146,7 @@ class ChatCerebras(BaseChatLLM):
})
return cerebras_messages
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Cerebras-compatible tool definitions.
"""
@@ -196,13 +213,13 @@ class ChatCerebras(BaseChatLLM):
def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
cerebras_messages = self._convert_messages(messages)
cerebras_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": cerebras_messages,
**self.kwargs
}
-
+
# Only add tools if they exist
if cerebras_tools:
params["tools"] = cerebras_tools
@@ -210,15 +227,15 @@ class ChatCerebras(BaseChatLLM):
params["reasoning_format"] = "parsed"
if "gpt-oss" in self._model.lower():
params["reasoning_effort"] = params.get("reasoning_effort", "medium")
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if structured_output or json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
-
+
if structured_output:
try:
parsed = structured_output.model_validate_json(response.choices[0].message.content)
@@ -252,28 +269,28 @@ class ChatCerebras(BaseChatLLM):
async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
cerebras_messages = self._convert_messages(messages)
cerebras_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": cerebras_messages,
**self.kwargs
}
-
+
if cerebras_tools:
params["tools"] = cerebras_tools
if self._is_reasoning_model():
params["reasoning_format"] = "parsed"
if "gpt-oss" in self._model.lower():
params["reasoning_effort"] = params.get("reasoning_effort", "medium")
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if structured_output or json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
-
+
if structured_output:
try:
parsed = structured_output.model_validate_json(response.choices[0].message.content)
@@ -296,35 +313,35 @@ class ChatCerebras(BaseChatLLM):
def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
cerebras_messages = self._convert_messages(messages)
cerebras_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": cerebras_messages,
"stream": True,
**self.kwargs
}
-
+
if cerebras_tools:
params["tools"] = cerebras_tools
if self._is_reasoning_model():
params["reasoning_format"] = "parsed"
if "gpt-oss" in self._model.lower():
params["reasoning_effort"] = params.get("reasoning_effort", "medium")
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if structured_output or json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -347,9 +364,9 @@ class ChatCerebras(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
-
+
reasoning_delta = getattr(delta, "reasoning", None)
if reasoning_delta:
if not think_started:
@@ -382,7 +399,7 @@ class ChatCerebras(BaseChatLLM):
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -405,35 +422,35 @@ class ChatCerebras(BaseChatLLM):
async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
cerebras_messages = self._convert_messages(messages)
cerebras_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": cerebras_messages,
"stream": True,
**self.kwargs
}
-
+
if cerebras_tools:
params["tools"] = cerebras_tools
if self._is_reasoning_model():
params["reasoning_format"] = "parsed"
if "gpt-oss" in self._model.lower():
params["reasoning_effort"] = params.get("reasoning_effort", "medium")
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if structured_output or json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -456,7 +473,7 @@ class ChatCerebras(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
reasoning_delta = getattr(delta, "reasoning", None)
@@ -491,7 +508,7 @@ class ChatCerebras(BaseChatLLM):
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
diff --git a/windows_use/providers/deepgram/stt.py b/windows_use/providers/deepgram/stt.py
index 5185268..5759ec9 100644
--- a/windows_use/providers/deepgram/stt.py
+++ b/windows_use/providers/deepgram/stt.py
@@ -1,6 +1,5 @@
-import os
import logging
-from typing import Optional
+import os
from deepgram import DeepgramClient, PrerecordedOptions
@@ -46,8 +45,8 @@ class STTDeepgram(BaseSTT):
def __init__(
self,
model: str = "nova-2",
- api_key: Optional[str] = None,
- language: Optional[str] = None,
+ api_key: str | None = None,
+ language: str | None = None,
smart_format: bool = True,
diarize: bool = False,
):
diff --git a/windows_use/providers/deepgram/tts.py b/windows_use/providers/deepgram/tts.py
index c7ce568..9c56e2a 100644
--- a/windows_use/providers/deepgram/tts.py
+++ b/windows_use/providers/deepgram/tts.py
@@ -1,6 +1,5 @@
-import os
import logging
-from typing import Optional
+import os
from deepgram import DeepgramClient, SpeakOptions
@@ -49,7 +48,7 @@ class TTSDeepgram(BaseTTS):
def __init__(
self,
model: str = "aura-2-thalia-en",
- api_key: Optional[str] = None,
+ api_key: str | None = None,
encoding: str = "linear16",
sample_rate: int = 24000,
):
diff --git a/windows_use/providers/deepseek/llm.py b/windows_use/providers/deepseek/llm.py
index 6056909..df26f7e 100644
--- a/windows_use/providers/deepseek/llm.py
+++ b/windows_use/providers/deepseek/llm.py
@@ -1,7 +1,6 @@
"""DeepSeek LLM provider via OpenAI-compatible API."""
import os
-from typing import Optional
from windows_use.providers.openai.llm import ChatOpenAI
@@ -19,11 +18,11 @@ class ChatDeepSeek(ChatOpenAI):
def __init__(
self,
model: str = "deepseek-chat",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
timeout: float = 600.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
**kwargs,
):
api_key = api_key or os.environ.get("DEEPSEEK_API_KEY")
diff --git a/windows_use/providers/elevenlabs/stt.py b/windows_use/providers/elevenlabs/stt.py
index 8266d47..4c1936f 100644
--- a/windows_use/providers/elevenlabs/stt.py
+++ b/windows_use/providers/elevenlabs/stt.py
@@ -1,8 +1,7 @@
-import os
import logging
-from typing import Optional
+import os
-from elevenlabs.client import ElevenLabs, AsyncElevenLabs
+from elevenlabs.client import AsyncElevenLabs, ElevenLabs
from windows_use.providers.base import BaseSTT
@@ -42,8 +41,8 @@ class STTElevenLabs(BaseSTT):
def __init__(
self,
model: str = "scribe_v2",
- api_key: Optional[str] = None,
- language_code: Optional[str] = None,
+ api_key: str | None = None,
+ language_code: str | None = None,
diarize: bool = False,
tag_audio_events: bool = False,
timeout: float = 120.0,
diff --git a/windows_use/providers/elevenlabs/tts.py b/windows_use/providers/elevenlabs/tts.py
index 7aa279a..e26f0aa 100644
--- a/windows_use/providers/elevenlabs/tts.py
+++ b/windows_use/providers/elevenlabs/tts.py
@@ -1,8 +1,7 @@
-import os
import logging
-from typing import Optional
+import os
-from elevenlabs.client import ElevenLabs, AsyncElevenLabs
+from elevenlabs.client import AsyncElevenLabs, ElevenLabs
from windows_use.providers.base import BaseTTS
@@ -49,10 +48,10 @@ class TTSElevenLabs(BaseTTS):
self,
model: str = "eleven_multilingual_v2",
voice_id: str = "JBFqnCBsd6RMkjVDRZzb",
- api_key: Optional[str] = None,
+ api_key: str | None = None,
output_format: str = "pcm_24000",
- stability: Optional[float] = None,
- similarity_boost: Optional[float] = None,
+ stability: float | None = None,
+ similarity_boost: float | None = None,
timeout: float = 120.0,
):
self._model = model
diff --git a/windows_use/providers/events.py b/windows_use/providers/events.py
index 5c7dc17..fe6a979 100644
--- a/windows_use/providers/events.py
+++ b/windows_use/providers/events.py
@@ -1,9 +1,10 @@
from enum import Enum
+
from pydantic import BaseModel
-from typing import Optional, Any
from windows_use.providers.views import TokenUsage
+
class LLMStreamEventType(str, Enum):
TEXT_START = "text_start"
TEXT_DELTA = "text_delta"
diff --git a/windows_use/providers/google/__init__.py b/windows_use/providers/google/__init__.py
index 8e33ddb..1713192 100644
--- a/windows_use/providers/google/__init__.py
+++ b/windows_use/providers/google/__init__.py
@@ -1,5 +1,5 @@
from windows_use.providers.google.llm import ChatGoogle
from windows_use.providers.google.stt import STTGoogle
-from windows_use.providers.google.tts import TTSGoogle, GOOGLE_TTS_VOICES
+from windows_use.providers.google.tts import GOOGLE_TTS_VOICES, TTSGoogle
__all__ = ["ChatGoogle", "STTGoogle", "TTSGoogle", "GOOGLE_TTS_VOICES"]
diff --git a/windows_use/providers/google/llm.py b/windows_use/providers/google/llm.py
index adda1a0..22c285b 100644
--- a/windows_use/providers/google/llm.py
+++ b/windows_use/providers/google/llm.py
@@ -1,16 +1,33 @@
+import json
+import logging
import os
import uuid
-import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, overload
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
from google import genai
from google.genai import types
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-import json
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -31,10 +48,10 @@ class ChatGoogle(BaseChatLLM):
def __init__(
self,
model: str = "gemini-2.5-flash",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
- temperature: Optional[float] = None,
- thinking_budget: Optional[int] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ temperature: float | None = None,
+ thinking_budget: int | None = None,
**kwargs,
):
"""
@@ -74,8 +91,8 @@ class ChatGoogle(BaseChatLLM):
return "2.5" in self._model
def _convert_messages(
- self, messages: List[BaseMessage]
- ) -> tuple[Optional[str], list[types.Content]]:
+ self, messages: list[BaseMessage]
+ ) -> tuple[str | None, list[types.Content]]:
"""
Convert BaseMessage objects to Google Gemini-compatible content list.
@@ -88,7 +105,7 @@ class ChatGoogle(BaseChatLLM):
A tuple of (system_instruction, contents).
"""
raw_contents: list[types.Content] = []
- system_instruction: Optional[str] = None
+ system_instruction: str | None = None
for msg in messages:
if isinstance(msg, SystemMessage):
@@ -175,7 +192,7 @@ class ChatGoogle(BaseChatLLM):
merged.append(content)
return merged
- def _convert_tools(self, tools: List[Tool]) -> list[types.Tool]:
+ def _convert_tools(self, tools: list[Tool]) -> list[types.Tool]:
"""
Convert Tool objects to Google Gemini-compatible tool definitions.
"""
@@ -193,9 +210,9 @@ class ChatGoogle(BaseChatLLM):
def _build_config(
self,
- system_instruction: Optional[str],
- tools: Optional[list[types.Tool]],
- structured_output: Optional[type[BaseModel]] = None,
+ system_instruction: str | None,
+ tools: list[types.Tool] | None,
+ structured_output: type[BaseModel] | None = None,
json_mode: bool = False,
) -> types.GenerateContentConfig:
"""
@@ -245,7 +262,7 @@ class ChatGoogle(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
- def _extract_thinking(self, response: Any) -> Optional[str]:
+ def _extract_thinking(self, response: Any) -> str | None:
"""
Extract thinking/reasoning content from the response parts.
"""
@@ -465,7 +482,7 @@ class ChatGoogle(BaseChatLLM):
text_started = True
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_START)
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=text_content)
-
+
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
if text_started:
@@ -541,7 +558,7 @@ class ChatGoogle(BaseChatLLM):
text_started = True
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_START)
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=text_content)
-
+
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
if text_started:
diff --git a/windows_use/providers/google/stt.py b/windows_use/providers/google/stt.py
index 6316aa4..33a097c 100644
--- a/windows_use/providers/google/stt.py
+++ b/windows_use/providers/google/stt.py
@@ -1,6 +1,5 @@
-import os
import logging
-from typing import Optional
+import os
from google import genai
from google.genai import types
@@ -42,9 +41,9 @@ class STTGoogle(BaseSTT):
def __init__(
self,
model: str = "gemini-2.5-flash",
- api_key: Optional[str] = None,
+ api_key: str | None = None,
prompt: str = "Transcribe this audio clip word for word. Return only the transcription, no extra commentary.",
- language: Optional[str] = None,
+ language: str | None = None,
):
self._model = model
self.api_key = (
diff --git a/windows_use/providers/google/tts.py b/windows_use/providers/google/tts.py
index 9399c18..c632cd5 100644
--- a/windows_use/providers/google/tts.py
+++ b/windows_use/providers/google/tts.py
@@ -1,7 +1,6 @@
+import logging
import os
import wave
-import logging
-from typing import Optional
from google import genai
from google.genai import types
@@ -66,7 +65,7 @@ class TTSGoogle(BaseTTS):
self,
model: str = "gemini-2.5-flash-preview-tts",
voice: str = "Kore",
- api_key: Optional[str] = None,
+ api_key: str | None = None,
sample_rate: int = 24000,
):
self._model = model
diff --git a/windows_use/providers/groq/__init__.py b/windows_use/providers/groq/__init__.py
index 84f1018..c8378e7 100644
--- a/windows_use/providers/groq/__init__.py
+++ b/windows_use/providers/groq/__init__.py
@@ -1,3 +1,3 @@
-from windows_use.providers.groq.llm import ChatGroq
-from windows_use.providers.groq.stt import STTGroq
-from windows_use.providers.groq.tts import TTSGroq
+from windows_use.providers.groq.llm import ChatGroq as ChatGroq
+from windows_use.providers.groq.stt import STTGroq as STTGroq
+from windows_use.providers.groq.tts import TTSGroq as TTSGroq
diff --git a/windows_use/providers/groq/llm.py b/windows_use/providers/groq/llm.py
index ac4b33b..0a2b871 100644
--- a/windows_use/providers/groq/llm.py
+++ b/windows_use/providers/groq/llm.py
@@ -1,35 +1,52 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, Union, overload
-from groq import Groq, AsyncGroq
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
+from groq import AsyncGroq, Groq
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
class ChatGroq(BaseChatLLM):
"""
Groq LLM implementation following the BaseChatLLM protocol.
-
+
Groq provides ultra-fast inference for open-source models like:
- Llama 3.3 70B
- Mixtral
- Gemma 2
"""
-
+
def __init__(
self,
model: str = "llama-3.3-70b-versatile",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
timeout: float = 60.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
**kwargs
):
"""
@@ -47,7 +64,7 @@ class ChatGroq(BaseChatLLM):
self._model = model
self.api_key = api_key or os.environ.get("GROQ_API_KEY")
self.temperature = temperature
-
+
self.client = Groq(
api_key=self.api_key,
base_url=base_url,
@@ -77,7 +94,7 @@ class ChatGroq(BaseChatLLM):
p in m for p in ("gpt-oss", "qwen3-32b", "qwen/qwen3")
)
- def _convert_messages(self, messages: List[BaseMessage]) -> List[dict]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
Convert BaseMessage objects to Groq-compatible message dictionaries.
"""
@@ -92,7 +109,7 @@ class ChatGroq(BaseChatLLM):
content_list = []
if msg.content:
content_list.append({"type": "text", "text": msg.content})
-
+
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
content_list.append({
@@ -127,7 +144,7 @@ class ChatGroq(BaseChatLLM):
})
return groq_messages
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Groq-compatible tool definitions.
"""
@@ -188,13 +205,13 @@ class ChatGroq(BaseChatLLM):
def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
groq_messages = self._convert_messages(messages)
groq_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": groq_messages,
**self.kwargs
}
-
+
# Only add tools if they exist
if groq_tools:
params["tools"] = groq_tools
@@ -203,19 +220,19 @@ class ChatGroq(BaseChatLLM):
params["reasoning_format"] = "parsed"
else:
params["include_reasoning"] = True
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
# Handle structured output and json_mode
if structured_output:
# Groq doesn't have beta.parse, so use json_mode and manual parsing
params["response_format"] = {"type": "json_object"}
elif json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
-
+
if structured_output:
try:
# Parse the JSON response into the structured output
@@ -225,7 +242,7 @@ class ChatGroq(BaseChatLLM):
else:
# Fallback to empty object if no content
parsed = structured_output()
-
+
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
thinking_tokens = None
if response.usage and hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
@@ -254,13 +271,13 @@ class ChatGroq(BaseChatLLM):
async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
groq_messages = self._convert_messages(messages)
groq_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": groq_messages,
**self.kwargs
}
-
+
if groq_tools:
params["tools"] = groq_tools
if self._is_reasoning_model():
@@ -268,17 +285,17 @@ class ChatGroq(BaseChatLLM):
params["reasoning_format"] = "parsed"
else:
params["include_reasoning"] = True
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if structured_output:
params["response_format"] = {"type": "json_object"}
elif json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
-
+
if structured_output:
try:
content_text = response.choices[0].message.content
@@ -286,7 +303,7 @@ class ChatGroq(BaseChatLLM):
parsed = structured_output.model_validate_json(content_text)
else:
parsed = structured_output()
-
+
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
thinking_tokens = None
if response.usage and hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
@@ -314,14 +331,14 @@ class ChatGroq(BaseChatLLM):
def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
groq_messages = self._convert_messages(messages)
groq_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": groq_messages,
"stream": True,
**self.kwargs
}
-
+
if groq_tools:
params["tools"] = groq_tools
if self._is_reasoning_model():
@@ -329,21 +346,21 @@ class ChatGroq(BaseChatLLM):
params["reasoning_format"] = "parsed"
else:
params["include_reasoning"] = True
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -366,7 +383,7 @@ class ChatGroq(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
reasoning_delta = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
@@ -401,7 +418,7 @@ class ChatGroq(BaseChatLLM):
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -424,14 +441,14 @@ class ChatGroq(BaseChatLLM):
async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
groq_messages = self._convert_messages(messages)
groq_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": groq_messages,
"stream": True,
**self.kwargs
}
-
+
if groq_tools:
params["tools"] = groq_tools
if self._is_reasoning_model():
@@ -439,21 +456,21 @@ class ChatGroq(BaseChatLLM):
params["reasoning_format"] = "parsed"
else:
params["include_reasoning"] = True
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -476,9 +493,9 @@ class ChatGroq(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
-
+
reasoning_delta = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
if reasoning_delta:
if not think_started:
@@ -511,7 +528,7 @@ class ChatGroq(BaseChatLLM):
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -530,14 +547,14 @@ class ChatGroq(BaseChatLLM):
def get_metadata(self) -> Metadata:
# Context windows vary by model
context_window = 128000 # Default
-
+
if "llama-3.3" in self._model or "llama-3.1" in self._model:
context_window = 128000
elif "mixtral" in self._model:
context_window = 32768
elif "gemma-2" in self._model:
context_window = 8192
-
+
return Metadata(
name=self._model,
context_window=context_window,
diff --git a/windows_use/providers/groq/stt.py b/windows_use/providers/groq/stt.py
index 78b6406..387d45a 100644
--- a/windows_use/providers/groq/stt.py
+++ b/windows_use/providers/groq/stt.py
@@ -1,8 +1,7 @@
-import os
import logging
-from typing import Optional
+import os
-from groq import Groq, AsyncGroq
+from groq import AsyncGroq, Groq
from windows_use.providers.base import BaseSTT
@@ -41,8 +40,8 @@ class STTGroq(BaseSTT):
def __init__(
self,
model: str = "whisper-large-v3-turbo",
- api_key: Optional[str] = None,
- language: Optional[str] = None,
+ api_key: str | None = None,
+ language: str | None = None,
temperature: float = 0.0,
timeout: float = 120.0,
):
diff --git a/windows_use/providers/groq/tts.py b/windows_use/providers/groq/tts.py
index 1a8e625..7a55dff 100644
--- a/windows_use/providers/groq/tts.py
+++ b/windows_use/providers/groq/tts.py
@@ -1,8 +1,7 @@
-import os
import logging
-from typing import Optional
+import os
-from groq import Groq, AsyncGroq
+from groq import AsyncGroq, Groq
from windows_use.providers.base import BaseTTS
@@ -50,7 +49,7 @@ class TTSGroq(BaseTTS):
self,
model: str = "canopylabs/orpheus-v1-english",
voice: str = "troy",
- api_key: Optional[str] = None,
+ api_key: str | None = None,
speed: float = 1.0,
response_format: str = "wav",
timeout: float = 120.0,
diff --git a/windows_use/providers/litellm/llm.py b/windows_use/providers/litellm/llm.py
index 3bef4a5..c57fe2a 100644
--- a/windows_use/providers/litellm/llm.py
+++ b/windows_use/providers/litellm/llm.py
@@ -1,14 +1,30 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, overload
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
import litellm
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -33,11 +49,11 @@ class ChatLiteLLM(BaseChatLLM):
def __init__(
self,
model: str,
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
timeout: float = 600.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
drop_params: bool = True,
**kwargs,
):
@@ -75,7 +91,7 @@ class ChatLiteLLM(BaseChatLLM):
def provider(self) -> str:
return "litellm"
- def _convert_messages(self, messages: List[BaseMessage]) -> List[dict]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
Convert BaseMessage objects to OpenAI-compatible message dictionaries.
LiteLLM uses the OpenAI message format for all providers.
@@ -140,7 +156,7 @@ class ChatLiteLLM(BaseChatLLM):
})
return converted
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to OpenAI-compatible tool definitions.
"""
@@ -154,8 +170,8 @@ class ChatLiteLLM(BaseChatLLM):
def _build_params(
self,
- messages: List[dict],
- tools: Optional[List[dict]] = None,
+ messages: list[dict],
+ tools: list[dict] | None = None,
stream: bool = False,
json_mode: bool = False,
) -> dict:
@@ -414,7 +430,7 @@ class ChatLiteLLM(BaseChatLLM):
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -503,7 +519,7 @@ class ChatLiteLLM(BaseChatLLM):
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
diff --git a/windows_use/providers/mistral/__init__.py b/windows_use/providers/mistral/__init__.py
index 47f1989..826269a 100644
--- a/windows_use/providers/mistral/__init__.py
+++ b/windows_use/providers/mistral/__init__.py
@@ -1 +1 @@
-from windows_use.providers.mistral.llm import ChatMistral
+from windows_use.providers.mistral.llm import ChatMistral as ChatMistral
diff --git a/windows_use/providers/mistral/llm.py b/windows_use/providers/mistral/llm.py
index 41314fe..bc2c115 100644
--- a/windows_use/providers/mistral/llm.py
+++ b/windows_use/providers/mistral/llm.py
@@ -1,15 +1,31 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, Union, overload
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
from mistralai import Mistral
-from mistralai.models import AssistantMessage, UserMessage, SystemMessage as MistralSystemMessage, ToolMessage as MistralToolMessage
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -25,21 +41,21 @@ def _mistral_tool_call_id(s: str) -> str:
class ChatMistral(BaseChatLLM):
"""
Mistral AI LLM implementation following the BaseChatLLM protocol.
-
+
Supports Mistral models including:
- Mistral Large
- Mistral Medium
- Mistral Small
- Codestral
"""
-
+
def __init__(
self,
model: str = "mistral-large-latest",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
- timeout: Optional[int] = None,
- temperature: Optional[float] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ timeout: int | None = None,
+ temperature: float | None = None,
**kwargs
):
"""
@@ -67,7 +83,7 @@ class ChatMistral(BaseChatLLM):
def provider(self) -> str:
return "mistral"
- def _convert_messages(self, messages: List[BaseMessage]) -> List[Any]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[Any]:
"""
Convert BaseMessage objects to Mistral-compatible message objects.
"""
@@ -81,7 +97,7 @@ class ChatMistral(BaseChatLLM):
content = []
if msg.content:
content.append({"type": "text", "text": msg.content})
-
+
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
content.append({
@@ -122,7 +138,7 @@ class ChatMistral(BaseChatLLM):
})
return mistral_messages
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Mistral-compatible tool definitions.
"""
@@ -252,25 +268,25 @@ class ChatMistral(BaseChatLLM):
def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
mistral_messages = self._convert_messages(messages)
mistral_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": mistral_messages,
**self.kwargs
}
-
+
# Only add tools if they exist
if mistral_tools:
params["tools"] = mistral_tools
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if structured_output or json_mode:
params["response_format"] = {"type": "json_object"}
response = self.client.chat.complete(**params)
-
+
if structured_output:
try:
# Parse JSON response into structured output
@@ -308,24 +324,24 @@ class ChatMistral(BaseChatLLM):
async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
mistral_messages = self._convert_messages(messages)
mistral_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": mistral_messages,
**self.kwargs
}
-
+
if mistral_tools:
params["tools"] = mistral_tools
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if structured_output or json_mode:
params["response_format"] = {"type": "json_object"}
response = await self.client.chat.complete_async(**params)
-
+
if structured_output:
try:
content_text, _ = self._extract_content(response.choices[0].message.content)
@@ -361,30 +377,30 @@ class ChatMistral(BaseChatLLM):
def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
mistral_messages = self._convert_messages(messages)
mistral_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": mistral_messages,
**self.kwargs
}
-
+
if mistral_tools:
params["tools"] = mistral_tools
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.stream(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -417,7 +433,7 @@ class ChatMistral(BaseChatLLM):
tool_call_name = tc_delta.function.name
if tc_delta.function.arguments:
tool_call_args += tc_delta.function.arguments
-
+
# Track usage
if hasattr(chunk, 'data') and hasattr(chunk.data, 'usage') and chunk.data.usage:
usage_data = chunk.data.usage
@@ -434,14 +450,14 @@ class ChatMistral(BaseChatLLM):
total_tokens=usage_data.total_tokens,
thinking_tokens=thinking_tokens,
)
-
+
# Yield accumulated tool call as final response
if tool_call_id and tool_call_name:
try:
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -464,30 +480,30 @@ class ChatMistral(BaseChatLLM):
async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
mistral_messages = self._convert_messages(messages)
mistral_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": mistral_messages,
**self.kwargs
}
-
+
if mistral_tools:
params["tools"] = mistral_tools
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.client.chat.stream_async(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -520,7 +536,7 @@ class ChatMistral(BaseChatLLM):
tool_call_name = tc_delta.function.name
if tc_delta.function.arguments:
tool_call_args += tc_delta.function.arguments
-
+
# Track usage
if hasattr(chunk, 'data') and hasattr(chunk.data, 'usage') and chunk.data.usage:
usage_data = chunk.data.usage
@@ -537,14 +553,14 @@ class ChatMistral(BaseChatLLM):
total_tokens=usage_data.total_tokens,
thinking_tokens=thinking_tokens,
)
-
+
# Yield accumulated tool call as final response
if tool_call_id and tool_call_name:
try:
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -562,7 +578,7 @@ class ChatMistral(BaseChatLLM):
def get_metadata(self) -> Metadata:
# Context windows vary by model
context_window = 128000 # Default
-
+
if "large" in self._model:
context_window = 128000
elif "medium" in self._model:
@@ -571,7 +587,7 @@ class ChatMistral(BaseChatLLM):
context_window = 32000
elif "codestral" in self._model:
context_window = 32000
-
+
return Metadata(
name=self._model,
context_window=context_window,
diff --git a/windows_use/providers/nvidia/llm.py b/windows_use/providers/nvidia/llm.py
index c6e0b81..d7cbc63 100644
--- a/windows_use/providers/nvidia/llm.py
+++ b/windows_use/providers/nvidia/llm.py
@@ -1,7 +1,6 @@
"""NVIDIA NIM LLM provider via OpenAI-compatible API."""
import os
-from typing import Optional
from windows_use.providers.openai.llm import ChatOpenAI
@@ -19,11 +18,11 @@ class ChatNvidia(ChatOpenAI):
def __init__(
self,
model: str = "qwen/qwen3.5-122b-a10b",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
timeout: float = 600.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
**kwargs,
):
api_key = api_key or os.environ.get("NVIDIA_NIM_API_KEY") or os.environ.get("NVIDIA_API_KEY")
diff --git a/windows_use/providers/ollama/__init__.py b/windows_use/providers/ollama/__init__.py
index 8d25999..730ba61 100644
--- a/windows_use/providers/ollama/__init__.py
+++ b/windows_use/providers/ollama/__init__.py
@@ -1 +1 @@
-from windows_use.providers.ollama.llm import ChatOllama
+from windows_use.providers.ollama.llm import ChatOllama as ChatOllama
diff --git a/windows_use/providers/ollama/llm.py b/windows_use/providers/ollama/llm.py
index a578e3e..e05033e 100644
--- a/windows_use/providers/ollama/llm.py
+++ b/windows_use/providers/ollama/llm.py
@@ -1,16 +1,32 @@
-import os
import json
-import uuid
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, overload
-import ollama
-from ollama import Client, AsyncClient
+import os
+import uuid
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
+from ollama import AsyncClient, Client
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -18,13 +34,13 @@ class ChatOllama(BaseChatLLM):
"""
Ollama LLM implementation following the BaseChatLLM protocol.
"""
-
+
def __init__(
self,
model: str = "llama3.1",
- host: Optional[str] = None,
+ host: str | None = None,
timeout: float = 600.0,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
**kwargs
):
"""
@@ -40,7 +56,7 @@ class ChatOllama(BaseChatLLM):
self._model = model
self.host = host or os.environ.get("OLLAMA_HOST", "http://localhost:11434")
self.temperature = temperature
-
+
self.client = Client(host=self.host, timeout=timeout)
self.aclient = AsyncClient(host=self.host, timeout=timeout)
self.kwargs = kwargs
@@ -61,7 +77,7 @@ class ChatOllama(BaseChatLLM):
for p in ("qwen3", "deepseek-r1", "deepseek-v3", "gpt-oss")
)
- def _convert_messages(self, messages: List[BaseMessage]) -> List[dict]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
Convert BaseMessage objects to Ollama-compatible message dictionaries.
"""
@@ -102,7 +118,7 @@ class ChatOllama(BaseChatLLM):
})
return ollama_messages
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Ollama-compatible tool definitions.
"""
@@ -159,28 +175,28 @@ class ChatOllama(BaseChatLLM):
def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
ollama_messages = self._convert_messages(messages)
ollama_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": ollama_messages,
**self.kwargs
}
-
+
if ollama_tools:
params["tools"] = ollama_tools
if self._is_thinking_model():
params["think"] = True
-
+
if self.temperature is not None:
if "options" not in params:
params["options"] = {}
params["options"]["temperature"] = self.temperature
-
+
if json_mode or structured_output:
params["format"] = "json" if not structured_output else structured_output.model_json_schema()
response = self.client.chat(**params)
-
+
if structured_output:
try:
parsed = structured_output.model_validate_json(response["message"]["content"])
@@ -205,28 +221,28 @@ class ChatOllama(BaseChatLLM):
async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
ollama_messages = self._convert_messages(messages)
ollama_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": ollama_messages,
**self.kwargs
}
-
+
if ollama_tools:
params["tools"] = ollama_tools
if self._is_thinking_model():
params["think"] = True
-
+
if self.temperature is not None:
if "options" not in params:
params["options"] = {}
params["options"]["temperature"] = self.temperature
-
+
if json_mode or structured_output:
params["format"] = "json" if not structured_output else structured_output.model_json_schema()
response = await self.aclient.chat(**params)
-
+
if structured_output:
try:
parsed = structured_output.model_validate_json(response["message"]["content"])
@@ -250,29 +266,29 @@ class ChatOllama(BaseChatLLM):
def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
ollama_messages = self._convert_messages(messages)
ollama_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": ollama_messages,
"stream": True,
**self.kwargs
}
-
+
if ollama_tools:
params["tools"] = ollama_tools
if self._is_thinking_model():
params["think"] = True
-
+
if self.temperature is not None:
if "options" not in params:
params["options"] = {}
params["options"]["temperature"] = self.temperature
-
+
if json_mode:
params["format"] = "json"
response = self.client.chat(**params)
-
+
text_started = False
think_started = False
usage = None
@@ -336,29 +352,29 @@ class ChatOllama(BaseChatLLM):
async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
ollama_messages = self._convert_messages(messages)
ollama_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": ollama_messages,
"stream": True,
**self.kwargs
}
-
+
if ollama_tools:
params["tools"] = ollama_tools
if self._is_thinking_model():
params["think"] = True
-
+
if self.temperature is not None:
if "options" not in params:
params["options"] = {}
params["options"]["temperature"] = self.temperature
-
+
if json_mode:
params["format"] = "json"
response = await self.aclient.chat(**params)
-
+
text_started = False
think_started = False
usage = None
@@ -409,7 +425,7 @@ class ChatOllama(BaseChatLLM):
),
usage=usage
)
-
+
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
if text_started:
diff --git a/windows_use/providers/open_router/llm.py b/windows_use/providers/open_router/llm.py
index b41971b..c698e25 100644
--- a/windows_use/providers/open_router/llm.py
+++ b/windows_use/providers/open_router/llm.py
@@ -1,14 +1,31 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, Union, overload
-from openai import OpenAI, AsyncOpenAI
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
+from openai import AsyncOpenAI, OpenAI
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -16,19 +33,19 @@ class ChatOpenRouter(BaseChatLLM):
"""
OpenRouter LLM implementation following the BaseChatLLM protocol.
Uses OpenAI SDK with OpenRouter base URL.
-
+
OpenRouter provides access to multiple LLM providers through a unified API.
"""
-
+
def __init__(
self,
model: str,
- api_key: Optional[str] = None,
+ api_key: str | None = None,
base_url: str = "https://openrouter.ai/api/v1",
timeout: float = 600.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
- default_headers: Optional[dict] = None,
+ temperature: float | None = None,
+ default_headers: dict | None = None,
**kwargs
):
"""
@@ -46,10 +63,10 @@ class ChatOpenRouter(BaseChatLLM):
self._model = model
self.api_key = api_key or os.environ.get("OPENROUTER_API_KEY")
self.temperature = temperature
-
+
# Build headers
headers = default_headers or {}
-
+
self.client = OpenAI(
api_key=self.api_key,
base_url=base_url,
@@ -74,7 +91,7 @@ class ChatOpenRouter(BaseChatLLM):
def provider(self) -> str:
return "open_router"
- def _convert_messages(self, messages: List[BaseMessage]) -> List[dict]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
Convert BaseMessage objects to OpenRouter-compatible message dictionaries.
"""
@@ -88,7 +105,7 @@ class ChatOpenRouter(BaseChatLLM):
content_list = []
if msg.content:
content_list.append({"type": "text", "text": msg.content})
-
+
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
content_list.append({
@@ -123,7 +140,7 @@ class ChatOpenRouter(BaseChatLLM):
})
return openai_messages
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to OpenRouter-compatible tool definitions.
"""
@@ -186,37 +203,37 @@ class ChatOpenRouter(BaseChatLLM):
def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": openai_messages,
**self.kwargs
}
-
+
# Only add tools if they exist
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
# Note: OpenRouter doesn't support structured_output via beta.parse
if structured_output:
logger.warning("OpenRouter does not support structured_output via beta.parse. Using json_mode instead.")
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
-
+
if structured_output:
# Try to parse the JSON response into the structured output
try:
content_text = response.choices[0].message.content
parsed_data = json.loads(content_text)
parsed_obj = structured_output(**parsed_data)
-
+
thinking_tokens = getattr(
getattr(response.usage, "completion_tokens_details", None),
"reasoning_tokens",
@@ -237,7 +254,7 @@ class ChatOpenRouter(BaseChatLLM):
except (json.JSONDecodeError, TypeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
# Fall through to normal response processing
-
+
return self._process_response(response)
@overload
@@ -247,34 +264,34 @@ class ChatOpenRouter(BaseChatLLM):
async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": openai_messages,
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
if structured_output:
logger.warning("OpenRouter does not support structured_output via beta.parse. Using json_mode instead.")
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
-
+
if structured_output:
try:
content_text = response.choices[0].message.content
parsed_data = json.loads(content_text)
parsed_obj = structured_output(**parsed_data)
-
+
thinking_tokens = getattr(
getattr(response.usage, "completion_tokens_details", None),
"reasoning_tokens",
@@ -294,7 +311,7 @@ class ChatOpenRouter(BaseChatLLM):
return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
except (json.JSONDecodeError, TypeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
-
+
return self._process_response(response)
@overload
@@ -304,7 +321,7 @@ class ChatOpenRouter(BaseChatLLM):
def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": openai_messages,
@@ -312,24 +329,24 @@ class ChatOpenRouter(BaseChatLLM):
"stream_options": {"include_usage": True},
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -352,9 +369,9 @@ class ChatOpenRouter(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
-
+
if hasattr(delta, "reasoning_content") and delta.reasoning_content:
if not think_started:
think_started = True
@@ -368,7 +385,7 @@ class ChatOpenRouter(BaseChatLLM):
text_started = True
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_START)
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
-
+
# Accumulate tool call deltas
if hasattr(delta, 'tool_calls') and delta.tool_calls:
tc_delta = delta.tool_calls[0]
@@ -379,14 +396,14 @@ class ChatOpenRouter(BaseChatLLM):
tool_call_name = tc_delta.function.name
if tc_delta.function.arguments:
tool_call_args += tc_delta.function.arguments
-
+
# Yield accumulated tool call as final response
if tool_call_id and tool_call_name:
try:
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -409,7 +426,7 @@ class ChatOpenRouter(BaseChatLLM):
async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": openai_messages,
@@ -417,24 +434,24 @@ class ChatOpenRouter(BaseChatLLM):
"stream_options": {"include_usage": True},
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None:
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -457,7 +474,7 @@ class ChatOpenRouter(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
if hasattr(delta, "reasoning_content") and delta.reasoning_content:
@@ -473,7 +490,7 @@ class ChatOpenRouter(BaseChatLLM):
text_started = True
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_START)
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
-
+
# Accumulate tool call deltas
if hasattr(delta, 'tool_calls') and delta.tool_calls:
tc_delta = delta.tool_calls[0]
@@ -484,14 +501,14 @@ class ChatOpenRouter(BaseChatLLM):
tool_call_name = tc_delta.function.name
if tc_delta.function.arguments:
tool_call_args += tc_delta.function.arguments
-
+
# Yield accumulated tool call as final response
if tool_call_id and tool_call_name:
try:
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
diff --git a/windows_use/providers/openai/llm.py b/windows_use/providers/openai/llm.py
index 711f4df..a4ffd94 100644
--- a/windows_use/providers/openai/llm.py
+++ b/windows_use/providers/openai/llm.py
@@ -1,21 +1,38 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, Union, overload
-from openai import OpenAI, AsyncOpenAI
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
+from openai import AsyncOpenAI, OpenAI
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
class ChatOpenAI(BaseChatLLM):
"""
OpenAI LLM implementation following the BaseChatLLM protocol.
-
+
Supports:
- Standard chat completions
- Tool/function calling
@@ -24,15 +41,15 @@ class ChatOpenAI(BaseChatLLM):
- Vision (image inputs)
- Reasoning models (o1-preview, o1-mini)
"""
-
+
def __init__(
self,
model: str = "gpt-4o",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
timeout: float = 600.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
**kwargs
):
"""
@@ -51,7 +68,7 @@ class ChatOpenAI(BaseChatLLM):
self.api_key = api_key or os.environ.get("OPENAI_API_KEY")
self.base_url = base_url or os.environ.get("OPENAI_BASE_URL")
self.temperature = temperature
-
+
self.client = OpenAI(
api_key=self.api_key,
base_url=self.base_url,
@@ -73,12 +90,12 @@ class ChatOpenAI(BaseChatLLM):
@property
def provider(self) -> str:
return "openai"
-
+
def _is_reasoning_model(self) -> bool:
"""Check if the model is a reasoning model (o-series: o1, o3, o4, etc.)."""
return self._model.startswith(("o1", "o3", "o4"))
- def _convert_messages(self, messages: List[BaseMessage]) -> List[dict]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
Convert BaseMessage objects to OpenAI-compatible message dictionaries.
"""
@@ -92,7 +109,7 @@ class ChatOpenAI(BaseChatLLM):
content_list = []
if msg.content:
content_list.append({"type": "text", "text": msg.content})
-
+
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
content_list.append({
@@ -131,7 +148,7 @@ class ChatOpenAI(BaseChatLLM):
})
return openai_messages
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to OpenAI-compatible tool definitions.
"""
@@ -203,21 +220,21 @@ class ChatOpenAI(BaseChatLLM):
def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": openai_messages,
**self.kwargs
}
-
+
# Only add tools if they exist
if openai_tools:
params["tools"] = openai_tools
-
+
# Temperature handling - o1 models don't support temperature
if self.temperature is not None and not self._is_reasoning_model():
params["temperature"] = self.temperature
-
+
if structured_output:
# Use beta parse endpoint for structured outputs
response = self.client.beta.chat.completions.parse(
@@ -233,7 +250,7 @@ class ChatOpenAI(BaseChatLLM):
response.usage.completion_tokens_details, "thinking_tokens", None
)
- usage = TokenUsage(
+ TokenUsage(
prompt_tokens=response.usage.prompt_tokens,
completion_tokens=response.usage.completion_tokens,
total_tokens=response.usage.total_tokens,
@@ -245,7 +262,7 @@ class ChatOpenAI(BaseChatLLM):
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = self.client.chat.completions.create(**params)
return self._process_response(response)
@@ -256,19 +273,19 @@ class ChatOpenAI(BaseChatLLM):
async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": openai_messages,
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None and not self._is_reasoning_model():
params["temperature"] = self.temperature
-
+
if structured_output:
response = await self.aclient.beta.chat.completions.parse(
**params,
@@ -295,7 +312,7 @@ class ChatOpenAI(BaseChatLLM):
if json_mode:
params["response_format"] = {"type": "json_object"}
-
+
response = await self.aclient.chat.completions.create(**params)
return self._process_response(response)
@@ -306,7 +323,7 @@ class ChatOpenAI(BaseChatLLM):
def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": openai_messages,
@@ -314,28 +331,28 @@ class ChatOpenAI(BaseChatLLM):
"stream_options": {"include_usage": True},
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None and not self._is_reasoning_model():
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
response = self.client.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
usage = None
-
+
for chunk in response:
if not chunk.choices:
# Final chunk with usage
@@ -355,9 +372,9 @@ class ChatOpenAI(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
-
+
if self._is_reasoning_model() and hasattr(delta, "reasoning_content") and delta.reasoning_content:
if not think_started:
think_started = True
@@ -378,7 +395,7 @@ class ChatOpenAI(BaseChatLLM):
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
-
+
if tc_delta.function:
if tc_delta.function.name:
tool_call_name = tc_delta.function.name
@@ -389,14 +406,14 @@ class ChatOpenAI(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
if text_started:
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
-
+
# Yield accumulated tool call as final response
if tool_call_id and tool_call_name:
try:
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -414,7 +431,7 @@ class ChatOpenAI(BaseChatLLM):
async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
-
+
params = {
"model": self._model,
"messages": openai_messages,
@@ -422,27 +439,27 @@ class ChatOpenAI(BaseChatLLM):
"stream_options": {"include_usage": True},
**self.kwargs
}
-
+
if openai_tools:
params["tools"] = openai_tools
-
+
if self.temperature is not None and not self._is_reasoning_model():
params["temperature"] = self.temperature
-
+
if json_mode:
params["response_format"] = {"type": "json_object"}
response = await self.aclient.chat.completions.create(**params)
-
+
# Accumulators for streamed tool calls
tool_call_id = None
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
-
+
async for chunk in response:
if not chunk.choices:
# Final chunk with usage
@@ -462,9 +479,9 @@ class ChatOpenAI(BaseChatLLM):
thinking_tokens=thinking_tokens,
)
continue
-
+
delta = chunk.choices[0].delta
-
+
if self._is_reasoning_model() and hasattr(delta, "reasoning_content") and delta.reasoning_content:
if not think_started:
think_started = True
@@ -485,7 +502,7 @@ class ChatOpenAI(BaseChatLLM):
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
-
+
if tc_delta.function:
if tc_delta.function.name:
tool_call_name = tc_delta.function.name
@@ -496,14 +513,14 @@ class ChatOpenAI(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
if text_started:
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
-
+
# Yield accumulated tool call as final response
if tool_call_id and tool_call_name:
try:
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -517,7 +534,7 @@ class ChatOpenAI(BaseChatLLM):
def get_metadata(self) -> Metadata:
# Determine context window based on model
context_window = 128000 # Default for GPT-4o and newer models
-
+
if self._model.startswith("gpt-4-turbo"):
context_window = 128000
elif self._model.startswith("gpt-4"):
@@ -526,7 +543,7 @@ class ChatOpenAI(BaseChatLLM):
context_window = 16385
elif self._model.startswith("o1"):
context_window = 200000 # o1 models have larger context
-
+
return Metadata(
name=self._model,
context_window=context_window,
diff --git a/windows_use/providers/openai/stt.py b/windows_use/providers/openai/stt.py
index 1f629f0..9793dbf 100644
--- a/windows_use/providers/openai/stt.py
+++ b/windows_use/providers/openai/stt.py
@@ -1,8 +1,7 @@
-import os
import logging
-from typing import Optional
+import os
-from openai import OpenAI, AsyncOpenAI
+from openai import AsyncOpenAI, OpenAI
from windows_use.providers.base import BaseSTT
@@ -36,9 +35,9 @@ class STTOpenAI(BaseSTT):
def __init__(
self,
model: str = "whisper-1",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
- language: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ language: str | None = None,
temperature: float = 0.0,
timeout: float = 120.0,
):
diff --git a/windows_use/providers/openai/tts.py b/windows_use/providers/openai/tts.py
index abfa8bd..057d9a0 100644
--- a/windows_use/providers/openai/tts.py
+++ b/windows_use/providers/openai/tts.py
@@ -1,8 +1,7 @@
-import os
import logging
-from typing import Optional
+import os
-from openai import OpenAI, AsyncOpenAI
+from openai import AsyncOpenAI, OpenAI
from windows_use.providers.base import BaseTTS
@@ -42,8 +41,8 @@ class TTSOpenAI(BaseTTS):
self,
model: str = "tts-1",
voice: str = "alloy",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
speed: float = 1.0,
response_format: str = "wav",
timeout: float = 120.0,
diff --git a/windows_use/providers/perplexity/llm.py b/windows_use/providers/perplexity/llm.py
index 1012f83..36c6221 100644
--- a/windows_use/providers/perplexity/llm.py
+++ b/windows_use/providers/perplexity/llm.py
@@ -1,17 +1,30 @@
-import os
import json
import logging
-from typing import Optional, Any, List, Iterator, AsyncIterator
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any
import httpx
from pydantic import BaseModel
-from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
-from windows_use.tools import Tool
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ ToolCall,
+)
from windows_use.providers.perplexity.view import get_model_info
+from windows_use.providers.views import Metadata, TokenUsage
+from windows_use.tools import Tool
logger = logging.getLogger(__name__)
@@ -30,7 +43,7 @@ class ChatPerplexity:
def __init__(
self,
model: str = "sonar-pro",
- api_key: Optional[str] = None,
+ api_key: str | None = None,
base_url: str = "https://api.perplexity.ai",
timeout: float = 600.0,
temperature: float = 0.5,
@@ -63,7 +76,7 @@ class ChatPerplexity:
# ── Message conversion ──────────────────────────────────────────
- def _convert_messages(self, messages: list[BaseMessage]) -> tuple[Optional[str], list[dict]]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> tuple[str | None, list[dict]]:
"""Convert internal messages to Perplexity Agent API format.
Returns (instructions, input_messages).
@@ -121,7 +134,7 @@ class ChatPerplexity:
# ── Tool conversion ─────────────────────────────────────────────
- def _convert_tools(self, tools: List[Tool]) -> list[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""Convert Tool objects to Perplexity Agent API (Responses API) format.
Responses API uses a flat structure (no `function` wrapper):
diff --git a/windows_use/providers/views.py b/windows_use/providers/views.py
index bb722d4..35beac7 100644
--- a/windows_use/providers/views.py
+++ b/windows_use/providers/views.py
@@ -1,17 +1,17 @@
-from typing import Optional
+
from pydantic import BaseModel
class TokenUsage(BaseModel):
"""Token usage information from LLM responses."""
- prompt_tokens: Optional[int] = 0
- completion_tokens: Optional[int] = 0
- total_tokens: Optional[int] = 0
- image_tokens: Optional[int] = 0
- thinking_tokens: Optional[int] = 0
- cache_creation_input_tokens: Optional[int] = 0
- cache_read_input_tokens: Optional[int] = 0
+ prompt_tokens: int | None = 0
+ completion_tokens: int | None = 0
+ total_tokens: int | None = 0
+ image_tokens: int | None = 0
+ thinking_tokens: int | None = 0
+ cache_creation_input_tokens: int | None = 0
+ cache_read_input_tokens: int | None = 0
class Metadata(BaseModel):
diff --git a/windows_use/providers/vllm/llm.py b/windows_use/providers/vllm/llm.py
index cb038c9..ed80765 100644
--- a/windows_use/providers/vllm/llm.py
+++ b/windows_use/providers/vllm/llm.py
@@ -1,14 +1,31 @@
-import os
import json
import logging
-from typing import Iterator, AsyncIterator, List, Optional, Any, overload
-from openai import OpenAI, AsyncOpenAI
+import os
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, overload
+
+from openai import AsyncOpenAI, OpenAI
from pydantic import BaseModel
+
+from windows_use.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ ImageMessage,
+ SystemMessage,
+ ToolMessage,
+)
from windows_use.providers.base import BaseChatLLM
-from windows_use.providers.views import TokenUsage, Metadata
-from windows_use.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage, ImageMessage, ToolMessage
+from windows_use.providers.events import (
+ LLMEvent,
+ LLMEventType,
+ LLMStreamEvent,
+ LLMStreamEventType,
+ Thinking,
+ ToolCall,
+)
+from windows_use.providers.views import Metadata, TokenUsage
from windows_use.tools import Tool
-from windows_use.providers.events import LLMEvent, LLMEventType, LLMStreamEvent, LLMStreamEventType, ToolCall, Thinking
logger = logging.getLogger(__name__)
@@ -34,11 +51,11 @@ class ChatVLLM(BaseChatLLM):
def __init__(
self,
model: str,
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
timeout: float = 600.0,
max_retries: int = 2,
- temperature: Optional[float] = None,
+ temperature: float | None = None,
**kwargs,
):
"""
@@ -82,7 +99,7 @@ class ChatVLLM(BaseChatLLM):
def provider(self) -> str:
return "vllm"
- def _convert_messages(self, messages: List[BaseMessage]) -> List[dict]:
+ def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""Convert BaseMessage objects to OpenAI-compatible message dictionaries."""
openai_messages = []
for msg in messages:
@@ -128,7 +145,7 @@ class ChatVLLM(BaseChatLLM):
})
return openai_messages
- def _convert_tools(self, tools: List[Tool]) -> List[dict]:
+ def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""Convert Tool objects to OpenAI-compatible tool definitions."""
return [
{
@@ -385,7 +402,7 @@ class ChatVLLM(BaseChatLLM):
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -442,7 +459,7 @@ class ChatVLLM(BaseChatLLM):
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -500,7 +517,7 @@ class ChatVLLM(BaseChatLLM):
tool_call_name = None
tool_call_args = ""
usage = None
-
+
text_started = False
think_started = False
@@ -557,7 +574,7 @@ class ChatVLLM(BaseChatLLM):
params = json.loads(tool_call_args)
except json.JSONDecodeError:
params = {}
-
+
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
@@ -585,7 +602,7 @@ class ChatVLLM(BaseChatLLM):
owned_by=owned_by,
)
except Exception:
- logger.debug(f"Could not retrieve model metadata from vLLM server, using defaults")
+ logger.debug("Could not retrieve model metadata from vLLM server, using defaults")
return Metadata(
name=self._model,
context_window=32768,
diff --git a/windows_use/speech/service.py b/windows_use/speech/service.py
index 5fdf062..a4041a5 100644
--- a/windows_use/speech/service.py
+++ b/windows_use/speech/service.py
@@ -1,15 +1,15 @@
"""STT and TTS service implementations for recording, transcription, and playback."""
+import asyncio
+import logging
import os
import wave
-import logging
-import asyncio
-from time import sleep
-from threading import Thread
from tempfile import NamedTemporaryFile
+from threading import Thread
+from time import sleep
from typing import TYPE_CHECKING
-from pyaudio import PyAudio, paInt16, Stream
+from pyaudio import PyAudio, Stream, paInt16
if TYPE_CHECKING:
from windows_use.providers.base import BaseSTT, BaseTTS
diff --git a/windows_use/telemetry/service.py b/windows_use/telemetry/service.py
index 39aded1..ed1ad80 100644
--- a/windows_use/telemetry/service.py
+++ b/windows_use/telemetry/service.py
@@ -1,10 +1,12 @@
-from windows_use.telemetry.views import BaseTelemetryEvent
-from uuid_extensions import uuid7str
+import atexit
+import os
+from pathlib import Path
+
from dotenv import load_dotenv
from posthog import Posthog
-from pathlib import Path
-import os
-import atexit
+from uuid_extensions import uuid7str
+
+from windows_use.telemetry.views import BaseTelemetryEvent
load_dotenv()
@@ -42,31 +44,31 @@ class ProductTelemetry:
def user_id(self):
if self._user_id is not None:
return self._user_id
-
+
import tempfile
temp_dir = Path(os.path.join(tempfile.gettempdir(), '.windows-use'))
temp_dir.mkdir(parents=True, exist_ok=True)
user_id_file = temp_dir / '.windows-use-user-id'
-
+
if user_id_file.exists():
try:
self._user_id = user_id_file.read_text(encoding='utf-8').strip()
except Exception:
pass
-
+
if not self._user_id:
self._user_id = uuid7str()
try:
user_id_file.write_text(self._user_id, encoding='utf-8')
except Exception:
pass
-
+
return self._user_id
def capture(self, event:BaseTelemetryEvent):
client = self.client
if not client:
- return
+ return
try:
client.capture(
distinct_id=self.user_id,
diff --git a/windows_use/telemetry/views.py b/windows_use/telemetry/views.py
index 5f9c314..f946a9f 100644
--- a/windows_use/telemetry/views.py
+++ b/windows_use/telemetry/views.py
@@ -1,7 +1,8 @@
from abc import ABC, abstractmethod
-from dataclasses import dataclass, asdict
+from dataclasses import asdict, dataclass
from typing import Any
+
@dataclass
class BaseTelemetryEvent(ABC):
@property
@@ -12,7 +13,7 @@ class BaseTelemetryEvent(ABC):
@property
def properties(self) -> dict[str,Any]:
return {k: v for k, v in asdict(self).items()}
-
+
@dataclass
class AgentTelemetryEvent(BaseTelemetryEvent):
query: str
@@ -25,4 +26,4 @@ class AgentTelemetryEvent(BaseTelemetryEvent):
error: str | None=None
event_name: str = "agent_event"
is_success:bool=False
-
+
diff --git a/windows_use/tools/__init__.py b/windows_use/tools/__init__.py
index 81466d7..a6e0c1f 100644
--- a/windows_use/tools/__init__.py
+++ b/windows_use/tools/__init__.py
@@ -1,3 +1,3 @@
-from .service import Tool,ToolResult,MAX_TOOL_OUTPUT_LENGTH
+from .service import MAX_TOOL_OUTPUT_LENGTH, Tool, ToolResult
__all__ = ["Tool","ToolResult","MAX_TOOL_OUTPUT_LENGTH"]
diff --git a/windows_use/tools/service.py b/windows_use/tools/service.py
index f1c1c04..cb305b5 100644
--- a/windows_use/tools/service.py
+++ b/windows_use/tools/service.py
@@ -1,9 +1,10 @@
-from pydantic import BaseModel, ValidationError
-from dataclasses import dataclass,field
-from typing import Any
-from abc import ABC
import asyncio
import logging
+from abc import ABC
+from dataclasses import dataclass, field
+from typing import Any
+
+from pydantic import BaseModel, ValidationError
EXCLUDED_PROPERTIES = ["title"]
@@ -21,7 +22,7 @@ class ToolResult:
@classmethod
def success_result(cls,output:str,metadata:dict[str,Any]=None) -> "ToolResult":
return cls(success=True,output=output,metadata=metadata)
-
+
@classmethod
def error_result(cls,error:str,metadata:dict[str,Any]=None) -> "ToolResult":
return cls(success=False,error=error,metadata=metadata)
diff --git a/windows_use/uia/__init__.py b/windows_use/uia/__init__.py
index 169ef2c..83901ef 100644
--- a/windows_use/uia/__init__.py
+++ b/windows_use/uia/__init__.py
@@ -1,5 +1,5 @@
+from .controls import *
+from .core import *
from .enums import *
from .exceptions import *
-from .core import *
from .patterns import *
-from .controls import *
diff --git a/windows_use/uia/controls.py b/windows_use/uia/controls.py
index 487d75a..3ebbed5 100644
--- a/windows_use/uia/controls.py
+++ b/windows_use/uia/controls.py
@@ -11,20 +11,22 @@ uiautomation is shared under the Apache Licene 2.0.
This means that the code can be freely copied and distributed, and costs nothing to use.
'''
+import ctypes
+import datetime
import os
+import re
import sys
import time
-import datetime
-import re
-import ctypes
+from collections.abc import Callable
+from typing import Any, Optional
+
import comtypes
-from typing import (Any, Callable, List, Optional)
-from .enums import *
+
from .core import *
-from .core import _AutomationClient, IUIAutomationElement
+from .core import IUIAutomationElement, _AutomationClient
+from .enums import *
from .patterns import *
-
METRO_WINDOW_CLASS_NAME = 'Windows.UI.Core.CoreWindow' # for Windows 8 and 8.1
SEARCH_INTERVAL = 0.5 # search control interval seconds
MAX_MOVE_SECOND = 1 # simulate mouse move or drag max seconds
@@ -42,19 +44,19 @@ ProcessTime = time.perf_counter # this returns nearly 0 when first call it if p
ProcessTime() # need to call it once if python version <= 3.6
TreeNode = Any
-class Control():
+class Control:
ValidKeys = set(['ControlType', 'ClassName', 'AutomationId', 'Name', 'SubName', 'RegexName', 'Depth', 'Compare'])
def __init__(self, searchFromControl: Optional['Control'] = None, searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL, foundIndex: int = 1, element=None,
- ControlType: Optional[int] = None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ ControlType: int | None = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
"""
searchFromControl: `Control` or its subclass, if it is None, search from root control(Desktop).
@@ -108,12 +110,10 @@ class Control():
self._supportedPatterns = {}
def __str__(self) -> str:
- return 'ControlType: {0} ClassName: {1} AutomationId: {2} Rect: {3} Name: {4} Handle: 0x{5:X}({5})'.format(
- self.ControlTypeName, self.ClassName, self.AutomationId, self.BoundingRectangle, self.Name, self.NativeWindowHandle)
+ return f'ControlType: {self.ControlTypeName} ClassName: {self.ClassName} AutomationId: {self.AutomationId} Rect: {self.BoundingRectangle} Name: {self.Name} Handle: 0x{self.NativeWindowHandle:X}({self.NativeWindowHandle})'
def __repr__(self) -> str:
- return '<{0} ClassName={1!r} AutomationId={2} Rect={3} Name={4!r} Handle=0x{5:X}({5})>'.format(
- self.__class__.__name__, self.ClassName, self.AutomationId, self.BoundingRectangle, self.Name, self.NativeWindowHandle)
+ return f'<{self.__class__.__name__} ClassName={self.ClassName!r} AutomationId={self.AutomationId} Rect={self.BoundingRectangle} Name={self.Name!r} Handle=0x{self.NativeWindowHandle:X}({self.NativeWindowHandle})>'
def __getitem__(self, pos: int) -> Optional['Control']:
if pos == 1:
@@ -151,14 +151,14 @@ class Control():
return None
@staticmethod
- def CreateControlsFromRawElementArray(raw_pointer) -> List['Control']:
+ def CreateControlsFromRawElementArray(raw_pointer) -> list['Control']:
"""
Convert a raw POINTER(IUnknown) to a list of Control subclasses.
-
+
Cached property values like SelectionSelectionProperty return a raw
IUnknown COM pointer (an IUIAutomationElementArray). This method
handles the QueryInterface call and element extraction.
-
+
raw_pointer: POINTER(IUnknown) from GetCachedPropertyValue or GetPropertyValue.
Return List[Control], a list of Control subclasses. Empty list if conversion fails.
"""
@@ -670,7 +670,7 @@ class Control():
"""
try:
handle = self.Element.CurrentNativeWindowHandle
- except comtypes.COMError as ex:
+ except comtypes.COMError:
return 0
return 0 if handle is None else handle
@@ -702,21 +702,21 @@ class Control():
"""
return self.Element.CurrentProviderDescription
- def FindAll(self, scope: int, condition) -> List['Control']:
+ def FindAll(self, scope: int, condition) -> list['Control']:
"""
Find all UI Automation elements that satisfy the specified condition.
Call IUIAutomationElement::FindAll.
-
+
scope: int, a value in class `TreeScope`, specifying the scope of the search.
condition: a condition object from IUIAutomation.CreateTrueCondition() or similar.
Return List[Control], a list of `Control` subclasses that match the condition.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-findall
"""
elementArray = self.Element.FindAll(scope, condition)
if not elementArray:
return []
-
+
controls = []
length = elementArray.Length
for i in range(length):
@@ -725,23 +725,23 @@ class Control():
if control:
controls.append(control)
return controls
-
- def FindAllBuildCache(self, scope: int, condition, cacheRequest: 'CacheRequest') -> List['Control']:
+
+ def FindAllBuildCache(self, scope: int, condition, cacheRequest: 'CacheRequest') -> list['Control']:
"""
Find all UI Automation elements that satisfy the specified condition, and cache properties and patterns.
Call IUIAutomationElement::FindAllBuildCache.
-
+
scope: int, a value in class `TreeScope`, specifying the scope of the search.
condition: a condition object from IUIAutomation.CreateTrueCondition() or similar.
cacheRequest: CacheRequest, specifies the properties and patterns to cache.
Return List[Control], a list of `Control` subclasses that match the condition with cached data.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-findallbuildcache
"""
elementArray = self.Element.FindAllBuildCache(scope, condition, cacheRequest.check_request)
if not elementArray:
return []
-
+
controls = []
length = elementArray.Length
for i in range(length):
@@ -750,52 +750,52 @@ class Control():
if control:
controls.append(control)
return controls
-
+
def FindFirst(self, scope: int, condition) -> Optional['Control']:
"""
Find the first UI Automation element that satisfies the specified condition.
Call IUIAutomationElement::FindFirst.
-
+
scope: int, a value in class `TreeScope`, specifying the scope of the search.
condition: a condition object from IUIAutomation.CreateTrueCondition() or similar.
Return `Control` subclass or None.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-findfirst
"""
element = self.Element.FindFirst(scope, condition)
return Control.CreateControlFromElement(element)
-
+
def FindFirstBuildCache(self, scope: int, condition, cacheRequest: 'CacheRequest') -> Optional['Control']:
"""
Find the first UI Automation element that satisfies the specified condition, and cache properties and patterns.
Call IUIAutomationElement::FindFirstBuildCache.
-
+
scope: int, a value in class `TreeScope`, specifying the scope of the search.
condition: a condition object from IUIAutomation.CreateTrueCondition() or similar.
cacheRequest: CacheRequest, specifies the properties and patterns to cache.
Return `Control` subclass or None with cached data.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-findfirstbuildcache
"""
element = self.Element.FindFirstBuildCache(scope, condition, cacheRequest.check_request)
return Control.CreateControlFromElement(element)
-
- def GetCachedChildren(self) -> List['Control']:
+
+ def GetCachedChildren(self) -> list['Control']:
"""
Retrieve the cached child elements of this UI Automation element.
Call IUIAutomationElement::GetCachedChildren.
-
+
Return List[Control], a list of cached child `Control` subclasses.
- Note: Children are cached only if the scope of the cache request included TreeScope_Subtree,
+ Note: Children are cached only if the scope of the cache request included TreeScope_Subtree,
TreeScope_Children, or TreeScope_Descendants.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcachedchildren
"""
try:
elementArray = self.Element.GetCachedChildren()
if not elementArray:
return []
-
+
controls = []
length = elementArray.Length
for i in range(length):
@@ -804,86 +804,86 @@ class Control():
if control:
controls.append(control)
return controls
- except comtypes.COMError as ex:
+ except comtypes.COMError:
return []
-
+
def GetCachedParent(self) -> Optional['Control']:
"""
Retrieve the cached parent of this UI Automation element.
Call IUIAutomationElement::GetCachedParent.
-
+
Return `Control` subclass or None.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcachedparent
"""
try:
element = self.Element.GetCachedParent()
return Control.CreateControlFromElement(element)
- except comtypes.COMError as ex:
+ except comtypes.COMError:
return None
-
+
def GetCachedPattern(self, patternId: int):
"""
Retrieve a cached pattern interface from this UI Automation element.
Call IUIAutomationElement::GetCachedPattern.
-
+
patternId: int, a value in class `PatternId`.
Return a pattern object if the pattern was cached, else None.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcachedpattern
"""
try:
pattern = self.Element.GetCachedPattern(patternId)
if pattern:
return CreatePattern(patternId, pattern)
- except comtypes.COMError as ex:
+ except comtypes.COMError:
return None
-
+
def GetCachedPatternAs(self, patternId: int, riid):
"""
Retrieve a cached pattern interface from this UI Automation element, with a specific interface ID.
Call IUIAutomationElement::GetCachedPatternAs.
-
+
patternId: int, a value in class `PatternId`.
riid: GUID, the interface identifier.
Return a pattern object if the pattern was cached, else None.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcachedpatternas
"""
try:
return self.Element.GetCachedPatternAs(patternId, riid)
- except comtypes.COMError as ex:
+ except comtypes.COMError:
return None
-
+
def GetCachedPropertyValue(self, propertyId: int) -> Any:
"""
Retrieve a cached property value from this UI Automation element.
Call IUIAutomationElement::GetCachedPropertyValue.
-
+
propertyId: int, a value in class `PropertyId`.
Return Any, the cached property value corresponding to propertyId.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcachedpropertyvalue
"""
try:
return self.Element.GetCachedPropertyValue(propertyId)
- except comtypes.COMError as ex:
+ except comtypes.COMError:
return None
-
+
def GetCachedPropertyValueEx(self, propertyId: int, ignoreDefaultValue: int) -> Any:
"""
Retrieve a cached property value from this UI Automation element, optionally ignoring the default value.
Call IUIAutomationElement::GetCachedPropertyValueEx.
-
+
propertyId: int, a value in class `PropertyId`.
ignoreDefaultValue: int, 0 or 1. If 1, a default value is not returned.
Return Any, the cached property value corresponding to propertyId.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcachedpropertyvalueex
"""
try:
return self.Element.GetCachedPropertyValueEx(propertyId, ignoreDefaultValue)
- except comtypes.COMError as ex:
+ except comtypes.COMError:
return None
def GetClickablePoint(self) -> Tuple[int, int, bool]:
@@ -908,7 +908,7 @@ class Control():
subPattern = CreatePattern(patternId, pattern)
self._supportedPatterns[patternId] = subPattern
return subPattern
- except comtypes.COMError as ex:
+ except comtypes.COMError:
pass
def GetPatternAs(self, patternId: int, riid):
@@ -940,7 +940,7 @@ class Control():
"""
return self.Element.GetCurrentPropertyValueEx(propertyId, ignoreDefaultValue)
- def GetRuntimeId(self) -> List[int]:
+ def GetRuntimeId(self) -> list[int]:
"""
Call IUIAutomationElement::GetRuntimeId.
Return List[int], a list of int.
@@ -958,7 +958,7 @@ class Control():
"""
try:
return self.Element.SetFocus() == S_OK
- except comtypes.COMError as ex:
+ except comtypes.COMError:
return False
@property
@@ -1001,12 +1001,12 @@ class Control():
return pattern
@property
- def AvailablePatternIds(self) -> List[PatternId]:
+ def AvailablePatternIds(self) -> list[PatternId]:
"""
Return the UI Automation pattern ids currently supported by this control.
These ids can be passed directly into `GetPattern()`.
"""
- supported_pattern_ids: List[PatternId] = []
+ supported_pattern_ids: list[PatternId] = []
for pattern_id in PatternConstructors.keys():
try:
if self.GetPattern(pattern_id):
@@ -1016,7 +1016,7 @@ class Control():
return supported_pattern_ids
@property
- def AvailablePatternNames(self) -> List[str]:
+ def AvailablePatternNames(self) -> list[str]:
"""
Return the UI Automation pattern names currently supported by this control.
"""
@@ -1105,7 +1105,7 @@ class Control():
else:
break
- def GetChildren(self) -> List['Control']:
+ def GetChildren(self) -> list['Control']:
"""
Return List[Control], a list of `Control` subclasses.
"""
@@ -1181,9 +1181,9 @@ class Control():
prev = self.searchFromControl
if prev and not prev._element and not prev.Exists(maxSearchSeconds, searchIntervalSeconds):
return False
- startTime2 = ProcessTime()
+ ProcessTime()
if DEBUG_SEARCH_TIME:
- startDateTime = datetime.datetime.now()
+ datetime.datetime.now()
while True:
control = FindControl(self.searchFromControl, self._CompareFunction, self.searchDepth, False, self.foundIndex)
if control:
@@ -1229,12 +1229,12 @@ class Control():
"""
if not self.Exists(maxSearchSeconds, searchIntervalSeconds, False if raiseException else DEBUG_EXIST_DISAPPEAR):
if raiseException:
- raise LookupError('Find Control Timeout({}s): {}'.format(maxSearchSeconds, self.GetSearchPropertiesStr()))
+ raise LookupError(f'Find Control Timeout({maxSearchSeconds}s): {self.GetSearchPropertiesStr()}')
else:
return False
return True
- def GetPosition(self, ratioX: float = 0.5, ratioY: float = 0.5) -> Optional[Tuple[int, int]]:
+ def GetPosition(self, ratioX: float = 0.5, ratioY: float = 0.5) -> Tuple[int, int] | None:
"""
Gets the position of the center of the control.
ratioX: float.
@@ -1248,7 +1248,7 @@ class Control():
y = rect.top + int(rect.height() * ratioY)
return x, y
- def MoveCursorToInnerPos(self, x: Optional[int] = None, y: Optional[int] = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True) -> Optional[Tuple[int, int]]:
+ def MoveCursorToInnerPos(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True) -> Tuple[int, int] | None:
"""
Move cursor to control's internal position, default to center.
x: int, if < 0, move to self.BoundingRectangle.right + x, if not None, ignore ratioX.
@@ -1276,14 +1276,14 @@ class Control():
SetCursorPos(x, y)
return x, y
- def MoveCursorToMyCenter(self, simulateMove: bool = True) -> Optional[Tuple[int, int]]:
+ def MoveCursorToMyCenter(self, simulateMove: bool = True) -> Tuple[int, int] | None:
"""
Move cursor to control's center.
Return Tuple[int, int], two ints tuple (x, y), the cursor positon relative to screen(0, 0) after moving.
"""
return self.MoveCursorToInnerPos(simulateMove=simulateMove)
- def Click(self, x: Optional[int] = None, y: Optional[int] = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def Click(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x: int, if < 0, click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
@@ -1300,7 +1300,7 @@ class Control():
if point:
Click(point[0], point[1], waitTime)
- def MiddleClick(self, x: Optional[int] = None, y: Optional[int] = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def MiddleClick(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x: int, if < 0, middle click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, middle click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
@@ -1317,7 +1317,7 @@ class Control():
if point:
MiddleClick(point[0], point[1], waitTime)
- def RightClick(self, x: Optional[int] = None, y: Optional[int] = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def RightClick(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x: int, if < 0, right click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, right click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
@@ -1334,7 +1334,7 @@ class Control():
if point:
RightClick(point[0], point[1], waitTime)
- def DoubleClick(self, x: Optional[int] = None, y: Optional[int] = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def DoubleClick(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x: int, if < 0, right click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, right click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
@@ -1371,7 +1371,7 @@ class Control():
y2 = (rect.top if y2 >= 0 else rect.bottom) + y2
RightDragDrop(x1, y1, x2, y2, moveSpeed, waitTime)
- def WheelDown(self, x: Optional[int] = None, y: Optional[int] = None, ratioX: float = 0.5, ratioY: float = 0.5, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def WheelDown(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Make control have focus first, move cursor to the specified position and mouse wheel down.
x: int, if < 0, move x cursor to self.BoundingRectangle.right + x, if not None, ignore ratioX.
@@ -1389,7 +1389,7 @@ class Control():
WheelDown(wheelTimes, interval, waitTime)
SetCursorPos(cursorX, cursorY)
- def WheelUp(self, x: Optional[int] = None, y: Optional[int] = None, ratioX: float = 0.5, ratioY: float = 0.5, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def WheelUp(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Make control have focus first, move cursor to the specified position and mouse wheel up.
x: int, if < 0, move x cursor to self.BoundingRectangle.right + x, if not None, ignore ratioX.
@@ -1407,7 +1407,7 @@ class Control():
WheelUp(wheelTimes, interval, waitTime)
SetCursorPos(cursorX, cursorY)
- def ShowWindow(self, cmdShow: int, waitTime: float = OPERATION_WAIT_TIME) -> Optional[bool]:
+ def ShowWindow(self, cmdShow: int, waitTime: float = OPERATION_WAIT_TIME) -> bool | None:
"""
Get a native handle from self or ancestors until valid and call native `ShowWindow` with cmdShow.
cmdShow: int, a value in in class `SW`.
@@ -1430,14 +1430,14 @@ class Control():
return ret
return None
- def Show(self, waitTime: float = OPERATION_WAIT_TIME) -> Optional[bool]:
+ def Show(self, waitTime: float = OPERATION_WAIT_TIME) -> bool | None:
"""
Call native `ShowWindow(SW.Show)`.
Return bool, True if succeed otherwise False and None if the handle could not be gotten.
"""
return self.ShowWindow(SW.Show, waitTime)
- def Hide(self, waitTime: float = OPERATION_WAIT_TIME) -> Optional[bool]:
+ def Hide(self, waitTime: float = OPERATION_WAIT_TIME) -> bool | None:
"""
Call native `ShowWindow(SW.Hide)`.
waitTime: float
@@ -1460,7 +1460,7 @@ class Control():
return MoveWindow(handle, x, y, width, height, int(repaint))
return False
- def GetWindowText(self) -> Optional[str]:
+ def GetWindowText(self) -> str | None:
"""
Call native GetWindowText if control has a valid native handle.
"""
@@ -1540,13 +1540,13 @@ class Control():
return None
def Control(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'Control':
return Control(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1560,13 +1560,13 @@ class Control():
**searchProperties)
def ButtonControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ButtonControl':
return ButtonControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1580,13 +1580,13 @@ class Control():
**searchProperties)
def CalendarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'CalendarControl':
return CalendarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1600,13 +1600,13 @@ class Control():
**searchProperties)
def CheckBoxControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'CheckBoxControl':
return CheckBoxControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1620,13 +1620,13 @@ class Control():
**searchProperties)
def ComboBoxControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ComboBoxControl':
return ComboBoxControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1640,13 +1640,13 @@ class Control():
**searchProperties)
def CustomControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'CustomControl':
return CustomControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1660,13 +1660,13 @@ class Control():
**searchProperties)
def DataGridControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'DataGridControl':
return DataGridControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1680,13 +1680,13 @@ class Control():
**searchProperties)
def DataItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'DataItemControl':
return DataItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1700,13 +1700,13 @@ class Control():
**searchProperties)
def DocumentControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'DocumentControl':
return DocumentControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1720,13 +1720,13 @@ class Control():
**searchProperties)
def EditControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'EditControl':
return EditControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1740,13 +1740,13 @@ class Control():
**searchProperties)
def GroupControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'GroupControl':
return GroupControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1760,13 +1760,13 @@ class Control():
**searchProperties)
def HeaderControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'HeaderControl':
return HeaderControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1780,13 +1780,13 @@ class Control():
**searchProperties)
def HeaderItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'HeaderItemControl':
return HeaderItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1800,13 +1800,13 @@ class Control():
**searchProperties)
def HyperlinkControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'HyperlinkControl':
return HyperlinkControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1820,13 +1820,13 @@ class Control():
**searchProperties)
def ImageControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ImageControl':
return ImageControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1840,13 +1840,13 @@ class Control():
**searchProperties)
def ListControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ListControl':
return ListControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1860,13 +1860,13 @@ class Control():
**searchProperties)
def ListItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ListItemControl':
return ListItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1880,13 +1880,13 @@ class Control():
**searchProperties)
def MenuControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'MenuControl':
return MenuControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1900,13 +1900,13 @@ class Control():
**searchProperties)
def MenuBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'MenuBarControl':
return MenuBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1920,13 +1920,13 @@ class Control():
**searchProperties)
def MenuItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'MenuItemControl':
return MenuItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1940,13 +1940,13 @@ class Control():
**searchProperties)
def PaneControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'PaneControl':
return PaneControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1960,13 +1960,13 @@ class Control():
**searchProperties)
def ProgressBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ProgressBarControl':
return ProgressBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -1980,13 +1980,13 @@ class Control():
**searchProperties)
def RadioButtonControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'RadioButtonControl':
return RadioButtonControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2000,13 +2000,13 @@ class Control():
**searchProperties)
def ScrollBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ScrollBarControl':
return ScrollBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2020,13 +2020,13 @@ class Control():
**searchProperties)
def SemanticZoomControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'SemanticZoomControl':
return SemanticZoomControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2040,13 +2040,13 @@ class Control():
**searchProperties)
def SeparatorControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'SeparatorControl':
return SeparatorControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2060,13 +2060,13 @@ class Control():
**searchProperties)
def SliderControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'SliderControl':
return SliderControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2080,13 +2080,13 @@ class Control():
**searchProperties)
def SpinnerControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'SpinnerControl':
return SpinnerControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2100,13 +2100,13 @@ class Control():
**searchProperties)
def SplitButtonControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'SplitButtonControl':
return SplitButtonControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2120,13 +2120,13 @@ class Control():
**searchProperties)
def StatusBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'StatusBarControl':
return StatusBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2140,13 +2140,13 @@ class Control():
**searchProperties)
def TabControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'TabControl':
return TabControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2160,13 +2160,13 @@ class Control():
**searchProperties)
def TabItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'TabItemControl':
return TabItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2180,13 +2180,13 @@ class Control():
**searchProperties)
def TableControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'TableControl':
return TableControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2200,13 +2200,13 @@ class Control():
**searchProperties)
def TextControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'TextControl':
return TextControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2220,13 +2220,13 @@ class Control():
**searchProperties)
def ThumbControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ThumbControl':
return ThumbControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2240,13 +2240,13 @@ class Control():
**searchProperties)
def TitleBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'TitleBarControl':
return TitleBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2260,13 +2260,13 @@ class Control():
**searchProperties)
def ToolBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ToolBarControl':
return ToolBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2280,13 +2280,13 @@ class Control():
**searchProperties)
def ToolTipControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'ToolTipControl':
return ToolTipControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2300,13 +2300,13 @@ class Control():
**searchProperties)
def TreeControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'TreeControl':
return TreeControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2320,13 +2320,13 @@ class Control():
**searchProperties)
def TreeItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'TreeItemControl':
return TreeItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2340,13 +2340,13 @@ class Control():
**searchProperties)
def WindowControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties) -> 'WindowControl':
return WindowControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
foundIndex=foundIndex, element=element,
@@ -2361,18 +2361,18 @@ class Control():
class AppBarControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.AppBarControl,
@@ -2387,18 +2387,18 @@ class AppBarControl(Control):
class ButtonControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ButtonControl,
@@ -2431,18 +2431,18 @@ class ButtonControl(Control):
class CalendarControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.CalendarControl,
@@ -2481,18 +2481,18 @@ class CalendarControl(Control):
class CheckBoxControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.CheckBoxControl,
@@ -2520,18 +2520,18 @@ class CheckBoxControl(Control):
class ComboBoxControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ComboBoxControl,
@@ -2562,7 +2562,7 @@ class ComboBoxControl(Control):
"""
return self.GetPattern(PatternId.ValuePattern)
- def Select(self, itemName: str = '', condition: Optional[Callable[[str], bool]] = None, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> bool:
+ def Select(self, itemName: str = '', condition: Callable[[str], bool] | None = None, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Show combobox's popup menu and select a item by name.
itemName: str.
@@ -2613,18 +2613,18 @@ class ComboBoxControl(Control):
class CustomControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.CustomControl,
@@ -2639,18 +2639,18 @@ class CustomControl(Control):
class DataGridControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.DataGridControl,
@@ -2689,18 +2689,18 @@ class DataGridControl(Control):
class DataItemControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.DataItemControl,
@@ -2757,18 +2757,18 @@ class DataItemControl(Control):
class DocumentControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.DocumentControl,
@@ -2801,18 +2801,18 @@ class DocumentControl(Control):
class EditControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.EditControl,
@@ -2845,18 +2845,18 @@ class EditControl(Control):
class GroupControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.GroupControl,
@@ -2877,18 +2877,18 @@ class GroupControl(Control):
class HeaderControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.HeaderControl,
@@ -2909,18 +2909,18 @@ class HeaderControl(Control):
class HeaderItemControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.HeaderItemControl,
@@ -2947,18 +2947,18 @@ class HeaderItemControl(Control):
class HyperlinkControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.HyperlinkControl,
@@ -2985,18 +2985,18 @@ class HyperlinkControl(Control):
class ImageControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ImageControl,
@@ -3023,18 +3023,18 @@ class ImageControl(Control):
class ListControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ListControl,
@@ -3073,18 +3073,18 @@ class ListControl(Control):
class ListItemControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ListItemControl,
@@ -3141,18 +3141,18 @@ class ListItemControl(Control):
class MenuControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.MenuControl,
@@ -3167,18 +3167,18 @@ class MenuControl(Control):
class MenuBarControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.MenuBarControl,
@@ -3211,18 +3211,18 @@ class MenuBarControl(Control):
class MenuItemControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.MenuItemControl,
@@ -3260,7 +3260,7 @@ class MenuItemControl(Control):
return self.GetPattern(PatternId.TogglePattern)
-class TopLevel():
+class TopLevel:
"""Class TopLevel"""
def SetTopmost(self, isTopmost: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> bool:
@@ -3348,18 +3348,18 @@ class TopLevel():
class PaneControl(Control, TopLevel):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.PaneControl,
@@ -3392,18 +3392,18 @@ class PaneControl(Control, TopLevel):
class ProgressBarControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ProgressBarControl,
@@ -3430,18 +3430,18 @@ class ProgressBarControl(Control):
class RadioButtonControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.RadioButtonControl,
@@ -3462,18 +3462,18 @@ class RadioButtonControl(Control):
class ScrollBarControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ScrollBarControl,
@@ -3494,18 +3494,18 @@ class ScrollBarControl(Control):
class SemanticZoomControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.SemanticZoomControl,
@@ -3520,18 +3520,18 @@ class SemanticZoomControl(Control):
class SeparatorControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.SeparatorControl,
@@ -3546,18 +3546,18 @@ class SeparatorControl(Control):
class SliderControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.SliderControl,
@@ -3590,18 +3590,18 @@ class SliderControl(Control):
class SpinnerControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.SpinnerControl,
@@ -3634,18 +3634,18 @@ class SpinnerControl(Control):
class SplitButtonControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.SplitButtonControl,
@@ -3672,18 +3672,18 @@ class SplitButtonControl(Control):
class StatusBarControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.StatusBarControl,
@@ -3704,18 +3704,18 @@ class StatusBarControl(Control):
class TabControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.TabControl,
@@ -3742,18 +3742,18 @@ class TabControl(Control):
class TabItemControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.TabItemControl,
@@ -3774,18 +3774,18 @@ class TabItemControl(Control):
class TableControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.TableControl,
@@ -3842,18 +3842,18 @@ class TableControl(Control):
class TextControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.TextControl,
@@ -3886,18 +3886,18 @@ class TextControl(Control):
class ThumbControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ThumbControl,
@@ -3918,18 +3918,18 @@ class ThumbControl(Control):
class TitleBarControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.TitleBarControl,
@@ -3944,18 +3944,18 @@ class TitleBarControl(Control):
class ToolBarControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ToolBarControl,
@@ -3988,18 +3988,18 @@ class ToolBarControl(Control):
class ToolTipControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.ToolTipControl,
@@ -4026,18 +4026,18 @@ class ToolTipControl(Control):
class TreeControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.TreeControl,
@@ -4064,18 +4064,18 @@ class TreeControl(Control):
class TreeItemControl(Control):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.TreeItemControl,
@@ -4120,18 +4120,18 @@ class TreeItemControl(Control):
class WindowControl(Control, TopLevel):
- def __init__(self, searchFromControl: Optional[Control] = None,
+ def __init__(self, searchFromControl: Control | None = None,
searchDepth: int = 0xFFFFFFFF,
searchInterval: float = SEARCH_INTERVAL,
foundIndex: int = 1,
element=None,
- Name: Optional[str] = None,
- SubName: Optional[str] = None,
- RegexName: Optional[str] = None,
- ClassName: Optional[str] = None,
- AutomationId: Optional[str] = None,
- Depth: Optional[int] = None,
- Compare: Optional[Callable[[TreeNode], bool]] = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
**searchProperties):
Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
ControlType=ControlType.WindowControl,
@@ -4251,9 +4251,9 @@ def WaitForDisappear(control: Control, timeout: float) -> bool:
return control.Disappears(timeout, 1)
-def WalkTree(top, getChildren: Optional[Callable[[TreeNode], List[TreeNode]]] = None,
- getFirstChild: Optional[Callable[[TreeNode], TreeNode]] = None, getNextSibling: Optional[Callable[[TreeNode], TreeNode]] = None,
- yieldCondition: Optional[Callable[[TreeNode, int], bool]] = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF):
+def WalkTree(top, getChildren: Callable[[TreeNode], list[TreeNode]] | None = None,
+ getFirstChild: Callable[[TreeNode], TreeNode] | None = None, getNextSibling: Callable[[TreeNode], TreeNode] | None = None,
+ yieldCondition: Callable[[TreeNode, int], bool] | None = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF):
"""
Walk a tree not using recursive algorithm.
top: a tree node.
@@ -4334,10 +4334,10 @@ def GetRootControl() -> PaneControl:
if control is None:
raise AssertionError('Expected valid root element')
- raise AssertionError('Expected root element to be a PaneControl. Found: %s (%s)' % (type(control), control))
+ raise AssertionError(f'Expected root element to be a PaneControl. Found: {type(control)} ({control})')
-def GetFocusedControl() -> Optional[Control]:
+def GetFocusedControl() -> Control | None:
"""Return `Control` subclass."""
return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.GetFocusedElement())
@@ -4359,7 +4359,7 @@ def GetForegroundControl() -> Control:
# return parentControl
-def GetConsoleWindow() -> Optional[WindowControl]:
+def GetConsoleWindow() -> WindowControl | None:
"""Return `WindowControl` or None, a console window that runs python."""
consoleWindow = ControlFromHandle(ctypes.windll.kernel32.GetConsoleWindow())
if consoleWindow and consoleWindow.ClassName == 'PseudoConsoleWindow':
@@ -4368,7 +4368,7 @@ def GetConsoleWindow() -> Optional[WindowControl]:
return consoleWindow
-def ControlFromPoint(x: int, y: int) -> Optional[Control]:
+def ControlFromPoint(x: int, y: int) -> Control | None:
"""
Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon.
Return `Control` subclass or None.
@@ -4377,7 +4377,7 @@ def ControlFromPoint(x: int, y: int) -> Optional[Control]:
return Control.CreateControlFromElement(element)
-def ControlFromPoint2(x: int, y: int) -> Optional[Control]:
+def ControlFromPoint2(x: int, y: int) -> Control | None:
"""
Get a native handle from point x,y and call IUIAutomation.ElementFromHandle.
Return `Control` subclass.
@@ -4385,7 +4385,7 @@ def ControlFromPoint2(x: int, y: int) -> Optional[Control]:
return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y)))
-def ControlFromCursor() -> Optional[Control]:
+def ControlFromCursor() -> Control | None:
"""
Call ControlFromPoint with current cursor point.
Return `Control` subclass.
@@ -4394,7 +4394,7 @@ def ControlFromCursor() -> Optional[Control]:
return ControlFromPoint(x, y)
-def ControlFromCursor2() -> Optional[Control]:
+def ControlFromCursor2() -> Control | None:
"""
Call ControlFromPoint2 with current cursor point.
Return `Control` subclass.
@@ -4403,7 +4403,7 @@ def ControlFromCursor2() -> Optional[Control]:
return ControlFromPoint2(x, y)
-def ControlFromHandle(handle: int) -> Optional[Control]:
+def ControlFromHandle(handle: int) -> Control | None:
"""
Call IUIAutomation.ElementFromHandle with a native handle.
handle: int, a native window handle.
@@ -4490,7 +4490,7 @@ def EnumAndLogControlAncestors(control: Control, showAllName: bool = True, showP
LogControl(curr, i, showAllName, showPid)
-def FindControl(control: Optional[Control], compare: Callable[[Control, int], bool], maxDepth: int = 0xFFFFFFFF, findFromSelf: bool = False, foundIndex: int = 1) -> Optional[Control]:
+def FindControl(control: Control | None, compare: Callable[[Control, int], bool], maxDepth: int = 0xFFFFFFFF, findFromSelf: bool = False, foundIndex: int = 1) -> Control | None:
"""
control: `Control` or its subclass.
compare: Callable[[Control, int], bool], function(control: Control, depth: int) -> bool.
diff --git a/windows_use/uia/core.py b/windows_use/uia/core.py
index 0591168..b9d7900 100644
--- a/windows_use/uia/core.py
+++ b/windows_use/uia/core.py
@@ -11,19 +11,19 @@ uiautomation is shared under the Apache Licene 2.0.
This means that the code can be freely copied and distributed, and costs nothing to use.
'''
+import ctypes
+import ctypes.wintypes
import os
-import sys
-import time
import shlex
import struct
+import sys
import threading
-import ctypes
+import time
+from collections.abc import Callable
+from typing import Any
+
import comtypes
-import ctypes.wintypes
import comtypes.client
-import ctypes.wintypes
-from typing import (Any, Callable, Dict, List, Tuple, Optional,Generator)
-
METRO_WINDOW_CLASS_NAME = 'Windows.UI.Core.CoreWindow' # for Windows 8 and 8.1
SEARCH_INTERVAL = 0.5 # search control interval seconds
@@ -42,8 +42,6 @@ ProcessTime = time.perf_counter # this returns nearly 0 when first call it if p
ProcessTime() # need to call it once if python version <= 3.6
TreeNode = Any
from .enums import *
-import ctypes.wintypes
-
def IsTopLevelWindow(handle: int) -> bool:
@@ -113,7 +111,7 @@ ctypes.windll.kernel32.GlobalLock.restype = ctypes.c_void_p
ctypes.windll.kernel32.OpenProcess.restype = ctypes.c_void_p
ctypes.windll.ntdll.NtQueryInformationProcess.restype = ctypes.c_uint32
-def _GetDictKeyName(theDict: Dict[str, Any], theValue: Any, keyCondition: Optional[Callable[[str], bool]] = None) -> str:
+def _GetDictKeyName(theDict: dict[str, Any], theValue: Any, keyCondition: Callable[[str], bool] | None = None) -> str:
for key, value in theDict.items():
if keyCondition:
if keyCondition(key) and theValue == value:
@@ -167,7 +165,7 @@ def WindowFromPoint(x: int, y: int) -> int:
return ctypes.windll.user32.WindowFromPoint(ctypes.wintypes.POINT(x, y)) # or ctypes.windll.user32.WindowFromPoint(x, y)
-def GetCursorPos() -> Tuple[int, int]:
+def GetCursorPos() -> tuple[int, int]:
"""
GetCursorPos from Win32.
Get current mouse cursor positon.
@@ -178,7 +176,7 @@ def GetCursorPos() -> Tuple[int, int]:
return point.x, point.y
-def GetPhysicalCursorPos() -> Tuple[int, int]:
+def GetPhysicalCursorPos() -> tuple[int, int]:
"""
GetPhysicalCursorPos from Win32.
Get current mouse cursor positon.
@@ -516,7 +514,7 @@ def DragTo(start_x: int, start_y: int, end_x: int, end_y: int,
ReleaseMouse(0.05)
-def GetScreenSize() -> Tuple[int, int]:
+def GetScreenSize() -> tuple[int, int]:
"""
Return Tuple[int, int], two ints tuple (width, height).
"""
@@ -554,7 +552,7 @@ def SetScreenSize(width: int, height: int) -> bool:
return False
-def GetVirtualScreenSize() -> Tuple[int, int]:
+def GetVirtualScreenSize() -> tuple[int, int]:
"""
Return Tuple[int, int], two ints tuple (width, height).
"""
@@ -565,7 +563,7 @@ def GetVirtualScreenSize() -> Tuple[int, int]:
return w, h
-def GetVirtualScreenRect() -> Tuple[int, int, int, int]:
+def GetVirtualScreenRect() -> tuple[int, int, int, int]:
"""Returns (left, top, width, height) of the virtual screen."""
SM_XVIRTUALSCREEN = 76
SM_YVIRTUALSCREEN = 77
@@ -580,7 +578,7 @@ def GetVirtualScreenRect() -> Tuple[int, int, int, int]:
-def GetMonitorsRect() -> List[Rect]:
+def GetMonitorsRect() -> list[Rect]:
"""
Get monitors' rect.
Return List[Rect].
@@ -592,7 +590,7 @@ def GetMonitorsRect() -> List[Rect]:
rect = Rect(lprcMonitor.contents.left, lprcMonitor.contents.top, lprcMonitor.contents.right, lprcMonitor.contents.bottom)
rects.append(rect)
return 1
- ret = ctypes.windll.user32.EnumDisplayMonitors(ctypes.c_void_p(0), ctypes.c_void_p(0), MonitorEnumProc(MonitorCallback), 0)
+ ctypes.windll.user32.EnumDisplayMonitors(ctypes.c_void_p(0), ctypes.c_void_p(0), MonitorEnumProc(MonitorCallback), 0)
return rects
@@ -869,7 +867,7 @@ def DwmIsCompositionEnabled() -> bool:
return False
-def DwmGetWindowExtendFrameBounds(handle: int) -> Optional[Rect]:
+def DwmGetWindowExtendFrameBounds(handle: int) -> Rect | None:
"""
Get Native Window Rect without invisible resize borders.
Return Rect or None. If handle is not top level, return None.
@@ -892,7 +890,7 @@ def DwmGetWindowExtendFrameBounds(handle: int) -> Optional[Rect]:
return None
-def GetWindowRect(handle: int) -> Optional[Rect]:
+def GetWindowRect(handle: int) -> Rect | None:
"""
GetWindowRect from user32.
Return RECT.
@@ -943,7 +941,7 @@ def PlayWaveFile(filePath: str = r'C:\Windows\Media\notify.wav', isAsync: bool =
return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(0), ctypes.c_void_p(0), ctypes.c_uint(0)))
-def IsProcess64Bit(processId: int) -> Optional[bool]:
+def IsProcess64Bit(processId: int) -> bool | None:
"""
Return True if process is 64 bit.
Return False if process is 32 bit.
@@ -951,7 +949,7 @@ def IsProcess64Bit(processId: int) -> Optional[bool]:
"""
try:
IsWow64Process = ctypes.windll.kernel32.IsWow64Process
- except Exception as ex:
+ except Exception:
return False
hProcess = ctypes.windll.kernel32.OpenProcess(0x1000, 0, processId) # PROCESS_QUERY_INFORMATION=0x0400,PROCESS_QUERY_LIMITED_INFORMATION=0x1000
if hProcess:
@@ -974,7 +972,7 @@ def IsUserAnAdmin() -> bool:
return bool(ctypes.windll.shell32.IsUserAnAdmin()) if IsNT6orHigher else True
-def RunScriptAsAdmin(argv: List[str], workingDirectory: str = None, showFlag: int = SW.ShowNormal) -> bool:
+def RunScriptAsAdmin(argv: list[str], workingDirectory: str = None, showFlag: int = SW.ShowNormal) -> bool:
"""
Run a python script as administrator.
System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled.
@@ -1188,9 +1186,9 @@ def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT
keyStr = text[i + 1:rindex]
key = [it for it in keyStr.split(' ') if it]
if not key:
- raise ValueError('"{}" is not valid, use "{{Space}}" or " " for " "'.format(text[i:rindex + 1]))
+ raise ValueError(f'"{text[i:rindex + 1]}" is not valid, use "{{Space}}" or " " for " "')
if (len(key) == 2 and not key[1].isdigit()) or len(key) > 2:
- raise ValueError('"{}" is not valid'.format(text[i:rindex + 1]))
+ raise ValueError(f'"{text[i:rindex + 1]}" is not valid')
upperKey = key[0].upper()
count = 1
if len(key) > 1:
@@ -1319,7 +1317,7 @@ def SetThreadDpiAwarenessContext(dpiAwarenessContext: int):
ctypes.windll.user32.SetThreadDpiAwarenessContext.restype = ctypes.c_void_p
oldContext = ctypes.windll.user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(dpiAwarenessContext))
return oldContext
- except Exception as ex:
+ except Exception:
pass
@@ -1391,15 +1389,14 @@ class ProcessInfo:
self.cmdLine = cmdLine # empty if failed
def __str__(self):
- return "ProcessInfo(pid={}, ppid={}, exeName='{}', is64Bit={}, exePath='{}', cmdLine='{}'".format(
- self.pid, self.ppid, self.exeName, self.is64Bit, self.exePath, self.cmdLine)
+ return f"ProcessInfo(pid={self.pid}, ppid={self.ppid}, exeName='{self.exeName}', is64Bit={self.is64Bit}, exePath='{self.exePath}', cmdLine='{self.cmdLine}'"
def __repr__(self):
return '<{} object at 0x{:08X} {}>'.format(self.__class__.__name__, id(self),
- ', '.join('{}={}'.format(k, v) for k, v in self.__dict__.items()))
+ ', '.join(f'{k}={v}' for k, v in self.__dict__.items()))
-def GetProcesses(detailedInfo: bool = True) -> List[ProcessInfo]:
+def GetProcesses(detailedInfo: bool = True) -> list[ProcessInfo]:
'''
Enum process by Win32 API.
detailedInfo: bool, only get pid and exeName if False.
@@ -1409,7 +1406,7 @@ def GetProcesses(detailedInfo: bool = True) -> List[ProcessInfo]:
if detailedInfo:
try:
IsWow64Process = ctypes.windll.kernel32.IsWow64Process
- except Exception as ex:
+ except Exception:
IsWow64Process = None
hSnapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot(15, 0) # TH32CS_SNAPALL = 15
processEntry32 = tagPROCESSENTRY32()
@@ -1529,7 +1526,7 @@ def _OpenClipboard(value):
time.sleep(0.005)
-def GetClipboardFormats() -> Dict[int, str]:
+def GetClipboardFormats() -> dict[int, str]:
'''
Get clipboard formats that system clipboard has currently.
Return Dict[int, str].
@@ -1625,10 +1622,10 @@ def SetClipboardHtml(htmlText: str) -> bool:
endHtml = len(formatBytes) + len(u8Html) - 2
startFragment = formatBytes.find(b'{}')
endFragment = formatBytes.find(b'<!--EndFragment-->') + len(u8Html) - 2
- formatBytes = formatBytes.replace(b'StartHTML:00000000', 'StartHTML:{:08}'.format(startHtml).encode('utf-8'))
- formatBytes = formatBytes.replace(b'EndHTML:00000000', 'EndHTML:{:08}'.format(endHtml).encode('utf-8'))
- formatBytes = formatBytes.replace(b'StartFragment:00000000', 'StartFragment:{:08}'.format(startFragment).encode('utf-8'))
- formatBytes = formatBytes.replace(b'EndFragment:00000000', 'EndFragment:{:08}'.format(endFragment).encode('utf-8'))
+ formatBytes = formatBytes.replace(b'StartHTML:00000000', f'StartHTML:{startHtml:08}'.encode())
+ formatBytes = formatBytes.replace(b'EndHTML:00000000', f'EndHTML:{endHtml:08}'.encode())
+ formatBytes = formatBytes.replace(b'StartFragment:00000000', f'StartFragment:{startFragment:08}'.encode())
+ formatBytes = formatBytes.replace(b'EndFragment:00000000', f'EndFragment:{endFragment:08}'.encode())
u8Result = formatBytes.replace(b'{}', u8Html)
ret = False
with _ClipboardLock:
@@ -1657,7 +1654,7 @@ def Input(prompt: str, consoleColor: int = ConsoleColor.Default) -> str:
def InputColorfully(prompt: str, consoleColor: int = ConsoleColor.Default) -> str:
print(prompt, end="")
return input()
-class Rect():
+class Rect:
"""
class Rect, like `ctypes.wintypes.RECT`.
"""
@@ -1700,10 +1697,10 @@ class Rect():
return self.left == rect.left and self.top == rect.top and self.right == rect.right and self.bottom == rect.bottom
def __str__(self) -> str:
- return '({},{},{},{})[{}x{}]'.format(self.left, self.top, self.right, self.bottom, self.width(), self.height())
+ return f'({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]'
def __repr__(self) -> str:
- return '{}({},{},{},{})[{}x{}]'.format(self.__class__.__name__, self.left, self.top, self.right, self.bottom, self.width(), self.height())
+ return f'{self.__class__.__name__}({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]'
class ClipboardFormat:
@@ -2031,7 +2028,7 @@ def RemoveAutomationEventHandler(eventId: int, element, handler) -> None:
"""
_AutomationClient.instance().IUIAutomation.RemoveAutomationEventHandler(eventId, element, handler)
-def AddPropertyChangedEventHandler(element, scope: int, cacheRequest, handler, propertyArray: List[int]) -> None:
+def AddPropertyChangedEventHandler(element, scope: int, cacheRequest, handler, propertyArray: list[int]) -> None:
"""
Registers a method that handles UI Automation property-changed events.
"""
@@ -2040,7 +2037,7 @@ def AddPropertyChangedEventHandler(element, scope: int, cacheRequest, handler, p
# Let's see how generic we can be.
# The signature in IUIAutomation is: HRESULT AddPropertyChangedEventHandler(ptr_element, scope, ptr_cacheRequest, ptr_handler, ptr_propertyArray)
# The last arg is SAFEARRAY(int)
-
+
# We might need to manually convert list to SAFEARRAY or rely on comtypes.
# For now, let's pass a tuple/list and see if comtypes marshals it.
_AutomationClient.instance().IUIAutomation.AddPropertyChangedEventHandler(element, scope, cacheRequest, handler, propertyArray)
@@ -2087,7 +2084,7 @@ def RemoveAllEventHandlers() -> None:
def CreateTrueCondition():
"""
Create a condition that is always true. This matches all elements.
-
+
Return: A condition object that can be used with FindAll, FindFirst, etc.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-createtruecondition
"""
@@ -2097,7 +2094,7 @@ def CreateTrueCondition():
def CreateFalseCondition():
"""
Create a condition that is always false. This matches no elements.
-
+
Return: A condition object that can be used with FindAll, FindFirst, etc.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-createfalsecondition
"""
@@ -2107,11 +2104,11 @@ def CreateFalseCondition():
def CreatePropertyCondition(propertyId: int, value):
"""
Create a condition that matches elements with a specific property value.
-
+
propertyId: int, a value in class `PropertyId`.
value: The value to match for the property.
Return: A condition object that can be used with FindAll, FindFirst, etc.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-createpropertycondition
"""
return _AutomationClient.instance().IUIAutomation.CreatePropertyCondition(propertyId, value)
@@ -2120,11 +2117,11 @@ def CreatePropertyCondition(propertyId: int, value):
def CreateAndCondition(condition1, condition2):
"""
Create a condition that is the logical AND of two conditions.
-
+
condition1: First condition.
condition2: Second condition.
Return: A condition object that can be used with FindAll, FindFirst, etc.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-createandcondition
"""
return _AutomationClient.instance().IUIAutomation.CreateAndCondition(condition1, condition2)
@@ -2133,11 +2130,11 @@ def CreateAndCondition(condition1, condition2):
def CreateOrCondition(condition1, condition2):
"""
Create a condition that is the logical OR of two conditions.
-
+
condition1: First condition.
condition2: Second condition.
Return: A condition object that can be used with FindAll, FindFirst, etc.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-createorcondition
"""
return _AutomationClient.instance().IUIAutomation.CreateOrCondition(condition1, condition2)
@@ -2146,10 +2143,10 @@ def CreateOrCondition(condition1, condition2):
def CreateNotCondition(condition):
"""
Create a condition that is the logical NOT of another condition.
-
+
condition: The condition to negate.
Return: A condition object that can be used with FindAll, FindFirst, etc.
-
+
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-createnotcondition
"""
return _AutomationClient.instance().IUIAutomation.CreateNotCondition(condition)
diff --git a/windows_use/uia/enums.py b/windows_use/uia/enums.py
index 491695b..0676a56 100644
--- a/windows_use/uia/enums.py
+++ b/windows_use/uia/enums.py
@@ -11,15 +11,14 @@ uiautomation is shared under the Apache Licene 2.0.
This means that the code can be freely copied and distributed, and costs nothing to use.
"""
+import ctypes
+import ctypes.wintypes
import os
import sys
import time
-import ctypes
-import ctypes.wintypes
from enum import IntEnum, IntFlag
from typing import Any
-
METRO_WINDOW_CLASS_NAME = 'Windows.UI.Core.CoreWindow' # for Windows 8 and 8.1
SEARCH_INTERVAL = 0.5 # search control interval seconds
MAX_MOVE_SECOND = 1 # simulate mouse move or drag max seconds
@@ -642,7 +641,7 @@ class AccessibleRole:
AccessibleRoleNames = {v: k for k, v in AccessibleRole.__dict__.items() if not k.startswith('_')}
-class AccessibleState():
+class AccessibleState:
"""
AccessibleState from IUIAutomation.
Refer https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.accessiblestates?view=netframework-4.8
@@ -1594,7 +1593,7 @@ class INPUT(ctypes.Structure):
('union', INPUTUnion))
-class Rect():
+class Rect:
"""
class Rect, like `ctypes.wintypes.RECT`.
"""
@@ -1637,10 +1636,10 @@ class Rect():
return self.left == rect.left and self.top == rect.top and self.right == rect.right and self.bottom == rect.bottom
def __str__(self) -> str:
- return '({},{},{},{})[{}x{}]'.format(self.left, self.top, self.right, self.bottom, self.width(), self.height())
+ return f'({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]'
def __repr__(self) -> str:
- return '{}({},{},{},{})[{}x{}]'.format(self.__class__.__name__, self.left, self.top, self.right, self.bottom, self.width(), self.height())
+ return f'{self.__class__.__name__}({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]'
class ClipboardFormat:
diff --git a/windows_use/uia/exceptions.py b/windows_use/uia/exceptions.py
index ca5ecde..edae008 100644
--- a/windows_use/uia/exceptions.py
+++ b/windows_use/uia/exceptions.py
@@ -1,5 +1,6 @@
from _ctypes import COMError # noqa: F401 — re-exported for callers
-from .enums import UIAError, is_dead_element_error, is_retryable_error
+
+from .enums import UIAError
class UIAException(Exception):
diff --git a/windows_use/uia/patterns.py b/windows_use/uia/patterns.py
index bb080a8..6f0f299 100644
--- a/windows_use/uia/patterns.py
+++ b/windows_use/uia/patterns.py
@@ -11,14 +11,16 @@ uiautomation is shared under the Apache Licene 2.0.
This means that the code can be freely copied and distributed, and costs nothing to use.
'''
+import ctypes
import os
import sys
import time
-import ctypes
-from typing import (Any, List, TYPE_CHECKING)
-from .enums import *
+from typing import TYPE_CHECKING, Any
+
from .core import *
from .core import _AutomationClient
+from .enums import *
+
if TYPE_CHECKING:
from .controls import Control
@@ -88,7 +90,6 @@ def GetPatternIdInterface(patternId: int):
PatternId.VirtualizedItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationVirtualizedItemPattern,
PatternId.WindowPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationWindowPattern,
}
- debug = False
# the following patterns doesn't exist on Windows 7 or lower
try:
_PatternIdInterfaces[PatternId.AnnotationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern
@@ -151,7 +152,7 @@ Refer https://docs.microsoft.com/en-us/previous-versions//dd319586(v=vs.85)
"""
-class AnnotationPattern():
+class AnnotationPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationannotationpattern"""
self.pattern = pattern
@@ -205,7 +206,7 @@ class AnnotationPattern():
return Control.CreateControlFromElement(ele)
-class CustomNavigationPattern():
+class CustomNavigationPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationcustomnavigationpattern"""
self.pattern = pattern
@@ -222,7 +223,7 @@ class CustomNavigationPattern():
return Control.CreateControlFromElement(ele)
-class DockPattern():
+class DockPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationdockpattern"""
self.pattern = pattern
@@ -249,7 +250,7 @@ class DockPattern():
return ret
-class DragPattern():
+class DragPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationdragpattern"""
self.pattern = pattern
@@ -266,7 +267,7 @@ class DragPattern():
return self.pattern.CurrentDropEffect
@property
- def DropEffects(self) -> List[str]:
+ def DropEffects(self) -> list[str]:
"""
Property DropEffects.
Call IUIAutomationDragPattern::get_CurrentDropEffects, todo SAFEARRAY.
@@ -286,7 +287,7 @@ class DragPattern():
"""
return bool(self.pattern.CurrentIsGrabbed)
- def GetGrabbedItems(self) -> List['Control']:
+ def GetGrabbedItems(self) -> list['Control']:
"""
Call IUIAutomationDragPattern::GetCurrentGrabbedItems.
Return List[Control], a list of `Control` subclasses that represent the full set of items
@@ -305,7 +306,7 @@ class DragPattern():
return []
-class DropTargetPattern():
+class DropTargetPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationdroptargetpattern"""
self.pattern = pattern
@@ -322,7 +323,7 @@ class DropTargetPattern():
return self.pattern.CurrentDropTargetEffect
@property
- def DropTargetEffects(self) -> List[str]:
+ def DropTargetEffects(self) -> list[str]:
"""
Property DropTargetEffects.
Call IUIAutomationDropTargetPattern::get_CurrentDropTargetEffects, todo SAFEARRAY.
@@ -334,7 +335,7 @@ class DropTargetPattern():
return self.pattern.CurrentDropTargetEffects
-class ExpandCollapsePattern():
+class ExpandCollapsePattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationexpandcollapsepattern"""
self.pattern = pattern
@@ -380,7 +381,7 @@ class ExpandCollapsePattern():
return False
-class GridItemPattern():
+class GridItemPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationgriditempattern"""
self.pattern = pattern
@@ -436,7 +437,7 @@ class GridItemPattern():
return self.pattern.CurrentRowSpan
-class GridPattern():
+class GridPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationgridpattern"""
self.pattern = pattern
@@ -470,7 +471,7 @@ class GridPattern():
return Control.CreateControlFromElement(self.pattern.GetItem(row, column))
-class InvokePattern():
+class InvokePattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationinvokepattern"""
self.pattern = pattern
@@ -488,7 +489,7 @@ class InvokePattern():
return ret
-class ItemContainerPattern():
+class ItemContainerPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationitemcontainerpattern"""
self.pattern = pattern
@@ -506,7 +507,7 @@ class ItemContainerPattern():
return Control.CreateControlFromElement(ele)
-class LegacyIAccessiblePattern():
+class LegacyIAccessiblePattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationlegacyiaccessiblepattern"""
self.pattern = pattern
@@ -613,7 +614,7 @@ class LegacyIAccessiblePattern():
time.sleep(waitTime)
return ret
- def GetSelection(self) -> List['Control']:
+ def GetSelection(self) -> list['Control']:
"""
Call IUIAutomationLegacyIAccessiblePattern::GetCurrentSelection.
Return List[Control], a list of `Control` subclasses,
@@ -667,7 +668,7 @@ class LegacyIAccessiblePattern():
return ret
-class MultipleViewPattern():
+class MultipleViewPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationmultipleviewpattern"""
self.pattern = pattern
@@ -682,7 +683,7 @@ class MultipleViewPattern():
"""
return self.pattern.CurrentCurrentView
- def GetSupportedViews(self) -> List[int]:
+ def GetSupportedViews(self) -> list[int]:
"""
Call IUIAutomationMultipleViewPattern::GetCurrentSupportedViews, todo.
Return List[int], a list of int, control-specific view identifiers.
@@ -710,7 +711,7 @@ class MultipleViewPattern():
return self.pattern.SetCurrentView(view) == S_OK
-class ObjectModelPattern():
+class ObjectModelPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationobjectmodelpattern"""
self.pattern = pattern
@@ -724,7 +725,7 @@ class ObjectModelPattern():
# return self.pattern.GetUnderlyingObjectModel()
-class RangeValuePattern():
+class RangeValuePattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationrangevaluepattern"""
self.pattern = pattern
@@ -805,7 +806,7 @@ class RangeValuePattern():
return ret
-class ScrollItemPattern():
+class ScrollItemPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationscrollitempattern"""
self.pattern = pattern
@@ -822,7 +823,7 @@ class ScrollItemPattern():
return ret
-class ScrollPattern():
+class ScrollPattern:
NoScrollValue = -1
def __init__(self, pattern=None):
@@ -918,7 +919,7 @@ class ScrollPattern():
return ret
-class SelectionItemPattern():
+class SelectionItemPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationselectionitempattern"""
self.pattern = pattern
@@ -981,7 +982,7 @@ class SelectionItemPattern():
return ret
-class SelectionPattern():
+class SelectionPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationselectionpattern"""
self.pattern = pattern
@@ -1006,7 +1007,7 @@ class SelectionPattern():
"""
return bool(self.pattern.CurrentIsSelectionRequired)
- def GetSelection(self) -> List['Control']:
+ def GetSelection(self) -> list['Control']:
"""
Call IUIAutomationSelectionPattern::GetCurrentSelection.
Return List[Control], a list of `Control` subclasses, the selected elements in the container..
@@ -1070,7 +1071,7 @@ class SelectionPattern2(SelectionPattern):
return self.pattern.CurrentItemCount
-class SpreadsheetItemPattern():
+class SpreadsheetItemPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationspreadsheetitempattern"""
self.pattern = pattern
@@ -1085,7 +1086,7 @@ class SpreadsheetItemPattern():
"""
return self.pattern.CurrentFormula
- def GetAnnotationObjects(self) -> List['Control']:
+ def GetAnnotationObjects(self) -> list['Control']:
"""
Call IUIAutomationSelectionPattern::GetCurrentAnnotationObjects.
Return List[Control], a list of `Control` subclasses representing the annotations associated with this spreadsheet cell.
@@ -1102,7 +1103,7 @@ class SpreadsheetItemPattern():
return controls
return []
- def GetAnnotationTypes(self) -> List[int]:
+ def GetAnnotationTypes(self) -> list[int]:
"""
Call IUIAutomationSelectionPattern::GetCurrentAnnotationTypes.
Return List[int], a list of int values in class `AnnotationType`,
@@ -1112,7 +1113,7 @@ class SpreadsheetItemPattern():
return self.pattern.GetCurrentAnnotationTypes()
-class SpreadsheetPattern():
+class SpreadsheetPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationspreadsheetpattern"""
self.pattern = pattern
@@ -1128,7 +1129,7 @@ class SpreadsheetPattern():
return Control.CreateControlFromElement(element=ele)
-class StylesPattern():
+class StylesPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationstylespattern"""
self.pattern = pattern
@@ -1194,7 +1195,7 @@ class StylesPattern():
return self.pattern.CurrentStyleName
-class SynchronizedInputPattern():
+class SynchronizedInputPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationsynchronizedinputpattern"""
self.pattern = pattern
@@ -1218,12 +1219,12 @@ class SynchronizedInputPattern():
return self.pattern.StartListening() == S_OK
-class TableItemPattern():
+class TableItemPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtableitempattern"""
self.pattern = pattern
- def GetColumnHeaderItems(self) -> List['Control']:
+ def GetColumnHeaderItems(self) -> list['Control']:
"""
Call IUIAutomationTableItemPattern::GetCurrentColumnHeaderItems.
Return List[Control], a list of `Control` subclasses, the column headers associated with a table item or cell.
@@ -1240,7 +1241,7 @@ class TableItemPattern():
return controls
return []
- def GetRowHeaderItems(self) -> List['Control']:
+ def GetRowHeaderItems(self) -> list['Control']:
"""
Call IUIAutomationTableItemPattern::GetCurrentRowHeaderItems.
Return List[Control], a list of `Control` subclasses, the row headers associated with a table item or cell.
@@ -1258,7 +1259,7 @@ class TableItemPattern():
return []
-class TablePattern():
+class TablePattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtablepattern"""
self.pattern = pattern
@@ -1273,7 +1274,7 @@ class TablePattern():
"""
return self.pattern.CurrentRowOrColumnMajor
- def GetColumnHeaders(self) -> List['Control']:
+ def GetColumnHeaders(self) -> list['Control']:
"""
Call IUIAutomationTablePattern::GetCurrentColumnHeaders.
Return List[Control], a list of `Control` subclasses, representing all the column headers in a table..
@@ -1290,7 +1291,7 @@ class TablePattern():
return controls
return []
- def GetRowHeaders(self) -> List['Control']:
+ def GetRowHeaders(self) -> list['Control']:
"""
Call IUIAutomationTablePattern::GetCurrentRowHeaders.
Return List[Control], a list of `Control` subclasses, representing all the row headers in a table.
@@ -1308,7 +1309,7 @@ class TablePattern():
return []
-class TextRange():
+class TextRange:
def __init__(self, textRange=None):
"""
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtextrange
@@ -1409,7 +1410,7 @@ class TextRange():
"""
return self.textRange.GetAttributeValue(textAttributeId)
- def GetBoundingRectangles(self) -> List[Rect]:
+ def GetBoundingRectangles(self) -> list[Rect]:
"""
Call IUIAutomationTextRange::GetBoundingRectangles.
textAttributeId: int, a value in class `TextAttributeId`.
@@ -1428,7 +1429,7 @@ class TextRange():
rects.append(rect)
return rects
- def GetChildren(self) -> List['Control']:
+ def GetChildren(self) -> list['Control']:
"""
Call IUIAutomationTextRange::GetChildren.
textAttributeId: int, a value in class `TextAttributeId`.
@@ -1551,7 +1552,7 @@ class TextRange():
return ret
-class TextChildPattern():
+class TextChildPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtextchildpattern"""
self.pattern = pattern
@@ -1577,7 +1578,7 @@ class TextChildPattern():
return TextRange(self.pattern.TextRange)
-class TextEditPattern():
+class TextEditPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtexteditpattern"""
self.pattern = pattern
@@ -1605,7 +1606,7 @@ class TextEditPattern():
return None
-class TextPattern():
+class TextPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtextpattern"""
self.pattern = pattern
@@ -1630,7 +1631,7 @@ class TextPattern():
"""
return bool(self.pattern.SupportedTextSelection)
- def GetSelection(self) -> List[TextRange]:
+ def GetSelection(self) -> list[TextRange]:
"""
Call IUIAutomationTextPattern::GetSelection.
Return List[TextRange], a list of `TextRange`, represents the currently selected text in a text-based control.
@@ -1645,7 +1646,7 @@ class TextPattern():
return textRanges
return []
- def GetVisibleRanges(self) -> List[TextRange]:
+ def GetVisibleRanges(self) -> list[TextRange]:
"""
Call IUIAutomationTextPattern::GetVisibleRanges.
Return List[TextRange], a list of `TextRange`, disjoint text ranges from a text-based control
@@ -1687,13 +1688,13 @@ class TextPattern():
return None
-class TextPattern2():
+class TextPattern2:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtextpattern2"""
self.pattern = pattern
-class TogglePattern():
+class TogglePattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtogglepattern"""
self.pattern = pattern
@@ -1728,7 +1729,7 @@ class TogglePattern():
return False
-class TransformPattern():
+class TransformPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtransformpattern"""
self.pattern = pattern
@@ -1805,7 +1806,7 @@ class TransformPattern():
return ret
-class TransformPattern2():
+class TransformPattern2:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtransformpattern2"""
self.pattern = pattern
@@ -1877,7 +1878,7 @@ class TransformPattern2():
return ret
-class ValuePattern():
+class ValuePattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationvaluepattern"""
self.pattern = pattern
@@ -1916,7 +1917,7 @@ class ValuePattern():
return ret
-class VirtualizedItemPattern():
+class VirtualizedItemPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationvirtualizeditempattern"""
self.pattern = pattern
@@ -1934,7 +1935,7 @@ class VirtualizedItemPattern():
return ret
-class WindowPattern():
+class WindowPattern:
def __init__(self, pattern=None):
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationwindowpattern"""
self.pattern = pattern
diff --git a/windows_use/vdm/__init__.py b/windows_use/vdm/__init__.py
index bb67a43..0fc537e 100644
--- a/windows_use/vdm/__init__.py
+++ b/windows_use/vdm/__init__.py
@@ -1 +1 @@
-from .core import *
+from .core import * # noqa: F403
diff --git a/windows_use/vdm/core.py b/windows_use/vdm/core.py
index 1c9da1f..6ea42a4 100644
--- a/windows_use/vdm/core.py
+++ b/windows_use/vdm/core.py
@@ -15,7 +15,7 @@ from ctypes import HRESULT, POINTER, byref, c_void_p
from ctypes.wintypes import BOOL, HWND, UINT
import comtypes.client
-from comtypes import COMMETHOD, GUID, IUnknown, STDMETHOD
+from comtypes import COMMETHOD, GUID, STDMETHOD, IUnknown
logger = logging.getLogger(__name__)