Skip to content

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

Python

fix: preserve task history and report agent failures consistently

TorgemanTarakaedc60b9f4bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c0b979..04f48c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,13 @@ 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
+
+- **Context compaction**: Mixed parameter types, missing content, and large values no longer crash history formatting. Async tasks use async summarization; failed summaries preserve history, and token usage resets between tasks.
+- **Task results**: Caught execution errors return failed results, invalid completion calls cannot report success, and provider errors are reported consistently in both execution modes. Telemetry failures no longer overwrite task outcomes; cancellation still propagates.
+
## [0.7.66] - 2026-03-25
### Added
diff --git a/tests/unit/agent/agent_prompt/test_compaction.py b/tests/unit/agent/agent_prompt/test_compaction.py
new file mode 100644
index 0000000..55951f5
--- /dev/null
+++ b/tests/unit/agent/agent_prompt/test_compaction.py
@@ -0,0 +1,187 @@
+import asyncio
+import json
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from windows_use.agent.context.service import Context
+from windows_use.messages import AIMessage, HumanMessage, ImageMessage, SystemMessage, ToolMessage
+from windows_use.providers.events import LLMEvent, LLMEventType
+from windows_use.providers.views import TokenUsage
+
+
+def context():
+ llm = MagicMock()
+ llm.ainvoke = AsyncMock()
+ return Context(llm=llm)
+
+
+def test_history_preserves_json_parameter_types_and_missing_content(context):
+ params = {
+ "text": "café",
+ "count": 3,
+ "ratio": 0.5,
+ "enabled": True,
+ "disabled": False,
+ "optional": None,
+ "coordinates": [10, 20],
+ "nested": {"items": [None, True, {"label": "Save"}]},
+ "thought": "Continue the task",
+ }
+ message = ToolMessage(id="call_1", name="example_tool", params=params, content=None)
+
+ history = context._format_history_for_compaction([message])
+
+ parameters = next(line for line in history.splitlines() if line.startswith("TOOL CALL"))
+ serialized = parameters.removeprefix("TOOL CALL call_1: example_tool(").removesuffix(")")
+ assert json.loads(serialized) == {
+ key: value for key, value in params.items() if key != "thought"
+ }
+ assert "THOUGHT: Continue the task" in history
+ assert "TOOL RESULT call_1: " in history
+ assert message.params == params
+ assert message.content is None
+
+
+def test_history_handles_message_variants_without_serializing_images(context):
+ image = object()
+ history = context._format_history_for_compaction(
+ [
+ SystemMessage(content="private system instructions"),
+ HumanMessage(content="Original task"),
+ ImageMessage(content="Current screen", images=[image]),
+ AIMessage(content=None),
+ AIMessage(content={"remaining": ["Save", "Verify"]}),
+ ]
+ )
+
+ assert "private system instructions" not in history
+ assert "USER: Original task" in history
+ assert "USER: Current screen" in history
+ assert "ASSISTANT: " in history
+ assert 'ASSISTANT: {"remaining": ["Save", "Verify"]}' in history
+ assert repr(image) not in history
+
+
+ "value",
+ ["x" * 20_000, list(range(10_000)), {"nested": {"text": "x" * 20_000}}],
+ ids=["long-string", "long-list", "nested-object"],
+)
+def test_history_bounds_tool_parameters_thought_and_result(context, value):
+ message = ToolMessage(
+ id="call_1",
+ name="example_tool",
+ params={"large": value, "thought": "t" * 20_000},
+ content="r" * 20_000,
+ )
+
+ history = context._format_history_for_compaction([message])
+
+ assert history.count("...[TRUNCATED]") == 3
+ assert len(history) < 7300
+ assert "TOOL CALL call_1: example_tool(" in history
+ assert "TOOL RESULT call_1:" in history
+ assert message.content == "r" * 20_000
+
+
+def test_history_bounds_many_parameters_as_a_group(context):
+ message = ToolMessage(
+ id="call_1",
+ name="example_tool",
+ params={f"field_{index}": "x" * 100 for index in range(1000)},
+ content="ok",
+ )
+
+ history = context._format_history_for_compaction([message])
+
+ assert "...[TRUNCATED]" in history
+ assert len(history) < 4300
+
+
[email protected]("async_mode", [False, True], ids=["sync", "async"])
+async def test_compaction_uses_matching_provider_and_resets_usage(context, async_mode):
+ event = LLMEvent(
+ type=LLMEventType.TEXT,
+ content=" Saved the draft. Next, verify its contents. ",
+ usage=TokenUsage(total_tokens=500),
+ )
+ context.llm.invoke.return_value = event
+ context.llm.ainvoke.return_value = event
+ context.token_usage = TokenUsage(total_tokens=90_000)
+ messages = [HumanMessage(content="Create a draft")]
+
+ result = await context.acompact(messages) if async_mode else context.compact(messages)
+
+ assert "Saved the draft. Next, verify its contents." in result
+ assert "Don't repeat already completed ACTIONS" in result
+ assert context.token_usage.total_tokens == 0
+ assert messages == [HumanMessage(content="Create a draft")]
+ if async_mode:
+ context.llm.ainvoke.assert_awaited_once()
+ context.llm.invoke.assert_not_called()
+ sent_messages = context.llm.ainvoke.call_args.args[0]
+ else:
+ context.llm.invoke.assert_called_once()
+ context.llm.ainvoke.assert_not_called()
+ sent_messages = context.llm.invoke.call_args.args[0]
+ assert isinstance(sent_messages[0], SystemMessage)
+ assert isinstance(sent_messages[1], HumanMessage)
+ assert "USER: Create a draft" in sent_messages[1].content
+
+
[email protected]("async_mode", [False, True], ids=["sync", "async"])
+ "response",
+ [
+ None,
+ LLMEvent(type=LLMEventType.TEXT, content=None, usage=TokenUsage()),
+ LLMEvent(type=LLMEventType.TEXT, content="", usage=TokenUsage()),
+ LLMEvent(type=LLMEventType.TEXT, content=" \n\t", usage=TokenUsage()),
+ LLMEvent(type=LLMEventType.ERROR, content="Rate limited", usage=TokenUsage()),
+ LLMEvent(type=LLMEventType.TOOL_CALL, content="Unusable answer", usage=TokenUsage()),
+ ],
+ ids=["none", "no-content", "empty", "whitespace", "error", "tool-call"],
+)
+async def test_invalid_summary_preserves_history_and_usage(context, async_mode, response):
+ context.llm.invoke.return_value = response
+ context.llm.ainvoke.return_value = response
+ usage = TokenUsage(total_tokens=90_000)
+ context.token_usage = usage
+ messages = [HumanMessage(content="Original task"), AIMessage(content="Progress")]
+ original = [message.model_copy(deep=True) for message in messages]
+
+ result = await context.acompact(messages) if async_mode else context.compact(messages)
+
+ assert result is None
+ assert messages == original
+ assert context.token_usage == usage
+
+
[email protected]("async_mode", [False, True], ids=["sync", "async"])
+async def test_provider_exception_preserves_history_and_usage(context, async_mode):
+ context.llm.invoke.side_effect = RuntimeError("Provider unavailable")
+ context.llm.ainvoke.side_effect = RuntimeError("Provider unavailable")
+ context.token_usage = TokenUsage(total_tokens=90_000)
+ messages = [HumanMessage(content="Original task")]
+
+ with pytest.raises(RuntimeError, match="Provider unavailable"):
+ if async_mode:
+ await context.acompact(messages)
+ else:
+ context.compact(messages)
+
+ assert messages == [HumanMessage(content="Original task")]
+ assert context.token_usage.total_tokens == 90_000
+
+
+async def test_async_compaction_propagates_cancellation(context):
+ context.llm.ainvoke.side_effect = asyncio.CancelledError
+ context.token_usage = TokenUsage(total_tokens=90_000)
+
+ with pytest.raises(asyncio.CancelledError):
+ await context.acompact([HumanMessage(content="Original task")])
+
+ assert context.token_usage.total_tokens == 90_000
+ context.llm.invoke.assert_not_called()
diff --git a/tests/unit/agent/test_agent_compaction.py b/tests/unit/agent/test_agent_compaction.py
new file mode 100644
index 0000000..7502415
--- /dev/null
+++ b/tests/unit/agent/test_agent_compaction.py
@@ -0,0 +1,155 @@
+"""Exercise history compaction through both real agent loops without desktop actions."""
+
+from collections import deque
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from pydantic import BaseModel
+
+from windows_use.agent.registry.service import Registry
+from windows_use.agent.service import Agent
+from windows_use.agent.tools.service import done_tool
+from windows_use.messages import HumanMessage, SystemMessage, ToolMessage
+from windows_use.providers.events import LLMEvent, LLMEventType, ToolCall
+from windows_use.providers.views import TokenUsage
+from windows_use.tools import Tool
+
+
+class RecordParams(BaseModel):
+ flag: bool
+ count: int
+ coordinates: list[int]
+
+
+@Tool("record_tool", model=RecordParams)
+def record_tool(flag: bool, count: int, coordinates: list[int], **kwargs) -> str:
+ return "recorded completed step"
+
+
+def tool_event(name, params, tokens=0):
+ return LLMEvent(
+ type=LLMEventType.TOOL_CALL,
+ tool_call=ToolCall(id=name, name=name, params=params),
+ usage=TokenUsage(total_tokens=tokens),
+ )
+
+
+def agent_factory():
+ with (
+ patch("windows_use.agent.service.Desktop"),
+ patch("windows_use.agent.service.WatchDog"),
+ patch("windows_use.agent.service.ProductTelemetry"),
+ ):
+
+ def make_agent(llm):
+ agent = Agent(llm=llm, max_steps=3, log_to_console=False, disable_loop_detection=True)
+ agent.context.system = MagicMock(return_value=SystemMessage(content="test system"))
+ agent.context.state = MagicMock(return_value=HumanMessage(content="current UI"))
+ agent.registry = Registry([record_tool, done_tool])
+ return agent
+
+ yield make_agent
+
+
[email protected]("async_mode", [False, True], ids=["sync", "async"])
[email protected]("summary_result", ["valid", "error", "empty", "exception"])
+def test_compaction_preserves_progress_and_failed_history(
+ agent_factory, async_mode, summary_result
+):
+ import asyncio
+
+ task_events = deque(
+ [
+ tool_event("record_tool", {"flag": True, "count": 3, "coordinates": [10, 20]}),
+ tool_event("missing_tool", {"attempt": 2}, tokens=90),
+ tool_event("done_tool", {"answer": "finished", "thought": "verified"}),
+ ]
+ )
+ task_inputs = []
+ summary_inputs = []
+
+ def respond(messages, tools=None):
+ if tools is not None:
+ task_inputs.append([message.model_copy(deep=True) for message in messages])
+ return task_events.popleft()
+ summary_inputs.append([message.model_copy(deep=True) for message in messages])
+ if summary_result == "exception":
+ raise RuntimeError("summary provider unavailable")
+ return LLMEvent(
+ type=LLMEventType.ERROR if summary_result == "error" else LLMEventType.TEXT,
+ content={
+ "valid": "Saved the completed step; missing tool failed",
+ "error": "busy",
+ "empty": " ",
+ }[summary_result],
+ usage=TokenUsage(),
+ )
+
+ llm = MagicMock()
+ llm.model_name = "test-model"
+ llm.provider = "test-provider"
+ llm.get_metadata.return_value.context_window = 100
+ llm.invoke.side_effect = respond
+ llm.ainvoke = AsyncMock(side_effect=respond)
+ agent = agent_factory(llm)
+
+ result = (
+ asyncio.run(agent.ainvoke("complete the task"))
+ if async_mode
+ else agent.invoke("complete the task")
+ )
+
+ assert result.is_done is True
+ assert result.content == "finished"
+ assert len(task_inputs) == 3
+ assert len(summary_inputs) == 1
+ formatted_history = summary_inputs[0][1].content
+ assert "recorded completed step" in formatted_history
+ assert "missing_tool" in formatted_history
+ assert '"count": 3' in formatted_history
+ assert '"flag": true' in formatted_history
+
+ next_messages = task_inputs[2]
+ if summary_result == "valid":
+ assert any(
+ "Saved the completed step" in (message.content or "") for message in next_messages
+ )
+ assert not any(isinstance(message, ToolMessage) for message in next_messages)
+ assert agent.state.error_messages == []
+ else:
+ assert any(
+ isinstance(message, ToolMessage) and message.name == "record_tool"
+ for message in next_messages
+ )
+ assert any(
+ isinstance(message, ToolMessage) and message.name == "missing_tool"
+ for message in next_messages
+ )
+ assert agent.state.error_messages
+ if async_mode:
+ llm.invoke.assert_not_called()
+ assert llm.ainvoke.await_count == 4
+ else:
+ llm.ainvoke.assert_not_called()
+ assert llm.invoke.call_count == 4
+
+
[email protected]("async_mode", [False, True], ids=["sync", "async"])
+def test_new_task_does_not_compact_previous_tasks_token_usage(agent_factory, async_mode):
+ import asyncio
+
+ llm = MagicMock()
+ llm.get_metadata.return_value.context_window = 100
+ completion = tool_event("done_tool", {"answer": "finished", "thought": "verified"}, tokens=90)
+ llm.invoke.return_value = completion
+ llm.ainvoke = AsyncMock(return_value=completion)
+ agent = agent_factory(llm)
+ agent.context.compact = MagicMock(side_effect=AssertionError("stale token usage"))
+ agent.context.acompact = AsyncMock(side_effect=AssertionError("stale token usage"))
+
+ for task in ("first task", "second task"):
+ result = asyncio.run(agent.ainvoke(task)) if async_mode else agent.invoke(task)
+ assert result.is_done is True
+ agent.context.compact.assert_not_called()
+ agent.context.acompact.assert_not_called()
diff --git a/tests/unit/agent/test_agent_results.py b/tests/unit/agent/test_agent_results.py
new file mode 100644
index 0000000..2b47af3
--- /dev/null
+++ b/tests/unit/agent/test_agent_results.py
@@ -0,0 +1,252 @@
+"""Task result contracts without desktop actions, network requests, or telemetry."""
+
+import asyncio
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from windows_use.agent.events import EventType
+from windows_use.agent.registry.views import ToolResult
+from windows_use.agent.service import Agent
+from windows_use.agent.views import AgentResult
+from windows_use.messages import HumanMessage, SystemMessage
+from windows_use.providers.events import LLMEvent, LLMEventType, ToolCall
+from windows_use.providers.views import TokenUsage
+
+
+def tool_call(name="done_tool", **params):
+ return LLMEvent(
+ type=LLMEventType.TOOL_CALL,
+ tool_call=ToolCall(id="call_1", name=name, params={"thought": "Test", **params}),
+ usage=TokenUsage(),
+ )
+
+
+def run_task(agent, asynchronous):
+ if asynchronous:
+ return asyncio.run(agent.ainvoke("A test task"))
+ return agent.invoke("A test task")
+
+
+def agent_factory():
+ with (
+ patch("windows_use.agent.service.Desktop") as desktop_class,
+ patch("windows_use.agent.service.WatchDog"),
+ patch("windows_use.agent.service.ProductTelemetry"),
+ patch("windows_use.agent.service.Context") as context_class,
+ patch("windows_use.agent.service.time.sleep"),
+ patch("asyncio.sleep", new_callable=AsyncMock),
+ ):
+ desktop_class.return_value.use_vision = False
+ context = context_class.return_value
+ context.need_compaction = False
+ context.system.return_value = SystemMessage(content="Test system instructions")
+ context.task.return_value = HumanMessage(content="A test task")
+ context.state.side_effect = lambda **kwargs: HumanMessage(content="A mocked desktop")
+
+ def make_agent(**kwargs):
+ llm = MagicMock()
+ llm.model_name = "test-model"
+ llm.provider = "test-provider"
+ llm.invoke.return_value = tool_call(answer="Finished")
+ llm.ainvoke = AsyncMock(return_value=tool_call(answer="Finished"))
+ events = []
+ agent = Agent(
+ llm=llm,
+ log_to_console=False,
+ disable_loop_detection=True,
+ event_subscriber=events.append,
+ **kwargs,
+ )
+ return agent, events
+
+ yield make_agent
+
+
[email protected]("asynchronous", [False, True])
+def test_unexpected_execution_error_returns_failed_result(agent_factory, asynchronous):
+ agent, events = agent_factory()
+ agent.context.state.side_effect = RuntimeError("Desktop observation failed")
+
+ result = run_task(agent, asynchronous)
+
+ assert isinstance(result, AgentResult)
+ assert result.is_done is False
+ assert result.error == "Desktop observation failed"
+ assert result.content is None
+ assert events[-1].type == EventType.ERROR
+ telemetry_event = agent.telemetry.capture.call_args.args[0]
+ assert telemetry_event.is_success is False
+ assert telemetry_event.error_type == "RuntimeError"
+ agent.watchdog.__exit__.assert_called_once()
+
+
[email protected]("asynchronous", [False, True])
+def test_watchdog_start_failure_returns_failed_result(agent_factory, asynchronous):
+ agent, _ = agent_factory()
+ agent.watchdog.__enter__.side_effect = RuntimeError("Could not start watchdog")
+
+ result = run_task(agent, asynchronous)
+
+ assert result.is_done is False
+ assert result.error == "Could not start watchdog"
+ agent.llm.invoke.assert_not_called()
+ agent.llm.ainvoke.assert_not_called()
+
+
[email protected]("asynchronous", [False, True])
+def test_invalid_done_call_cannot_report_success(agent_factory, asynchronous):
+ agent, events = agent_factory(max_steps=1, max_consecutive_failures=3)
+ invalid_done = tool_call() # Missing the required answer; real registry validation runs.
+ agent.llm.invoke.return_value = invalid_done
+ agent.llm.ainvoke.return_value = invalid_done
+
+ result = run_task(agent, asynchronous)
+
+ assert result.is_done is False
+ assert result.error
+ assert not any(event.type == EventType.DONE for event in events)
+ failures = [event for event in events if event.type == EventType.TOOL_RESULT]
+ assert len(failures) == 1
+ assert failures[0].data["is_success"] is False
+ assert "validation failed" in failures[0].data["content"]
+ assert "answer" in agent.state.error_messages[0].content
+
+
[email protected]("asynchronous", [False, True])
+def test_invalid_done_can_be_corrected_on_next_step(agent_factory, asynchronous):
+ agent, events = agent_factory(max_steps=2)
+ responses = [tool_call(), tool_call(answer="Corrected completion")]
+ agent.llm.invoke.side_effect = responses
+ agent.llm.ainvoke.side_effect = responses
+
+ result = run_task(agent, asynchronous)
+
+ assert result == AgentResult(is_done=True, content="Corrected completion")
+ assert len([event for event in events if event.type == EventType.DONE]) == 1
+
+
[email protected]("asynchronous", [False, True])
+def test_completion_uses_validated_tool_output(agent_factory, asynchronous):
+ agent, events = agent_factory()
+ executed = ToolResult(is_success=True, content="Validated completion")
+ agent.registry.execute = MagicMock(return_value=executed)
+ agent.registry.aexecute = AsyncMock(return_value=executed)
+
+ result = run_task(agent, asynchronous)
+
+ assert result.content == "Validated completion"
+ assert events[-1].data["content"] == "Validated completion"
+
+
[email protected]("asynchronous", [False, True])
[email protected]("detail", ["Provider rate limit reached", None])
+def test_provider_error_events_produce_meaningful_failed_results(
+ agent_factory, asynchronous, detail
+):
+ agent, events = agent_factory(max_consecutive_failures=2)
+ response = LLMEvent(type=LLMEventType.ERROR, content=detail, usage=TokenUsage())
+ agent.llm.invoke.return_value = response
+ agent.llm.ainvoke.return_value = response
+
+ result = run_task(agent, asynchronous)
+
+ assert result.is_done is False
+ expected_detail = detail or "Provider returned an error without details."
+ assert expected_detail in result.error
+ assert events[-1].data["error_source"] == "llm_exhausted_retries"
+ failures = events[-1].data["llm_errors"]
+ assert len(failures) == 2
+ assert [failure["attempt"] for failure in failures] == [1, 2]
+ assert all(failure["error_type"] == "provider_error" for failure in failures)
+ assert all(failure["error"] == expected_detail for failure in failures)
+
+
[email protected]("asynchronous", [False, True])
+def test_text_only_retries_explain_why_completion_failed(agent_factory, asynchronous):
+ agent, _ = agent_factory(max_consecutive_failures=2)
+ response = LLMEvent(type=LLMEventType.TEXT, content="I am done", usage=TokenUsage())
+ agent.llm.invoke.return_value = response
+ agent.llm.ainvoke.return_value = response
+
+ result = run_task(agent, asynchronous)
+
+ assert result.is_done is False
+ assert "text instead of a tool call" in result.error
+ assert "None" not in result.error
+
+
[email protected]("asynchronous", [False, True])
+def test_provider_exceptions_report_each_retry_and_final_failure(agent_factory, asynchronous):
+ agent, events = agent_factory(max_consecutive_failures=2)
+ agent.llm.invoke.side_effect = RuntimeError("Provider unavailable")
+ agent.llm.ainvoke.side_effect = RuntimeError("Provider unavailable")
+
+ result = run_task(agent, asynchronous)
+
+ assert result.is_done is False
+ assert "Provider unavailable" in result.error
+ assert events[-1].data["error_source"] == "llm_exhausted_retries"
+ assert len(events[-1].data["llm_errors"]) == 2
+ assert all(error["error_type"] == "RuntimeError" for error in events[-1].data["llm_errors"])
+
+
[email protected]("asynchronous", [False, True])
+def test_tool_failure_limit_is_enforced(agent_factory, asynchronous):
+ agent, _ = agent_factory(max_steps=5, max_consecutive_failures=2)
+ agent.llm.invoke.return_value = tool_call("click_tool")
+ agent.llm.ainvoke.return_value = tool_call("click_tool")
+ failure = ToolResult(is_success=False, error="Element disappeared")
+ agent.registry.execute = MagicMock(return_value=failure)
+ agent.registry.aexecute = AsyncMock(return_value=failure)
+
+ result = run_task(agent, asynchronous)
+
+ assert result.is_done is False
+ assert "2 consecutive tool failures" in result.error
+ assert "Element disappeared" in result.error
+ action = agent.registry.aexecute if asynchronous else agent.registry.execute
+ assert action.call_count == 2
+
+
[email protected]("asynchronous", [False, True])
[email protected]("operation", ["capture", "flush"])
[email protected]("task_fails", [False, True])
+def test_telemetry_failure_preserves_task_outcome(
+ agent_factory, asynchronous, operation, task_fails
+):
+ agent, _ = agent_factory()
+ getattr(agent.telemetry, operation).side_effect = RuntimeError("Telemetry unavailable")
+ if task_fails:
+ agent.context.state.side_effect = RuntimeError("Original task failure")
+
+ result = run_task(agent, asynchronous)
+
+ if task_fails:
+ assert result == AgentResult(is_done=False, error="Original task failure")
+ else:
+ assert result == AgentResult(is_done=True, content="Finished")
+
+
[email protected]("asynchronous", [False, True])
[email protected]("exception", [KeyboardInterrupt, asyncio.CancelledError])
+def test_cancellation_propagates_and_cleans_up_watchdog(agent_factory, asynchronous, exception):
+ agent, _ = agent_factory()
+ agent.llm.invoke.side_effect = exception()
+ agent.llm.ainvoke.side_effect = exception()
+
+ with pytest.raises(exception):
+ run_task(agent, asynchronous)
+
+ agent.watchdog.__exit__.assert_called_once()
+ agent.telemetry.capture.assert_not_called()
+
+
[email protected]("name", ["max_steps", "max_consecutive_failures"])
[email protected]("limit", [0, -1, 1.5, True])
+def test_invalid_limits_fail_before_desktop_initialization(name, limit):
+ with patch("windows_use.agent.service.Desktop") as desktop:
+ with pytest.raises(ValueError, match=f"{name} must be a positive integer"):
+ Agent(**{name: limit})
+ desktop.assert_not_called()
diff --git a/windows_use/agent/context/service.py b/windows_use/agent/context/service.py
index bba0f2c..e14afc2 100644
--- a/windows_use/agent/context/service.py
+++ b/windows_use/agent/context/service.py
@@ -1,3 +1,4 @@
+import json
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from getpass import getuser
@@ -17,10 +18,23 @@ from windows_use.messages import (
ToolMessage,
)
from windows_use.providers import BaseChatLLM, TokenUsage
+from windows_use.providers.events import LLMEvent, LLMEventType
_template_cache: dict[str, str] = {}
_NON_TOOL_PARAMS = {"thought"}
+_COMPACTION_CONTENT_LIMIT = 2000
+_COMPACTION_PARAMS_LIMIT = 4000
+_COMPACTION_THOUGHT_LIMIT = 1000
+_TRUNCATED = "...[TRUNCATED]"
+
+
+def _bounded_text(value: object, limit: int) -> str:
+ """Render JSON values before truncating, preserving their types in history."""
+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, default=str)
+ if len(text) > limit:
+ return text[: limit - len(_TRUNCATED)] + _TRUNCATED
+ return text
def _load_template(filename: str) -> str:
@@ -87,14 +101,12 @@ class Context:
def _format_history_for_compaction(self, messages: list[BaseMessage]) -> str:
lines = ["Following is the conversation that needs to be compacted:"]
for message in messages:
- content = (
- message.content[:2000] + "...[TRUNCATED]"
- if len(message.content) > 2000
- else message.content
- )
if isinstance(message, SystemMessage):
- pass
- elif isinstance(message, (HumanMessage)):
+ continue
+ content = _bounded_text(
+ message.content if message.content is not None else "", _COMPACTION_CONTENT_LIMIT
+ )
+ if isinstance(message, HumanMessage | ImageMessage):
lines.append(f"USER: {content}")
elif isinstance(message, AIMessage):
lines.append(f"ASSISTANT: {content}")
@@ -103,11 +115,11 @@ class Context:
name = message.name
params = message.params
if "thought" in params:
- lines.append(f"THOUGHT: {params['thought']}")
- 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
+ thought = _bounded_text(params["thought"], _COMPACTION_THOUGHT_LIMIT)
+ lines.append(f"THOUGHT: {thought}")
+ parts = _bounded_text(
+ {k: v for k, v in params.items() if k not in _NON_TOOL_PARAMS},
+ _COMPACTION_PARAMS_LIMIT,
)
lines.append(f"TOOL CALL {id}: {name}({parts})")
lines.append(f"TOOL RESULT {id}: {content}")
@@ -126,12 +138,33 @@ class Context:
self,
messages: list[BaseMessage],
) -> str | None:
+ """Summarize history, returning None when the provider gives no usable text."""
+ llm_response = self.llm.invoke(self._compaction_messages(messages))
+ return self._format_compaction_response(llm_response)
+
+ async def acompact(self, messages: list[BaseMessage]) -> str | None:
+ """Summarize history without making a synchronous provider call."""
+ llm_response = await self.llm.ainvoke(self._compaction_messages(messages))
+ return self._format_compaction_response(llm_response)
+
+ def _compaction_messages(self, messages: list[BaseMessage]) -> list[BaseMessage]:
template = _load_template("compact.md")
- compaction_messages = [
+ return [
SystemMessage(content=template),
HumanMessage(content=self._format_history_for_compaction(messages)),
]
- llm_response = self.llm.invoke(compaction_messages)
+
+ def _format_compaction_response(self, response: LLMEvent | None) -> str | None:
+ if (
+ response is None
+ or response.type != LLMEventType.TEXT
+ or not isinstance(response.content, str)
+ or not response.content.strip()
+ ):
+ return None
+ # The previous request's token count no longer describes the compacted history.
+ self.token_usage = TokenUsage()
+ summary = response.content.strip()
return f"""
# Context Restoration (Previous Session Compacted)
@@ -141,7 +174,7 @@ The previous conversation was compacted due to context window limitations. Below
---
-{llm_response.content}
+{summary}
---
diff --git a/windows_use/agent/service.py b/windows_use/agent/service.py
index 1e58234..7fe8deb 100644
--- a/windows_use/agent/service.py
+++ b/windows_use/agent/service.py
@@ -27,6 +27,7 @@ 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.providers.views import TokenUsage
from windows_use.telemetry.service import ProductTelemetry
from windows_use.telemetry.views import AgentTelemetryEvent
@@ -98,6 +99,13 @@ class Agent(BaseAgent):
experimental: Whether to include experimental tools. Defaults to False.
disable_loop_detection: Whether to disable loop detection. Defaults to False.
"""
+ for name, limit in (
+ ("max_steps", max_steps),
+ ("max_consecutive_failures", max_consecutive_failures),
+ ):
+ if type(limit) is not int or limit <= 0:
+ raise ValueError(f"{name} must be a positive integer")
+
self.name = "Windows Use"
self.description = "An agent that can interact with GUI elements on Windows OS"
self.mode = mode
@@ -171,6 +179,46 @@ class Agent(BaseAgent):
desktop=self.desktop,
)
+ def _emit_llm_error(self, step: int, attempt: int, error: str, error_type: str) -> dict:
+ data = {
+ "step": step,
+ "attempt": attempt + 1,
+ "provider": self.llm.provider,
+ "model": self.llm.model_name,
+ "error_type": error_type,
+ "error": error,
+ }
+ self.event.emit(AgentEvent(type=EventType.ERROR, data=data))
+ return data
+
+ def _capture_result(
+ self,
+ result: AgentResult,
+ exception: Exception | None = None,
+ error_traceback: str | None = None,
+ ) -> None:
+ """Record telemetry without changing the task's outcome if telemetry fails."""
+ try:
+ self.telemetry.capture(
+ AgentTelemetryEvent(
+ query=self.state.task,
+ steps=self.state.step,
+ max_steps=self.state.max_steps,
+ model=getattr(self.llm, "model_name", "unknown"),
+ provider=getattr(self.llm, "provider", "unknown"),
+ use_vision=self.desktop.use_vision,
+ answer=result.content,
+ error=result.error,
+ error_type=type(exception).__name__ if exception else None,
+ error_traceback=error_traceback,
+ version=_get_package_version(),
+ is_success=result.is_done,
+ )
+ )
+ self.telemetry.flush()
+ except Exception:
+ logger.warning("Unable to record agent telemetry.")
+
def loop(self) -> AgentResult:
"""Run the main agent loop.
@@ -190,9 +238,19 @@ class Agent(BaseAgent):
if self.context.need_compaction:
messages = self.state.messages + self.state.error_messages
- if content := self.context.compact(messages):
- self.state.messages = [self.system_message, HumanMessage(content=content)]
- self.state.error_messages.clear()
+ try:
+ content = self.context.compact(messages)
+ except Exception as error:
+ self.event.emit(
+ AgentEvent(
+ type=EventType.ERROR,
+ data={"step": step, "error": str(error), "error_source": "compaction"},
+ )
+ )
+ else:
+ if content:
+ self.state.messages = [self.system_message, HumanMessage(content=content)]
+ self.state.error_messages.clear()
# Check for loops and build state message with nudge
nudge = None if self.disable_loop_detection else self._loop_guard.check()
@@ -218,7 +276,7 @@ class Agent(BaseAgent):
# Reason: call LLM, retry on failure, return ToolMessage
message: ToolMessage | None = None
- last_error: Exception | None = None
+ last_error: str | None = None
llm_errors: list[dict] = []
for attempt in range(self.state.max_consecutive_failures):
try:
@@ -238,6 +296,7 @@ class Agent(BaseAgent):
)
break
case LLMEventType.TEXT:
+ last_error = "Provider returned text instead of a tool call."
ai_message = AIMessage(content=llm_event.content)
human_message = HumanMessage(
content="Response rejected, please use the `done_tool` to respond to the user."
@@ -245,31 +304,18 @@ class Agent(BaseAgent):
self.state.error_messages.extend([ai_message, human_message])
continue
case LLMEventType.ERROR:
- # Emit LLM error event
- llm_error_data = {
- "step": step,
- "attempt": attempt + 1,
- "provider": self.llm.provider,
- "model": self.llm.model_name,
- "error_type": type(llm_event).__name__,
- "error": str(llm_event),
- }
- self.event.emit(AgentEvent(type=EventType.ERROR, data=llm_error_data))
- llm_errors.append(llm_error_data)
+ last_error = (
+ llm_event.content or "Provider returned an error without details."
+ )
+ llm_errors.append(
+ self._emit_llm_error(step, attempt, last_error, "provider_error")
+ )
continue
except Exception as e:
- last_error = e
- # Emit LLM error event for exception
- llm_error_data = {
- "step": step,
- "attempt": attempt + 1,
- "provider": self.llm.provider,
- "model": self.llm.model_name,
- "error_type": type(e).__name__,
- "error": str(e),
- }
- self.event.emit(AgentEvent(type=EventType.ERROR, data=llm_error_data))
- llm_errors.append(llm_error_data)
+ last_error = str(e) or type(e).__name__
+ llm_errors.append(
+ self._emit_llm_error(step, attempt, last_error, type(e).__name__)
+ )
if attempt < self.state.max_consecutive_failures - 1:
wait_time = 2 ** (attempt + 1)
@@ -346,7 +392,7 @@ class Agent(BaseAgent):
message.content = content
self.state.error_messages.append(message)
- if tool_name != "done_tool":
+ if tool_name != "done_tool" or not tool_result.is_success:
self.event.emit(
AgentEvent(
type=EventType.TOOL_RESULT,
@@ -373,8 +419,8 @@ class Agent(BaseAgent):
else:
consecutive_failures = 0
- if tool_name == "done_tool":
- content = tool_params.get("answer", "")
+ if tool_name == "done_tool" and tool_result.is_success:
+ content = tool_result.content
self.event.emit(
AgentEvent(type=EventType.DONE, data={"step": step, "content": content})
)
@@ -389,50 +435,25 @@ class Agent(BaseAgent):
def invoke(self, task: str) -> AgentResult:
self.state.reset()
self.state.task = task
+ self.context.token_usage = TokenUsage()
try:
with self.desktop.auto_minimize() if self.auto_minimize else nullcontext():
self.watchdog.set_focus_callback(self.desktop.tree.on_focus_change)
with self.watchdog:
result = self.loop()
- self.telemetry.capture(
- AgentTelemetryEvent(
- query=task,
- steps=self.state.step,
- max_steps=self.state.max_steps,
- model=self.llm.model_name,
- provider=self.llm.provider,
- use_vision=self.desktop.use_vision,
- answer=result.content,
- error=result.error,
- version=_get_package_version(),
- is_success=result.is_done,
- )
- )
- self.telemetry.flush()
- return result
except Exception as e:
+ error = str(e) or type(e).__name__
self.event.emit(
AgentEvent(
type=EventType.ERROR,
- data={"step": self.state.step, "error": str(e)},
- )
- )
- self.telemetry.capture(
- AgentTelemetryEvent(
- query=task,
- steps=self.state.step,
- max_steps=self.state.max_steps,
- model=self.llm.model_name,
- provider=self.llm.provider,
- use_vision=self.desktop.use_vision,
- error=str(e),
- error_type=type(e).__name__,
- error_traceback=traceback.format_exc(),
- version=_get_package_version(),
- is_success=False,
+ data={"step": self.state.step, "error": error},
)
)
- self.telemetry.flush()
+ result = AgentResult(is_done=False, error=error)
+ self._capture_result(result, exception=e, error_traceback=traceback.format_exc())
+ else:
+ self._capture_result(result)
+ return result
async def aloop(self) -> AgentResult:
"""Run the main agent loop asynchronously."""
@@ -448,9 +469,19 @@ class Agent(BaseAgent):
if self.context.need_compaction:
messages = self.state.messages + self.state.error_messages
- if content := self.context.compact(messages):
- self.state.messages = [self.system_message, HumanMessage(content=content)]
- self.state.error_messages.clear()
+ try:
+ content = await self.context.acompact(messages)
+ except Exception as error:
+ self.event.emit(
+ AgentEvent(
+ type=EventType.ERROR,
+ data={"step": step, "error": str(error), "error_source": "compaction"},
+ )
+ )
+ else:
+ if content:
+ self.state.messages = [self.system_message, HumanMessage(content=content)]
+ self.state.error_messages.clear()
# Check for loops and build state message with nudge
nudge = None if self.disable_loop_detection else self._loop_guard.check()
@@ -475,7 +506,8 @@ class Agent(BaseAgent):
self._loop_guard.record_state(self.desktop.desktop_state)
message: ToolMessage | None = None
- last_error: Exception | None = None
+ last_error: str | None = None
+ llm_errors: list[dict] = []
for attempt in range(self.state.max_consecutive_failures):
try:
messages = list(chain(self.state.messages, self.state.error_messages))
@@ -494,14 +526,26 @@ class Agent(BaseAgent):
)
break
case LLMEventType.TEXT:
+ last_error = "Provider returned text instead of a tool call."
ai_message = AIMessage(content=llm_event.content)
human_message = HumanMessage(
content="Response rejected, please use the `done_tool` to respond to the user."
)
self.state.error_messages.extend([ai_message, human_message])
continue
+ case LLMEventType.ERROR:
+ last_error = (
+ llm_event.content or "Provider returned an error without details."
+ )
+ llm_errors.append(
+ self._emit_llm_error(step, attempt, last_error, "provider_error")
+ )
+ continue
except Exception as e:
- last_error = e
+ last_error = str(e) or type(e).__name__
+ llm_errors.append(
+ self._emit_llm_error(step, attempt, last_error, type(e).__name__)
+ )
if attempt < self.state.max_consecutive_failures - 1:
wait_time = 2 ** (attempt + 1)
logger.error(
@@ -520,7 +564,15 @@ class Agent(BaseAgent):
if message is None:
error = f"Agent failed after exhausting retries: {last_error}"
self.event.emit(
- AgentEvent(type=EventType.ERROR, data={"step": step, "error": error})
+ AgentEvent(
+ type=EventType.ERROR,
+ data={
+ "step": step,
+ "error": error,
+ "llm_errors": llm_errors,
+ "error_source": "llm_exhausted_retries",
+ },
+ )
)
return AgentResult(is_done=False, error=error)
@@ -569,7 +621,7 @@ class Agent(BaseAgent):
message.content = content
self.state.error_messages.append(message)
- if tool_name != "done_tool":
+ if tool_name != "done_tool" or not tool_result.is_success:
self.event.emit(
AgentEvent(
type=EventType.TOOL_RESULT,
@@ -596,8 +648,8 @@ class Agent(BaseAgent):
else:
consecutive_failures = 0
- if tool_name == "done_tool":
- content = tool_params.get("answer", "")
+ if tool_name == "done_tool" and tool_result.is_success:
+ content = tool_result.content
self.event.emit(
AgentEvent(type=EventType.DONE, data={"step": step, "content": content})
)
@@ -612,47 +664,22 @@ class Agent(BaseAgent):
async def ainvoke(self, task: str) -> AgentResult:
self.state.reset()
self.state.task = task
+ self.context.token_usage = TokenUsage()
try:
with self.desktop.auto_minimize() if self.auto_minimize else nullcontext():
self.watchdog.set_focus_callback(self.desktop.tree.on_focus_change)
with self.watchdog:
result = await self.aloop()
- self.telemetry.capture(
- AgentTelemetryEvent(
- query=task,
- steps=self.state.step,
- max_steps=self.state.max_steps,
- model=self.llm.model_name,
- provider=self.llm.provider,
- use_vision=self.desktop.use_vision,
- answer=result.content,
- error=result.error,
- version=_get_package_version(),
- is_success=result.is_done,
- )
- )
- self.telemetry.flush()
- return result
except Exception as e:
+ error = str(e) or type(e).__name__
self.event.emit(
AgentEvent(
type=EventType.ERROR,
- data={"step": self.state.step, "error": str(e)},
+ data={"step": self.state.step, "error": error},
)
)
- self.telemetry.capture(
- AgentTelemetryEvent(
- query=task,
- steps=self.state.step,
- max_steps=self.state.max_steps,
- model=self.llm.model_name,
- provider=self.llm.provider,
- use_vision=self.desktop.use_vision,
- error=str(e),
- error_type=type(e).__name__,
- error_traceback=traceback.format_exc(),
- version=_get_package_version(),
- is_success=False,
- )
- )
- self.telemetry.flush()
+ result = AgentResult(is_done=False, error=error)
+ self._capture_result(result, exception=e, error_traceback=traceback.format_exc())
+ else:
+ self._capture_result(result)
+ return result