Skip to content

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

Python

fix: normalize boolean tool inputs before desktop actions

TorgemanTaraka2427398f697
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c0b979..90c7410 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Fixed
+
+- **Input flags**: Boolean clear, Enter, Ctrl, and drag options now use validated values and defaults through tool dispatch. Legacy desktop `"true"`/`"false"` inputs remain supported, and multi-select releases Ctrl after an action failure.
+
## [0.7.66] - 2026-03-25
### Added
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 4ce228a..3b7abaf 100644
--- a/tests/unit/agent/agent_registry/test_agent_registry_service.py
+++ b/tests/unit/agent/agent_registry/test_agent_registry_service.py
@@ -17,7 +17,7 @@ class TestRegistry:
mock = MagicMock(spec=Tool)
mock.name = "TestTool"
mock.json_schema = {"name": "TestTool", "parameters": {}}
- mock.validate_params.return_value = []
+ mock.validate_and_normalize_params.side_effect = lambda params: (params, [])
mock.invoke.return_value = "Tool execution result"
return mock
@@ -43,7 +43,7 @@ class TestRegistry:
mock_tool.invoke.assert_called_once_with(desktop=mock_desktop, param1="val1")
def test_execute_validation_failure(self, mock_tool):
- mock_tool.validate_params.return_value = ["Invalid param"]
+ mock_tool.validate_and_normalize_params.side_effect = lambda params: ({}, ["Invalid param"])
registry = Registry(tools=[mock_tool])
result = registry.execute("TestTool", tool_params={"param1": "val1"})
diff --git a/tests/unit/agent/agent_tools/test_boolean_inputs.py b/tests/unit/agent/agent_tools/test_boolean_inputs.py
new file mode 100644
index 0000000..f96ee0c
--- /dev/null
+++ b/tests/unit/agent/agent_tools/test_boolean_inputs.py
@@ -0,0 +1,245 @@
+"""Exercise schema-to-desktop boolean handling without sending native input."""
+
+import asyncio
+from unittest.mock import MagicMock, call
+
+import pytest
+from pydantic import ValidationError
+
+import windows_use.agent.desktop.service as desktop_module
+from windows_use.agent.desktop.service import Desktop
+from windows_use.agent.registry.service import Registry
+from windows_use.agent.tools.service import move_tool, multi_edit_tool, multi_select_tool, type_tool
+
+
+def desktop_and_uia(monkeypatch):
+ uia = MagicMock()
+ uia.Keys.VK_CONTROL = 0x11
+ uia.GetCursorPos.return_value = (1, 2)
+ monkeypatch.setattr(desktop_module, "uia", uia)
+ monkeypatch.setattr(desktop_module, "sleep", MagicMock())
+ # These input methods need no initialized tree, windows, or COM resources.
+ return object.__new__(Desktop), uia
+
+
[email protected](params=["sync", "async"])
+def dispatch(request):
+ registry = Registry([type_tool, multi_select_tool, multi_edit_tool, move_tool])
+
+ def run(tool_name, params, desktop):
+ params = {"thought": "Exercise input behavior", **params}
+ if request.param == "sync":
+ return registry.execute(tool_name, params, desktop)
+ return asyncio.run(registry.aexecute(tool_name, params, desktop))
+
+ return run
+
+
+ "clear,press_enter,expected_keys",
+ [
+ (True, True, ["{Ctrl}a", "{Back}", "hello", "{Enter}"]),
+ (True, False, ["{Ctrl}a", "{Back}", "hello"]),
+ (False, True, ["hello", "{Enter}"]),
+ (False, False, ["hello"]),
+ ("true", "true", ["{Ctrl}a", "{Back}", "hello", "{Enter}"]),
+ ("true", "false", ["{Ctrl}a", "{Back}", "hello"]),
+ ("false", "true", ["hello", "{Enter}"]),
+ ("false", "false", ["hello"]),
+ ],
+)
+def test_typing_flags_reach_native_input(
+ dispatch, desktop_and_uia, clear, press_enter, expected_keys
+):
+ desktop, uia = desktop_and_uia
+ result = dispatch(
+ "type_tool",
+ {"loc": [10, 20], "text": "hello", "clear": clear, "press_enter": press_enter},
+ desktop,
+ )
+
+ assert result.is_success
+ uia.Click.assert_called_once_with(10, 20)
+ assert [entry.args[0] for entry in uia.SendKeys.call_args_list] == expected_keys
+
+
+def test_omitted_typing_flags_do_not_clear_or_submit(dispatch, desktop_and_uia):
+ desktop, uia = desktop_and_uia
+ result = dispatch("type_tool", {"loc": [10, 20], "text": "hello"}, desktop)
+
+ assert result.is_success
+ uia.SendKeys.assert_called_once_with("hello", interval=0.01, waitTime=0.05)
+
+
+ "press_ctrl,hold_ctrl", [(True, True), (False, False), ("true", True), ("false", False)]
+)
+def test_multiselect_holds_ctrl_only_when_requested(
+ dispatch, desktop_and_uia, press_ctrl, hold_ctrl
+):
+ desktop, uia = desktop_and_uia
+ result = dispatch(
+ "multi_select_tool",
+ {"elements": [[10, 20], [30, 40]], "press_ctrl": press_ctrl},
+ desktop,
+ )
+
+ assert result.is_success
+ expected = [call.Click(10, 20, waitTime=0.2), call.Click(30, 40, waitTime=0.2)]
+ if hold_ctrl:
+ expected = [
+ call.PressKey(0x11, waitTime=0.05),
+ *expected,
+ call.ReleaseKey(0x11, waitTime=0.05),
+ ]
+ assert uia.method_calls == expected
+
+
+def test_omitted_multiselect_flag_does_not_touch_ctrl(dispatch, desktop_and_uia):
+ desktop, uia = desktop_and_uia
+ result = dispatch("multi_select_tool", {"elements": [[10, 20]]}, desktop)
+
+ assert result.is_success
+ assert uia.method_calls == [call.Click(10, 20, waitTime=0.2)]
+
+
[email protected]("press_ctrl", [True, False])
+def test_multiselect_click_failure_releases_only_ctrl_it_pressed(
+ dispatch, desktop_and_uia, press_ctrl
+):
+ desktop, uia = desktop_and_uia
+ uia.Click.side_effect = RuntimeError("Input failed")
+ result = dispatch(
+ "multi_select_tool",
+ {"elements": [[10, 20]], "press_ctrl": press_ctrl},
+ desktop,
+ )
+
+ assert not result.is_success
+ assert "Input failed" in result.error
+ if press_ctrl:
+ assert uia.method_calls == [
+ call.PressKey(0x11, waitTime=0.05),
+ call.Click(10, 20, waitTime=0.2),
+ call.ReleaseKey(0x11, waitTime=0.05),
+ ]
+ else:
+ assert uia.method_calls == [call.Click(10, 20, waitTime=0.2)]
+
+
+def test_failed_ctrl_press_does_not_click_or_release_an_unheld_key(dispatch, desktop_and_uia):
+ desktop, uia = desktop_and_uia
+ uia.PressKey.side_effect = RuntimeError("Cannot press Ctrl")
+ result = dispatch("multi_select_tool", {"elements": [[10, 20]], "press_ctrl": True}, desktop)
+
+ assert not result.is_success
+ assert "Cannot press Ctrl" in result.error
+ uia.Click.assert_not_called()
+ uia.ReleaseKey.assert_not_called()
+
+
+ "drag,should_drag", [(True, True), (False, False), ("true", True), ("false", False)]
+)
+def test_move_dispatch_uses_normalized_booleans_and_coordinates(
+ dispatch, desktop_and_uia, drag, should_drag
+):
+ desktop, uia = desktop_and_uia
+ # Validation must dispatch its normalized values, not the original strings.
+ result = dispatch("move_tool", {"loc": ["10", "20"], "drag": drag}, desktop)
+
+ assert result.is_success
+ if should_drag:
+ uia.DragTo.assert_called_once_with(1, 2, 10, 20)
+ uia.MoveTo.assert_not_called()
+ else:
+ uia.MoveTo.assert_called_once_with(10, 20, moveSpeed=10)
+ uia.DragTo.assert_not_called()
+
+
+ "tool_name,params",
+ [
+ ("type_tool", {"loc": [10, 20], "text": "hello", "clear": "invalid"}),
+ ("type_tool", {"loc": [10, 20], "text": "hello", "press_enter": None}),
+ ("multi_select_tool", {"elements": [[10, 20]], "press_ctrl": "invalid"}),
+ ("move_tool", {"loc": [10, 20], "drag": "invalid"}),
+ ],
+)
+def test_invalid_boolean_is_rejected_before_input(dispatch, desktop_and_uia, tool_name, params):
+ desktop, uia = desktop_and_uia
+ result = dispatch(tool_name, params, desktop)
+
+ assert not result.is_success
+ assert "validation failed" in result.error
+ assert uia.method_calls == []
+
+
+def test_multi_edit_still_clears_each_field(dispatch, desktop_and_uia):
+ desktop, uia = desktop_and_uia
+ result = dispatch(
+ "multi_edit_tool", {"elements": [[10, 20, "first"], [30, 40, "second"]]}, desktop
+ )
+
+ assert result.is_success
+ assert uia.Click.call_args_list == [call(10, 20), call(30, 40)]
+ assert [entry.args[0] for entry in uia.SendKeys.call_args_list] == [
+ "{Ctrl}a",
+ "{Back}",
+ "first",
+ "{Ctrl}a",
+ "{Back}",
+ "second",
+ ]
+
+
+ "flag,enabled",
+ [
+ (True, True),
+ (False, False),
+ ("true", True),
+ ("false", False),
+ ("TRUE", True),
+ ("FALSE", False),
+ ],
+)
+def test_direct_desktop_flags_are_parsed_before_input(desktop_and_uia, flag, enabled):
+ desktop, uia = desktop_and_uia
+ desktop.type((10, 20), "hello", clear=flag, press_enter=flag)
+ expected_keys = ["{Ctrl}a", "{Back}", "hello", "{Enter}"] if enabled else ["hello"]
+ assert [entry.args[0] for entry in uia.SendKeys.call_args_list] == expected_keys
+
+ uia.reset_mock()
+ desktop.multi_select(press_ctrl=flag, elements=[(10, 20)])
+ assert uia.PressKey.call_count == int(enabled)
+ assert uia.ReleaseKey.call_count == int(enabled)
+
+
[email protected]("flag", ["invalid", None, [], 2])
[email protected]("parameter", ["clear", "press_enter", "press_ctrl"])
+def test_direct_invalid_flags_are_rejected_before_input(desktop_and_uia, parameter, flag):
+ desktop, uia = desktop_and_uia
+
+ with pytest.raises(ValidationError):
+ if parameter == "press_ctrl":
+ desktop.multi_select(elements=[(10, 20)], press_ctrl=flag)
+ else:
+ desktop.type((10, 20), "hello", **{parameter: flag})
+
+ assert uia.method_calls == []
+
+
[email protected]("caret_position", ["none", "idle"])
+def test_direct_typing_accepts_both_unchanged_caret_names(desktop_and_uia, caret_position):
+ desktop, uia = desktop_and_uia
+ desktop.type((10, 20), "hello", caret_position=caret_position)
+ uia.SendKeys.assert_called_once_with("hello", interval=0.01, waitTime=0.05)
+
+
+def test_direct_multiselect_rejects_invalid_coordinates_before_input(desktop_and_uia):
+ desktop, uia = desktop_and_uia
+ with pytest.raises(ValidationError):
+ desktop.multi_select(press_ctrl=True, elements=[(10, 20), 30])
+ assert uia.method_calls == []
diff --git a/windows_use/agent/desktop/service.py b/windows_use/agent/desktop/service.py
index 044f1c7..337c370 100644
--- a/windows_use/agent/desktop/service.py
+++ b/windows_use/agent/desktop/service.py
@@ -19,6 +19,7 @@ from fuzzywuzzy import process
from markdownify import markdownify
from PIL import Image, ImageDraw, ImageFont, ImageGrab
from psutil import Process
+from pydantic import validate_call
import windows_use.uia as uia
from windows_use.agent.desktop.config import KEY_ALIASES
@@ -413,13 +414,14 @@ class Desktop:
for _ in range(clicks):
uia.MiddleClick(x, y)
+ @validate_call
def type(
self,
loc: tuple[int, int],
text: str,
- caret_position: Literal["start", "end", "none"] = "none",
- clear: Literal["true", "false"] = "false",
- press_enter: Literal["true", "false"] = "false",
+ caret_position: Literal["start", "end", "none", "idle"] = "none",
+ clear: bool = False,
+ press_enter: bool = False,
):
x, y = loc
uia.Click(x, y)
@@ -427,13 +429,13 @@ class Desktop:
uia.SendKeys("{Home}", waitTime=0.05)
elif caret_position == "end":
uia.SendKeys("{End}", waitTime=0.05)
- if clear == "true":
+ if clear:
sleep(0.5)
uia.SendKeys("{Ctrl}a", waitTime=0.05)
uia.SendKeys("{Back}", waitTime=0.05)
escaped_text = escape_text_for_sendkeys(text)
uia.SendKeys(escaped_text, interval=0.01, waitTime=0.05)
- if press_enter == "true":
+ if press_enter:
uia.SendKeys("{Enter}", waitTime=0.05)
def scroll(
@@ -489,23 +491,29 @@ class Desktop:
sendkeys_str += "{" + name + "}"
uia.SendKeys(sendkeys_str, interval=0.01)
+ @validate_call
def multi_select(
self,
- press_ctrl: Literal["true", "false"] = "false",
- elements: list[tuple[int, int] | int] = [],
+ press_ctrl: bool = False,
+ elements: list[tuple[int, int]] = [],
):
- if press_ctrl == "true":
- uia.PressKey(uia.Keys.VK_CONTROL, waitTime=0.05)
- for element in elements:
- x, y = element
- uia.Click(x, y, waitTime=0.2)
- sleep(0.5)
- uia.ReleaseKey(uia.Keys.VK_CONTROL, waitTime=0.05)
+ ctrl_pressed = False
+ try:
+ if press_ctrl:
+ uia.PressKey(uia.Keys.VK_CONTROL, waitTime=0.05)
+ ctrl_pressed = True
+ for element in elements:
+ x, y = element
+ uia.Click(x, y, waitTime=0.2)
+ sleep(0.5)
+ finally:
+ if ctrl_pressed:
+ 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")
+ self.type((x, y), text=text, clear=True)
def scrape(self, url: str) -> str:
response = requests.get(url, timeout=10)
diff --git a/windows_use/agent/registry/service.py b/windows_use/agent/registry/service.py
index d019018..f0baac4 100644
--- a/windows_use/agent/registry/service.py
+++ b/windows_use/agent/registry/service.py
@@ -29,14 +29,14 @@ class Registry:
tool = self.get_tool(tool_name)
if not tool:
return ToolResult(is_success=False, error=f"Tool '{tool_name}' not found.")
- errors = tool.validate_params(tool_params)
+ params, errors = tool.validate_and_normalize_params(tool_params)
if errors:
error_msg = "\n".join(errors)
return ToolResult(
is_success=False, error=f"Tool '{tool_name}' validation failed:\n{error_msg}"
)
try:
- content = tool.invoke(**({"desktop": desktop} | tool_params))
+ content = tool.invoke(**(params | {"desktop": desktop}))
return ToolResult(is_success=True, content=content)
except Exception as error:
error_msg = str(error)
@@ -50,14 +50,14 @@ class Registry:
tool = self.get_tool(tool_name)
if not tool:
return ToolResult(is_success=False, error=f"Tool '{tool_name}' not found.")
- errors = tool.validate_params(tool_params)
+ params, errors = tool.validate_and_normalize_params(tool_params)
if errors:
error_msg = "\n".join(errors)
return ToolResult(
is_success=False, error=f"Tool '{tool_name}' validation failed:\n{error_msg}"
)
try:
- content = await tool.ainvoke(**({"desktop": desktop} | tool_params))
+ content = await tool.ainvoke(**(params | {"desktop": desktop}))
return ToolResult(is_success=True, content=content)
except Exception as error:
error_msg = str(error)
diff --git a/windows_use/agent/tools/service.py b/windows_use/agent/tools/service.py
index a8eb485..cceab9d 100644
--- a/windows_use/agent/tools/service.py
+++ b/windows_use/agent/tools/service.py
@@ -392,9 +392,9 @@ async def click_tool(
async def type_tool(
loc: list[int] | None = None,
text: str = "",
- clear: Literal["true", "false"] = "false",
+ clear: bool = False,
caret_position: Literal["start", "idle", "end"] = "idle",
- press_enter: Literal["true", "false"] = "false",
+ press_enter: bool = False,
**kwargs,
):
"""
@@ -470,7 +470,7 @@ async def shortcut_tool(shortcut: str, **kwargs) -> str:
@Tool("multi_select_tool", model=MultiSelect)
async def multi_select_tool(
- press_ctrl: Literal["true", "false"] = "true", elements: list[list[int]] = [], **kwargs
+ press_ctrl: bool = False, elements: list[list[int]] = [], **kwargs
) -> str:
"""
Clicks multiple locations in sequence. With press_ctrl=true, holds Ctrl to accumulate a multi-selection (e.g., selecting multiple files, checkboxes, or list items). With press_ctrl=false, clicks each location independently in order.
diff --git a/windows_use/tools/service.py b/windows_use/tools/service.py
index 56be067..8e08c33 100644
--- a/windows_use/tools/service.py
+++ b/windows_use/tools/service.py
@@ -69,18 +69,24 @@ class Tool(ABC):
}
def validate_params(self, args: dict[str, Any]) -> list[str]:
+ _, errors = self.validate_and_normalize_params(args)
+ return errors
+
+ def validate_and_normalize_params(
+ self, args: dict[str, Any]
+ ) -> tuple[dict[str, Any], list[str]]:
+ """Return the values validated by the schema, including coercions and defaults."""
try:
- self.model(**args)
- return []
+ return self.model(**args).model_dump(), []
except ValidationError as e:
errors = []
for error in e.errors():
field = "".join([str(loc) for loc in error["loc"]])
msg = error["msg"]
errors.append(f"{field}:{msg}")
- return errors
+ return {}, errors
except Exception as e:
- return [str(e)]
+ return {}, [str(e)]
def __call__(self, function):
if self.name is None: