Metadata-Version: 2.4
Name: easy-uiauto
Version: 1.1.6
Summary: Windows GUI automation with reusable controls, workflows, and a shared knowledge vault
Author-email: Poggi-Tang <2322806855@qq.com>
License-Expression: LicenseRef-easy-uiauto-Personal-Enterprise
Project-URL: Homepage, https://github.com/Poggi-Tang/easyautomation
Project-URL: Repository, https://github.com/Poggi-Tang/easyautomation.git
Project-URL: Issues, https://github.com/Poggi-Tang/easyautomation/issues
Project-URL: Changelog, https://github.com/Poggi-Tang/easyautomation/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/Poggi-Tang/easyautomation/blob/main/README.md
Keywords: auto,ui,uiauto,automation,gui-testing
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyautogui>=0.9.54
Requires-Dist: pynput>=1.8.1
Requires-Dist: uiautomation>=2.0.29
Requires-Dist: pyperclip>=1.8.0
Requires-Dist: build>=1.4.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Provides-Extra: mcp
Requires-Dist: mcp[cli]<2.0.0,>=1.0.0; extra == "mcp"
Provides-Extra: vision
Requires-Dist: opencv-python>=4.8; extra == "vision"
Requires-Dist: pytesseract>=0.3.10; extra == "vision"
Provides-Extra: gui
Requires-Dist: pypdf<7,>=5; extra == "gui"
Requires-Dist: pypdfium2<6,>=4.30; extra == "gui"
Requires-Dist: PySide6-Essentials<6.11,>=6.10; extra == "gui"
Requires-Dist: Pillow>=10.0; extra == "gui"
Requires-Dist: numpy>=1.26; extra == "gui"
Requires-Dist: opencv-python>=4.8; extra == "gui"
Provides-Extra: image
Requires-Dist: torch>=2.0; extra == "image"
Requires-Dist: rapidocr==3.10.0; extra == "image"
Requires-Dist: onnxruntime>=1.20; extra == "image"
Requires-Dist: Pillow>=10.0; extra == "image"
Requires-Dist: numpy>=1.26; extra == "image"
Requires-Dist: opencv-python>=4.8; extra == "image"
Provides-Extra: full
Requires-Dist: pypdf<7,>=5; extra == "full"
Requires-Dist: pypdfium2<6,>=4.30; extra == "full"
Requires-Dist: PySide6-Essentials<6.11,>=6.10; extra == "full"
Requires-Dist: mcp[cli]<2.0.0,>=1.0.0; extra == "full"
Requires-Dist: opencv-python>=4.8; extra == "full"
Requires-Dist: pytesseract>=0.3.10; extra == "full"
Requires-Dist: torch>=2.0; extra == "full"
Requires-Dist: rapidocr==3.10.0; extra == "full"
Requires-Dist: onnxruntime>=1.20; extra == "full"
Requires-Dist: Pillow>=10.0; extra == "full"
Requires-Dist: numpy>=1.26; extra == "full"
Dynamic: license-file

# easy-uiauto

English | [简体中文](README.zh-CN.md)

[![PyPI](https://img.shields.io/pypi/v/easy_uiauto?cacheSeconds=300)](https://pypi.org/project/easy-uiauto/)
[![Python](https://img.shields.io/pypi/pyversions/easy-uiauto?cacheSeconds=300)](https://pypi.org/project/easy-uiauto/)
[![License](https://img.shields.io/badge/license-Personal_free_%2F_Enterprise_paid-blue)](LICENSE)
[![CI](https://github.com/Poggi-Tang/easyautomation/actions/workflows/ci.yml/badge.svg)](https://github.com/Poggi-Tang/easyautomation/actions/workflows/ci.yml)
[![Publish](https://github.com/Poggi-Tang/easyautomation/actions/workflows/publish.yml/badge.svg)](https://github.com/Poggi-Tang/easyautomation/actions/workflows/publish.yml)

![logo](https://github.com/Poggi-Tang/easyautomation/blob/main/src/image/easy-uiauto.png)

Learn Windows applications in a GUI and save their controls and workflows for reuse by people and agents.

Select a window, mark regions, learn controls, compose workflows, and run them again.
The GUI, MCP and Python share one local Markdown knowledge vault, including manual edits
and learned results. Current version: **1.1.6**. Windows only. The GUI is primarily
Chinese; documentation is available in English and Chinese.

**Free for individuals; enterprise use requires a paid license.** The same policy
covers the GUI, MCP, Python API and bundled tools. Custom development, deployment,
knowledge and workflow configuration, automation solutions, training and maintenance
are separately scoped services. See [licensing and commercial services](docs/commercial-services.md).

## From an interface to reusable workflows

1. **Select an application**: open the target software, add it in the GUI and bind its window.
2. **Mark regions**: outline menus, toolbars or project trees and describe their purpose.
3. **Learn controls**: basic learning reads the visible region. Use deep learning on a region or a single control to explore menus and dialogs. Add missing controls or correct their names and descriptions manually.
4. **Compose workflows**: combine control operations with parameters, ordered steps and checks. Deep learning also archives the workflows it explores.
5. **Run and reuse**: execute a workflow in the GUI or call the same controls and workflows from an agent or Python. Resume incomplete learning, improve results or adapt them after a software update.

See the [GUI guide](docs/knowledge-gui.zh-CN.md) for detailed steps. Choose an integration when needed:

| Entry point | Purpose |
| --- | --- |
| GUI | Manage applications, regions, controls, references and workflows |
| MCP + Skill | Let an agent learn from manual input, maintain knowledge and execute tasks |
| Python API | Schedule controls and workflows from your own program |
| CLI / TCP service | Call learned application commands from a shell or another process |

## Local processing, models and offline use

| Feature | Model API requirement | Network use and data sent |
| --- | --- | --- |
| GUI editing, manual controls, composing and running saved workflows | None | Local execution; the target application may itself need a network |
| Image annotation, YOLO detection, RapidOCR text recognition | None | Offline after the model files are installed |
| GUI basic learning | None for local scanning; required for added semantic descriptions | Local scanning; enabling API descriptions sends window images and control information |
| Importing and understanding references, reference-assisted descriptions | Required | Local extraction; reference excerpts and relevant control information go to the API for interpretation. Import currently includes interpretation |
| Deep learning of a region or single control | Multimodal model with image input and JSON output | Screenshots, task context and relevant test inputs go to the API to plan interactions |
| CLI / MCP visual-first scanning and effect interpretation | Multimodal model | Selected-window images, or before/after images and related popup crops |
| Remote vision lookup fallback | Required only when explicitly enabled | Sends the requested screenshot area; UIA, templates and local OCR need no API |

**The offline bundle includes runtimes, detection and OCR models, but no semantic reasoning service.**
The API can be a cloud, intranet or local OpenAI-compatible service. API-dependent features avoid
public Internet access only when that endpoint is also local or on your intranet. YOLO and OCR
detect elements and read text; they do not plan workflows. Vault files contain interface text,
screenshots and reference material as ordinary local files. See [models, offline use and keys](docs/model-and-privacy.md).

## Start the GUI from this repository

For a ready-to-use offline copy, download the complete GUI ZIP from the
[latest release](https://github.com/Poggi-Tang/easyautomation/releases/latest),
extract it and double-click `setup.bat`.

On Windows x64, clone the repository's default **`main` branch** and double-click `setup.bat`:

```cmd
git clone https://github.com/Poggi-Tang/easyautomation.git
cd easyautomation
setup.bat
```

Alternatively, choose **Code → Download ZIP** on the default `main` branch, extract
it, and double-click `setup.bat`. No Python or developer tools need to be installed
beforehand. The first run needs Internet access to install a dedicated Python,
the GUI dependencies and local OCR/YOLO models; it then creates a desktop shortcut
and opens the GUI. Windows may request administrator approval.

The default installation is `%LOCALAPPDATA%\easy-uiauto\gui`. To choose another
directory, run `setup.bat -Target "D:\easy-uiauto-gui"`. Later, use the desktop
shortcut to open the GUI; after `git pull`, run `setup.bat` again to update it.
The GUI setup does not register MCP clients or change user PATH. The default
`main` branch includes the GUI, MCP and Python API; `uiauto-gui` is used for GUI development.
PyPI releases from 1.0.0 include the GUI. See the [GUI guide](docs/knowledge-gui.zh-CN.md).

## Overview

`easy-uiauto` combines a Python automation library, an MCP server, action
recording, and an Obsidian-compatible UI knowledge vault. It can locate controls
through Windows UI Automation, save controls from visible application regions,
and generate commands such as
`main.keypad.enter-digit-6.click`.

Use it to record desktop operations, write automated tests, or give an agent access
to saved controls and workflows. Version `1.1.5` locates deep-learning regions by
UI Automation properties or a unique reference-image match instead of saved
coordinates. It also improves exploration of editable controls and generates
control descriptions in Simplified Chinese. See the [release notes](CHANGELOG.md).

Saved-image annotation uses **YOLO + RapidOCR** by default: provide an image path and
an output directory to receive separate text, graphic and combined annotation
images, coordinates, recognition evidence and a local HTML viewer.

> Visual scanning and workflow exploration are still evolving. Review learned
> commands before using them for messages, payments, deletion, uploads, account
> changes, or other operations with external effects.

## What It Includes

- **Knowledge GUI**: select a software window, mark regions, and learn their controls.
  Keep separate Tab states, edit names and descriptions, import manuals, and compose
  workflows with parameters and checks. Saved learning images and execution results
  are shown separately. See the [GUI guide](docs/knowledge-gui.zh-CN.md).
- **Two region learning modes**: basic learning scans the visible region and analyzes
  semantics without interacting. Deep learning follows interaction branches and
  archives new regions, controls and workflows. Entrances that converge on the same
  state reference shared workflow steps. Unfinished branches retain their reasons.
  Relearning can continue unfinished branches, improve selected controls/workflows,
  or adapt to software updates while retaining manual edits and reporting validation results.
  Deep learning requires the configured API; required business inputs must be supplied.
  Local searches may use observed item names. Coverage is checked per control action,
  with omitted actions sent back for planning and retained as incomplete if unresolved.
  Input probes retain their live original values for verified restoration. A result state
  does not exempt its remaining actions from exploration. Creating or saving test data
  is an explicit option in the dialog.
  Select a saved control and use its toolbar or context menu to explore just that
  entry and its subsequent workflows, with a separate resumable learning record.

- **Desktop automation**: click, double-click, right-click, drag, scroll,
  keyboard input, hotkeys, window activation, and text entry.
- **Action recording**: record real operations, highlight the selected control,
  and generate reusable Python actions with a complete `LOCATION`.
- **MCP server**: call automation tools from Codex, Claude Code, DeepSeek Harness (DSH),
  or another MCP client. Agents can learn into existing GUI regions and save workflows
  in the same knowledge vault.
- **Visual-first learning**: identify the important regions and controls in one
  screenshot, then map them back to stable local UIA controls without walking the
  whole tree by default.
- **Control metadata**: store names, aliases, current values and relationships.
  Generated descriptions can explain visible states, such as a disabled Send button;
  inferred descriptions remain separate from observed behavior.
- **Semantic UI CLI**: turn verified controls into searchable application
  commands instead of rediscovering coordinates for every task.
- **Control overlays**: number every learned or executable control in one
  click-through overlay, save annotated page images, and preview operation targets.
- **Local image annotation**: YOLO selects CPU or NVIDIA GPU automatically; RapidOCR uses CPU, without a vision API;
  export blue `G` graphics and orange `T` text with one-pixel boxes, adjacent IDs,
  local geometry correction and automatic small-text recovery.
- **Effect learning**: compare before/after screenshots, inspect changed UIA
  properties and new windows, and save the observed result and success condition.
- **Readable knowledge**: keep pages, controls, images, interactions, and
  quarantine records as Markdown/YAML/PNG files that work directly with Obsidian
  and version control.
- **Stable records**: persist structured `LOCATION` identities and normalized
  visual hints, never process IDs, window handles, or absolute desktop rectangles.
- **Layered lookup**: contextual XPath with explicit selection modes, property
  combinations, saved image states, local OCR, then opt-in remote vision.
- **Selection modes**: return the first matching `Name` by default, or select a
  same-type sibling by `foundIndex`; ID-only selectors remain available.

## Capability Status

| Area | Status | Notes |
| --- | --- | --- |
| Python mouse, keyboard, window, and UIA APIs | Stable | Core automation APIs |
| Recording and replay | Stable | Produces reusable structured actions |
| MCP tools and client setup | Beta | Codex and Claude Code installers included |
| GUI region learning and workflows | Beta | Local YOLO + RapidOCR; reference-assisted descriptions use the configured API |
| GUI deep learning | Experimental | API-planned branches, automatic archiving, shared workflows and resumable progress |
| Visual-first scan and generated UI CLI | Beta | Requires an OpenAI-compatible vision endpoint |
| Local image annotation | Experimental | YOLO + RapidOCR; no API key; supports software screenshots and model diagrams |
| Before/after effect learning | Beta | Stores local evidence and learned success conditions |
| Recursive workflow exploration | Experimental | Restricted to reversible commands and bounded depth |

Automated workflow exploration intentionally excludes scrolling and dragging.
The base automation library still provides those operations for explicit scripts
and direct MCP calls.

## Installation

### Complete installation and offline deployment

On Windows x64, download and double-click [install-full.cmd](https://github.com/Poggi-Tang/easyautomation/releases/latest/download/install-full.cmd).
It installs a dedicated Python runtime, all Python dependencies, CPU PyTorch,
YOLO weights, RapidOCR, portable Tesseract with English/Chinese language data,
the configuration app and skills, then registers available MCP clients.
No existing Python installation is required. The installer verifies dependencies,
OCR recognition and YOLO inference before reporting success.

For offline deployment, [download the complete ZIP](https://github.com/Poggi-Tang/easyautomation/releases/latest/download/easy-uiauto-offline-win-x64.zip),
copy it to the offline PC, extract it, and double-click `install-offline.cmd`.

To prepare the ZIP yourself on a connected Windows PC, download and run
[download-offline.cmd](https://github.com/Poggi-Tang/easyautomation/releases/latest/download/download-offline.cmd).
The ZIP and SHA256 file are saved to `%USERPROFILE%\Downloads\easy-uiauto-offline`.

In a checkout, the installers build and use that checkout's wheel, including
unreleased GUI changes. Use `-Wheel` to supply an existing wheel explicitly.
Standalone release installers continue to use the corresponding PyPI release.
For GUI use without MCP, PATH or skill integration, double-click `setup.bat`.

From a repository checkout, you can specify directories:

```cmd
install-full.cmd -Target "D:\easy-uiauto"
download-offline.cmd -Output "D:\offline-packages"
```

The default installation is `%LOCALAPPDATA%\easy-uiauto\full`. Run
`easy_uiauto_config.cmd` there to configure the knowledge directory and remote API,
or `easy_uiauto_image.cmd` to annotate images. `activate.cmd` activates the environment
in an existing CMD window. `-Client none` skips MCP registration; `-NoIntegrate`
also skips user PATH and skill installation. Microsoft Visual C++ Runtime is
included and installed when missing; Windows may request administrator approval.

For an existing Python environment, install all Python dependencies with the
`full` extra, then use the setup command to prepare the complete runtime:

```cmd
python -m pip install -U "easy-uiauto[full]"
easy_uiauto_setup install
easy_uiauto_setup download "D:\offline-packages"
```

### Basic Python package

Requirements: Windows and Python 3.11 or newer.

Install from PyPI:

```bash
pip install easy-uiauto
```

Or install from source:

```bash
git clone https://github.com/Poggi-Tang/easyautomation.git
cd easyautomation
pip install -e .
```

For local image annotation, install the `image` extra and run:

```cmd
python -m pip install "easy-uiauto[image]"
easy_uiauto_image "C:\images\input.bmp" "C:\images\results"
```

Each run creates a result subdirectory containing `text.png`, `controls.png`,
`combined.png`, `elements.json`, `elements.csv`, diagnostics and `index.html`.
Open `index.html` after completion to view the results. Models run locally, with
CPU or NVIDIA GPU for YOLO; weights are downloaded and verified on first use. The default profile
is `ui` for ordinary software screenshots; use `--profile block-diagram` for
control and electrical model diagrams. See
[local image annotation from CMD](#local-image-annotation-from-cmd) for details.

## MCP Setup

Install the optional MCP dependencies when using easy-uiauto from an MCP client:

```bash
pip install "easy-uiauto[mcp]"
```

Install local OCR and image-template fallback support when needed:

```bash
pip install "easy-uiauto[mcp,vision]"
```

The `vision` extra provides OpenCV template matching and the Python Tesseract
adapter. OCR also requires the system Tesseract executable and relevant language
data (for example `eng` or `chi_sim`). The MCP tools are
`find_control_by_image`, `click_by_image`, `find_text_on_screen`, and
`click_text_on_screen`.

For ordinary Python code, install only the local vision extra and call the
rectangle segmenter directly. It does not start MCP, call OCR, or upload data:

```bash
pip install "easy-uiauto[vision]"
```

```python
from easy_uiauto.visual import segment_screen_rect

result = segment_screen_rect(
    {"left": 100, "top": 200, "right": 900, "bottom": 800},
    min_width=6,
    min_height=6,
    save_annotated=True,
)
for box in result["boxes"]:
    print(box["rect"], box["parent_id"])
print(result["relations"], result["groups"])
```

For a coarse UIA canvas whose internal elements have no UIA nodes, pass the
control result or its bounds directly to the local rectangle detector:

```text
get_control_at_position(x, y)
detect_visual_elements(rect=<the returned control object>)
```

`detect_visual_elements` captures only the supplied rectangle and returns numbered
class-agnostic boxes, absolute screen rectangles, input-relative normalized rectangles,
containment relationships, confidence, timing, and an annotated preview path. Its local
layout graph adds `right-of`, `below`, alignment, overlap, and adaptive-gap relations, then
builds variable-size union groups. Group signatures intentionally exclude element width,
height, and observed content, so changing name lengths and multiline content remain the same
structure. Repeated vertical items and table rows remain separate. The tool does not traverse
UIA, run OCR, infer semantics, download a model, or call a remote API.

Remote visual location does not run a local model or require a vendor SDK. Set
an OpenAI-compatible vision endpoint and credentials, then use
`find_control_by_vision` or `click_by_vision`:

```bash
EASY_UIAUTO_VISION_API_URL=https://your-api.example/v1/chat/completions
EASY_UIAUTO_VISION_API_KEY=your-api-key
EASY_UIAUTO_VISION_MODEL=your-vision-model
```

Those tools upload the current screenshot to the configured endpoint only for
that request. Use them as a final fallback after UIA, OCR, or image matching.

The MCP server ships with the library and reuses the same automation APIs:

```bash
easy_uiauto --help
easy_uiauto --version
easy_uiauto
```

The setup commands register, inspect, or remove the MCP entry through the
client's own CLI. Existing entries are not overwritten by the basic installer.

To configure remote vision and check client connectivity:

```bash
pip install --upgrade "easy-uiauto[mcp,vision]"
easy_uiauto --full-setup-codex \
  --vision-url https://your-api.example/v1/chat/completions \
  --vision-model your-vision-model
```

Full setup asks for a missing API key through hidden input, installs the Python
vision dependencies and Tesseract when needed, replaces only the `easy_uiauto`
Codex entry, installs the two bundled skills, and checks UIA, OCR, and the remote
vision endpoint. Validation uses generated images rather than the current desktop.
Vision settings are read dynamically by a current-version MCP process. Restart
Codex once after installing or updating the package, MCP entry, or skills; changing
only the vision settings does not require a second restart.

For a minimal Codex deployment with remote AI vision, use the quick setup
command. When no saved API key is available, it prompts once through hidden terminal input or a password dialog
for non-interactive agents. It stores the key in Credential Manager and the URL/model in user environment variables, replaces
only the `easy_uiauto` Codex MCP entry, and skips OCR installation and UI tests:

```bash
easy_uiauto --quick-setup-codex \
  --vision-url https://your-api.example/v1/chat/completions \
  --vision-model your-vision-model
```

```bash
easy_uiauto --install-codex
easy_uiauto --show-codex-config
easy_uiauto --uninstall-codex

easy_uiauto --install-claude-code
easy_uiauto --show-claude-code-config
easy_uiauto --uninstall-claude-code
```

Codex registration uses its global `config.toml`. Claude Code uses the `user`
scope. Restart the client after installing, updating, or removing the server.

### DeepSeek Harness (DSH)

Connect through the official `@deepseek-ai/dsh-mcp-client` plugin. Copy the
[example overlay](docs/examples/dsh/easy-uiauto.cordis.yml), set `command` to the
absolute path of the Python that has easy-uiauto installed, and start DSH:

```cmd
dsh web --patch "C:\configs\easy-uiauto.cordis.yml"
```

Save the knowledge-vault and vision settings with `easy_uiauto_config`, then copy
the two bundled skills into `$DSH_HOME/skills` (default `%USERPROFILE%\.dsh\skills`).
DSH's conversation model and easy-uiauto's vision endpoint are configured separately.
See the [DSH setup guide (Chinese)](docs/dsh-setup.zh-CN.md) for installation,
verification, and timeout troubleshooting.

### TCP Service

The long-running TCP service is also available:

```bash
easy_uiauto_service --help
python -m easy_uiauto.mcp.service --port 9876
```

TCP `get_control_tree` uses the same isolated inspection worker as MCP, with
defaults of 500 nodes and a 15-second timeout. Python clients can pass
`max_nodes` and `timeout_seconds` as keyword arguments; a timeout returns partial
results and leaves the service available. Reads do not activate windows, and
startup no longer walks the desktop. `compile_window` remains a bounded read;
`--cache-depth` sets its default depth.


### Action outcomes and condition checks

Desktop actions now return JSON with `ok`, `code`, `verified`, `retryable`,
`message`, and `data`; legacy text moves to `message`. Execution success does
not prove the intended effect. Use `wait_for_control`, `wait_for_text`, and
`get_window_state` / `wait_for_window` to verify conditions without repeating
actions. `get_capability_readiness` checks UIA, OCR, image matching and remote
vision prerequisites separately. Prefer `scroll`; `mouse_scroll` is a compatible
alias with identical parameters. Positive tick counts plus `up`/`down` now have
consistent direction in both tools.

See [outcome codes, migration notes and examples (Chinese)](docs/mcp-results-and-waits.md).

### Configuration Window

Windows x64 wheels and source distributions include
`easy_uiauto/bin/easy-uiauto-config.exe`. After installation, run
`easy_uiauto_config` to launch that bundled EXE, or double-click the standalone
`dist/easy-uiauto-config.exe`. It configures the knowledge directory, API URL,
API Key and API Model and includes its Python/Tk runtime for standalone use.
The API Key is masked by default, with a reveal button; the model dropdown accepts typed names as well
as selections from the provider's model list. Browse selects a local directory,
Fetch retrieves models in the background, and Save stores the API key in the current
user's Windows Credential Manager. Other settings remain in user environment variables.
A failed save restores previous settings and never falls back to plaintext key storage.
This window configures one API.

URLs may be a provider base, a versioned `/v1` base or a full `/chat/completions`
endpoint; saving normalizes the URL for the existing MCP. Model retrieval does
not save changes or send screenshots. The updated MCP reads saved settings on
its next call; older MCP versions need an upgrade and restart. Existing knowledge
is not moved when the directory changes.

Build on Windows:

```cmd
python -m pip install pyinstaller
python scripts/build_config_exe.py --bundle-package
python -m build
python scripts/verify_config_bundle.py
```

Build the EXE before the Python distributions. `--bundle-package` copies it into
the package resources. CI and tag publication first compile it on Windows, then
build the wheel and sdist and verify that both contain the same EXE before
publication. Compiled binaries travel as build artifacts and are not checked
into Git.

### Window Edge Cropping

Window learning, interaction screenshots and replay verification exclude native
invisible resize borders, then optionally find a near-full closed rectangle with
local pixel-matrix edge detection. Quiet outer backgrounds are checked for omitted
text strokes; busy exteriors require a continuous frame, balanced capture margins
and a broad title-bar transition. Ambiguous images stay unchanged. Captured
pixels and their screen origin change together. Rescan existing knowledge to
refresh the image reference and normalized geometry.

MCP `take_window_screenshot(window_name="New Project", auto_crop=True)` returns
both PNG and `capture_bounds`, `crop_offset` and size metadata. Set `auto_crop=False`
for the original UIA frame. Existing `take_screenshot` region captures are unchanged.
For a saved Pillow image, use `easy_uiauto.visual.crop_window_image(image)` with
the local `vision` dependencies; its result includes `image`, `rect_in_input`,
`offset` and `cropped`. This algorithm does not call a remote model.

## Learn an Application

The package includes two Codex skills:

- `$easy-uiauto-learning` learns controls, uses saved GUI regions and references,
  and saves requested workflows.
- `$easy-uiauto-operate` runs commands from an existing application vault.

After setup and restarting the MCP client, you can request a scan:

```text
Use $easy-uiauto-learning to learn the currently open WeChat window and build
its control knowledge and UI commands.
```

### Learn into existing GUI regions

Save the regions, descriptions and entry steps in the GUI first. Give the agent the
same absolute vault path and the application name. For example:

```text
Use $easy-uiauto-learning. In vault D:/UI-Knowledge, learn the saved regions for
My Application using my descriptions and enabled references. Keep the existing
region IDs and boundaries, and save each control under its region and Tab state.
Save a "Create project" workflow using the recorded controls, a project-name
parameter and result checks. Keep missing steps as a draft and report them.
Save the definition for review; I will specify execution testing separately.
```

`get_ui_library` reads the saved inputs. `get_ui_library_readiness` checks local
models, and `start_ui_library_task` starts region learning, menu expansion,
description supplementation or a saved workflow run. Use `get_ui_library_task`
and `stop_ui_library_task` to track or stop that task. `save_ui_workflow` writes
the GUI's workflow records; a ready definition is not an executed test result.

Learning follows saved entry steps and can operate the target application. After
the agent saves records, save any open GUI edits and refresh the tree. See the
[detailed instructions](docs/knowledge-gui.zh-CN.md#让-agent-按人工划分学习并归档).

### Light Scan

A light scan observes one visible page. It does not click the application.

```bash
easy_uiauto_ui scan "Window title"
easy_uiauto_ui apps
easy_uiauto_ui commands <app-id>
easy_uiauto_ui show <app-id>
```

The default `visual-first` strategy sends target-window screenshots to the
configured vision endpoint, using overlapping native-resolution tiles for large
windows. It enumerates meaningful visible elements individually and maps
those coordinates back to local UIA controls. It stores stable `LOCATION`
records, control crops, meaning, aliases, risk, and generated commands. Secondary
monitors are supported. The scan also saves `<page-id>.annotated.png` and briefly
draws the same numbered controls over the live window. Use `--no-overlay` when
visual feedback is not wanted.

Select it explicitly with `easy_uiauto_ui scan "Window title" --strategy visual-first`
or MCP `scan_window_knowledge(window_name="Window title", strategy="visual-first")`.
It samples visual targets through Python `uiautomation.ControlFromPoint` and checks
ancestors, geometry and native semantic consistency without enumerating the full UIA
tree. Both strategies use the same `uiautomation` backend. `uia_controls_seen` counts
selected controls, including the bounded native-label supplement, not all nodes exposed
by the application. `ok=true` means scanning completed; check `commands` for executable
knowledge.

Visual binding failures include `reason`: `no_uia_candidate` for empty point lookup,
`uia_lookup_failed` for UIA read errors, `geometry_rejected`, `semantic_rejected`, or
`score_rejected`. The latter three mean candidates were collected and rejected, not
that the application exposes no controls. `diagnostics` includes absolute target/sample
coordinates, candidate counts and rejection evidence. Rejection and error detail lists
are capped at eight each; `rejection_count` and `lookup_error_count` keep full counts.
Visual observations also retain these diagnostics in their `verification` records.

Desktop scans also enumerate Explorer's exposed desktop items to supplement
shortcuts and files omitted by vision. For desktops, vision analyzes only the
taskbars while visible native items are retained. A screen hit test excludes icons
covered by other windows, which UIA's `IsOffscreen` flag alone does not detect.
The `coverage` result reports tile, desktop-item, and occlusion counts; limits are
reported through `truncated`. Distinct visual
entities sharing a UIA container remain separate observations and annotations.
Only independently verified locators produce executable commands. Desktop items
supplemented from native names retain unknown risk and confirmation flags; their
opening effects have not been tested.

`get_control_tree` selects a visible window using Win32 and binds UIA only to its
handle. It runs in a disposable process without activating/restoring the window.
The defaults are `max_depth=5` (capped at 10), `max_nodes=500` (up to 5000), and
`timeout_seconds=15` (0.1–60, including worker startup). Child enumeration stops
at depth/node limits. Successful trees include `_inspection` with reached limits
and provider errors. A blocked provider returns `ok=false`, `code="timeout"`,
and the latest partial tree/checkpoint in `data`; only its worker is stopped.
`get_ui_learning_status` tracks learning tasks, not this inspection call.

MCP scans report their task ID, stage, elapsed time, and control-verification count
every five seconds. If a client stops waiting, call `get_ui_learning_status` before
retrying. A `running` task continues in the MCP process and must not be started twice.
Plain learning requests stop after this scan. Interactive `explore_ui_workflows`
runs only when deep or autonomous exploration is explicitly requested.

Runtime verification failures stay quarantined across rescans, index rebuilds and
semantic teaching. After repairing the locator or restoring the required visible
page, call `revalidate_ui_control(app_id=..., control_id=...)` for a fresh check.
It executes no control action and requires LOCATION/image evidence; OCR alone
cannot release quarantine. Original failure evidence remains in the record.
Automatic exploration skips previously attempted control/action pairs, including
no-change and interference records. Explicit `learn_ui_command_effect` remains
available for intentional repeated observations. Window activation preserves
maximization; an unrelated foreground window stops discovery and recovery input.

Named native menu, button, checkbox and radio actions are cross-checked against
their UIA labels, with common
Chinese/English action aliases and accelerator suffix normalization. For example,
Select all must not become Go to, nor Close become Maximize. Conflicting visual
observations remain diagnostics. Visual-first scans supplement actions from a
bounded shallow menu/titlebar UIA inventory of the target window, without desktop
root enumeration. Execution repeats the identity check; a known contradiction
cannot fall through to image/OCR matching, including legacy records after an
index rebuild. These checks cover common action labels, not every custom control.
Exploration selects only currently observed controls and excludes disabled
actions and new documents/windows without an Escape reversal. A nested stop also
withholds parent recovery input.
Known input labels such as Find what and Replace with provide independent native
evidence; editable content is not action identity. Disabled owners recover through
verified owned modal windows, without generic browser-back keys. Learning owned
dialogs preserves the application's main window name. Parent candidates are
checked again after recursive exploration to avoid repeating a nested action.

Task status is held in memory and is lost when the MCP process exits. Saved
knowledge remains on disk. Markdown files use UTF-8; in PowerShell, read them with
`Get-Content -Encoding UTF8`.

Use `--strategy full-uia` for diagnostics when visual targeting is not suitable.
This mode walks the visible UIA tree and performs a separate semantic pass, so it
is slower and produces more records.

### Saved UI images

Call MCP tool `analyze_ui_image(image_path="C:/images/screenshot.png")` to analyze a
saved PNG, JPEG, or WebP without opening or controlling an application.
The default `engine="local"` uses YOLO + RapidOCR. Review the output for missed
controls, incorrect boxes and OCR errors before using its coordinates.

Graphic detection uses Microsoft's official [OmniParser v2.0 icon_detect_v3 weights](https://huggingface.co/microsoft/OmniParser-v2.0/tree/main/icon_detect_v3),
`model.pt`, with the **YOLOv9-E** architecture. Text recognition uses RapidOCR's
**PP-OCRv6 small ONNX** models. These weights were not retrained on this project's
circuit or Simulink images. Install the local dependencies from the checkout:

```cmd
python -m pip install ".[mcp,image]"
```

Local inference needs no API URL, key, or remote model. The first run downloads and
verifies the YOLO weights; later runs reuse the cache. Missing local dependencies
produce an installation error without uploading the image. For remote comparison,
explicitly call `analyze_ui_image(image_path="C:/images/screenshot.png", engine="api")`.
Only that mode reads the configured vision API; `model`, `analysis_scale`, and
`analysis_context` are API-only options. MCP local mode defaults to `profile="ui"`;
select `block-diagram` for control and electrical model diagrams.
The separate `circuit` profile has been removed; update existing calls to `block-diagram`.
The default YOLO confidence threshold is **0.1**. Override it with MCP `confidence`
or the CMD `--confidence` option.

Local annotation also enables **rectangle-contour snapping** for graphic boxes:
grayscale threshold 210, candidate width 30..600 and height 12..60 pixels, highest
IoU at least 0.35, and candidate width/height no greater than 1.6x the old box.
A contour-area check rejects sparse text strokes. Unmatched boxes are retained.
This completes closed rectangular borders such as input fields and buttons; it
does not replace arbitrary-shape detection. Text and IDs stay unchanged.
`detected_rect` retains the prediction; `corrected_rect`, `snap_iou`, and
`geometry_correction` record the fit, with `rect`, `bbox`, center and normalized
coordinates updated together. The local default keeps a one-pixel margin.
Use MCP `rectangle_snap=False` or CMD `--no-rectangle-snap` to disable this pass.

Both modes first crop a reliable outer window frame locally. Ambiguous images stay
unchanged; `auto_crop=False` keeps the full input. `crop.offset` maps coordinates
back to the EXIF-oriented original `input_image_path`. The returned `image_path`
identifies the actual recognition input, saved as `analysis-input.png` when cropped,
so subsequent corrections use the matching image and coordinate system.
The tool returns `annotated_image`, `coordinates_json`, and
numbered `elements` with meaning, confidence, `bbox` (`x`, `y`, `width`, `height`),
`rect` (left/top inclusive, right/bottom exclusive), center, and normalized coordinates.
All element coordinates refer to the actual recognition input at `image_path`.
Graphics use blue boxes and `G1…` labels; text uses orange boxes and `T1…` labels.
`annotation_label` maps each display label to its original numeric `id`, which
correction tools continue to use. These remain observations without UIA or execution
verification, and no application knowledge is written. `output_dir` selects a parent
directory for a unique run folder; `max_elements` limits output with explicit
`truncated` reporting. Attachments must be accessible as local files to the server.
In API mode, small inputs are automatically enlarged up to 4x for recognition, with all regions
and elements mapped back to recognition-input coordinates. `analysis_scale=1` disables
enlargement; values from 1 to 4 set an explicit scale.
`box_padding` adds a margin in recognition-input pixels (local default 1, API default 2; set 0 to disable).
`detected_rect` retains the model's raw mapped bounds; the returned `rect` and
`bbox` include that margin and any known attached subcomponents. The enlarged
`annotated_preview_image` is drawn separately with one-pixel outlines and compact
labels, so enlarging an image does not enlarge its annotation strokes. Labels stay
two pixels outside one of their own box's edges; collision avoidance only slides
them along those edges. If no edge fits inside the image, a white canvas margin
keeps the complete label visible. Element coordinates remain unchanged;
`annotation_layout.image_origin` records the input's offset on that canvas and
`labels` records label positions in input coordinates. `annotation_preview_layout`
records the preview layout. Use
`analysis_context` to specify scope and granularity, for example whole circuit
model components rather than their internal resistor/capacitor symbols.

Use `correct_ui_image_annotations(coordinates_json=".../elements.json", refine_ids=[1,3,9])`
to fit selected existing boxes to local pixels without another API request. This
mode suits isolated icons on light, plain backgrounds; uncertain or connected
shapes are skipped with reasons. For exact bounds, pass
`corrections=[{"id":3,"rect":{"left":110,"top":65,"right":125,"bottom":81}}]`.
Explicit rectangles receive no added padding. Pixel fitting defaults to a one-pixel
margin. IDs, semantics, raw `detected_rect`, and the annotation style are preserved.
The default pipeline does not apply `icons` foreground fitting to every control:
it can shrink an input-field box to its text. Request it only for suitable isolated
icons and inspect the before/after result.
New PNG/JSON files retain the previous outputs; `corrected_rect` and
`correction.updates` record changes. New analyses include a source image hash so
correction rejects changed images. Legacy results validate dimensions only.

For existing rectangular UI controls, use
`correct_ui_image_annotations(coordinates_json=".../elements.json", profile="rectangles")`.
It applies the same rectangle snapping to all graphics, or selected `refine_ids`,
without another model request or changing text. It retains the full original JSON
metadata and can also refine explicitly requested API results.

For connected model components, add `profile="block-diagram"`. This uses original pixels
to detect rectangular frames, paired circles, grounded load branches and thick
busbars, then fits selected observations and merges shared geometry candidates.
`discover_missing=true` additionally recovers unassigned busbars; it does not add
other missing symbol kinds. Primary IDs and raw model evidence remain available,
with merged/added IDs and candidate counts in `correction`. This local mode does
not read reference annotations or make vision requests. It supports the documented
symbol structures rather than arbitrary circuit notation; review skipped matches.
Control block diagrams also support complete subsystem/constant/mux frames,
pointed From/Goto tags, machine/meter ellipses, terminal rings and grounds. Closed
outlines exclude frame and shadow edges from busbar discovery. Unsupported or
ambiguous predictions remain unchanged in `correction.needs_review_ids`; they
are not verified components. Tile coverage now reports bounds and raw/merged
observation counts. Cross-tile fusion preserves conflicting predictions in
`tile_observations`, without requiring identical model-generated roles or types.
Visible text is also a control. Labels, captions, values and port text use their
own `text-label` IDs; text and graphic boxes may overlap without being duplicates.
Use `text-of`/`label-of` associations so external captions do not enlarge graphic
bounds. `text_control_ids` are preserved by circuit correction; text geometry
requires a text detector/OCR or review, not a closed circuit-symbol outline.

### Local image annotation from CMD

CMD uses local YOLO + RapidOCR by default.
Run directly from the checkout without starting Codex or an MCP server:

```cmd
cd /d C:\path\to\easyautomation
annotate-image.cmd "C:\images\input.bmp" "C:\images\results"
```

#### IEEE9 annotation example

Annotate [IEEE9.bmp](https://raw.githubusercontent.com/Poggi-Tang/easyautomation/v0.9.10/docs/examples/IEEE9/IEEE9.bmp)
with local YOLO + RapidOCR:

```cmd
annotate-image.cmd "docs\examples\IEEE9\IEEE9.bmp" "%TEMP%\easy-uiauto-ieee9" --profile block-diagram
```

The example detects **42 graphics and 102 text regions**.

Original image:

![IEEE9 input](https://raw.githubusercontent.com/Poggi-Tang/easyautomation/v0.9.10/docs/examples/IEEE9/IEEE9.png)

Combined annotation:

![IEEE9 graphic and text annotations](https://raw.githubusercontent.com/Poggi-Tang/easyautomation/v0.9.10/docs/examples/IEEE9/results/combined.preview.png)

Results: [graphics](https://raw.githubusercontent.com/Poggi-Tang/easyautomation/v0.9.10/docs/examples/IEEE9/results/controls.png),
[text](https://raw.githubusercontent.com/Poggi-Tang/easyautomation/v0.9.10/docs/examples/IEEE9/results/text.preview.png),
[coordinates JSON](https://github.com/Poggi-Tang/easyautomation/blob/v0.9.10/docs/examples/IEEE9/results/elements.json).
For the interactive viewer, download the [example](docs/examples/IEEE9) and open
`docs/examples/IEEE9/results/index.html`.

The arguments are the input image and output parent directory. Quote paths containing
spaces. Each run creates an independent `<image>-<timestamp>-<id>` folder and prints
its path. Open `index.html` there to view all three layers and resource links:

- `text.png`: orange `T` text controls.
- `controls.png`: blue `G` graphic controls.
- `combined.png`: both layers with matching display IDs.
- `original.png`: EXIF-oriented input composited against white.
- `analysis-input.png`: the actual recognition input after optional window cropping.
- `elements.json` / `elements.csv`: text, IDs, coordinates, provenance and relations.
- `raw-yolo.json` / `raw-ocr.json`: original detector and OCR outputs.
- `ocr-recovery.json`: small-text candidates, rejection reasons and recognition evidence.
- `geometry-candidates.json`: original-pixel shape candidates and evidence.
- `rectangle-snap.json`: candidate rectangles, IoU, before/after bounds and skipped reasons.
- `ui-fusion.json`: blank-region rejection, compact-border protection, repeated-icon recovery and OCR conflicts.
- `before-snap.png` / `snap-compare.png`: before fitting and red original / green fitted / blue unchanged boxes.
- `summary.json` / `run.log`: counts, timings and success/failure diagnostics.

The default `--profile ui` handles ordinary software screenshots, matching MCP
local mode. Use `--profile block-diagram` for control and electrical model diagrams.
The default UI path also detects light canvases where exterior wire pixels connect
at least three independently bounded components. Within those canvases it applies
the same outline, color-body and busbar recovery as block-diagram, while keeping
surrounding UI and palette items separate. Panel borders are excluded from geometry
analysis so embedded canvases retain their internal components. Inspect
`diagram_recovery` in `ui-fusion.json` for canvas bounds, connection evidence and
replacement counts. GUI learning, MCP, CLI and Python share this automatic path.
Insufficient canvas evidence leaves the UI rules active; explicit block-diagram
remains available for model images. Recovery does not verify electrical connectivity
or execution.
UI mode checks proposal pixels and a two-pixel context,
rejecting regions without visible foreground or borders while retaining bordered
empty inputs. Compact closed control borders protect graphics from OCR deduplication;
suspect OCR glyphs such as M/check marks inside them are recorded as conflicts without
changing raw OCR output. Nested predictions of one compact border are merged with
all original `yolo_proposal_ids` retained.

UI mode also extracts up to 12 templates from already detected small icons in the
current image and recovers matching patterns at correlation >=0.97, excluding existing
small controls and normal OCR text. It uses no reviewed annotations or reference-image
coordinates. Recovered observations use `local-template-recovery` and
`confidence_kind=template-correlation`, which is not a YOLO probability or semantic
verification. Inspect `ui-fusion.json` for all filtering, protection and recovery evidence.
Aligned compact toolbar/dock proposals protect icons from low-confidence OCR
glyph conflicts, including light disabled artwork. Repeated tree prefixes and
leading search/filled markers can be separated from a caption. Original OCR text,
bounds and each correction remain in the report; a fitted glyph does not verify
the control's function.
UI layout lines separate table cells, row fragments and repeated list regions from
their atomic text/icon observations; the original region proposals remain in the
report. Pixel-fitted arrows and close symbols retire their duplicate OCR glyphs.
Supported scroll thumbs and a magnifier merged into a CJK caption can be separated
locally, with original text and bounds retained in correction evidence. Wide light
input borders and button borders protect those controls from text-only filtering.
Dense small-control pages also receive a separately rendered 2x preview; coordinates
remain relative to the analysis input and the viewer opens the readable preview.
Palettes with repeated section headers, regular pixel gutters and non-text shape
evidence use complete, uniform cells for visible items, including missed symbols.
Internal OCR stays in `visual_components`; empty slots are not added. Rectangle
snapping preserves the full cell. Inspect `palette_layout` in `ui-fusion.json` for
spacing, pixel bounds and grouped predictions. Layout recovery has no YOLO score
and does not verify control semantics or execution.
For UI inputs larger than 1280 pixels, the detector packs populated regions at
native scale into multiple detail canvases, reusing loaded weights. Oversized
regions use overlapping tiles so small controls crossing a seam can appear intact
in a neighboring tile. Whole-image detections remain; mapped additions retain
their patch evidence. Review `detail-input.png`, `detail-input-2.png`, etc. and
`detail-recovery.json` for mappings, inference counts and crop-edge rejections.
Additional passes can take longer; discovered content is no longer dropped to fit
a single canvas. Disable this with MCP/Python
`detail_recovery=False` or CMD `--no-detail-recovery`. Smaller images and model
diagrams retain their single whole-image pass.
The default YOLO input is a 1280x1280 square.
UI YOLO and OCR run concurrently within one `--threads` budget (default 3+1); one-thread
runs stay sequential. Model diagrams retain square, sequential inference.
`raw-yolo.json` records actual input shapes; `inference_execution` records the
schedule, thread split and wall time. Concurrent `yolo_seconds` and `ocr_seconds`
overlap and must not be added as total elapsed time. Reduced stride-aligned padding
is experimental: explicitly opt in with `--rectangular-inference` or Python/MCP
`rectangular_inference=True`. Detection scale stays the same, but changing input
shape can change predictions; validate quality rather than assuming lossless
acceleration. `--square-inference` remains a compatibility option for the default
square input. Compare scheduling with `--sequential-inference` or
`parallel_inference=False`. Models, thresholds and recovery passes stay the same.
Blank proposals need foreground inside their own bounds, or a complete matched
closed control border within their 2px context. A neighboring panel line alone
does not qualify. Empty inputs and checkboxes keep their closed-border support.
`pixel_evidence` records `inside_foreground_pixels`, `context_foreground_pixels`,
`context_closed_border` and `pixel_support` for review.
Other duplicate text proposals are removed; UI mode does not force diagram outlines
onto arbitrary icons. Results can
still contain missed regions, false positives and OCR errors. Diagram fitting supports
the implemented outline families only.

Reliable outer window frames are cropped before recognition by default. Use
`--no-auto-crop` to retain the full input. `crop.offset` in `elements.json` records
the origin in the original image; annotations and corrections match `analysis-input.png`.

The block-diagram profile also detects connected color foreground without selecting
specific hues. Touching color patches and narrow dark dividers form one body;
nearby text and connecting wires remain separate. Closed ports can extend the
body's bounds. Neutral mux bars and tags with text touching their border are
handled separately. Unmatched YOLO proposals with substantial non-text graphic
pixels remain review candidates instead of being discarded for an unknown shape.
The exported geometry records include accepted/rejected candidates, color evidence
and rejection reasons; the summary includes color counts and fusion time. This
does not retrain or replace the official YOLO/OCR models.

Small-text recovery is enabled by default inside existing closed control frames.
It reuses the detector probability map, checks relaxed proposals only inside those
frames, rejects existing text and connected wire/border strokes, and requires the
original and enlarged crops to produce identical text. At least one recognition
score must reach 0.95 and both must reach 0.90. Accepted observations are appended
without replacing the original results or IDs, with source
`rapidocr-small-text-recovery`. Inspect `ocr-recovery.json` for evidence and timing;
use `--no-small-text-recovery` to disable the pass for comparison.

On another machine, install optional dependencies from the repository first:

```cmd
python -m pip install ".[image]"
easy_uiauto_image "C:\images\input.bmp" "C:\images\results"
```

The official OmniParser YOLOv9-E model (~281 MB) is downloaded once, SHA256-verified
and cached. RapidOCR includes the PP-OCRv6 ONNX models. Existing local experiment
caches are reused when available. `--offline` requires cached models and prevents
YOLO downloads. Inference runs locally without a vision API or API key. Select YOLO's
device with `--device auto|cpu|cuda|cuda:N`; omitted values use the GUI/environment
setting, otherwise auto. OCR stays on CPU. Default bundles include CPU packages;
NVIDIA users can install the optional runtime with `setup.bat -Gpu`.
See [YOLO GPU setup](docs/yolo-gpu.md).
The CMD launcher uses `python` from PATH; set `EASY_UIAUTO_IMAGE_PYTHON` to select
another interpreter. Use `annotate-image.cmd --help` for options. Exit status is 0
on success and 2 on failure; failures after processing begins are recorded in that
run's `summary.json` and `run.log`.

### Whole-window CLI Exploration

This section describes `explore_ui_workflows` and the CLI explorer. For GUI region
learning, use **基本学习** (observe only) or **深度学习** (interactive branches), also
available through `start_ui_library_task` with `learn-region` or `deep-learn-region`.

Deep exploration starts with a light scan, executes known reversible commands,
and records what changed. New pages and dialogs can be scanned recursively.

Deep-learning interactions and recorded replay share `Controller` actions backed
by `uiautomation`. Verified targets are passed directly to the execution layer,
without a second XPath lookup. Target previews use the in-process `ScreenLineBox`
and close before operation-effect screenshots are captured; text-verification screenshots
temporarily hide previews. Use `highlight=false` with `learn_ui_command_effect`
or `explore_ui_workflows`, or `--no-highlight` on the CLI, to disable previews.
Manual recording remains independent of the knowledge vault.

```text
Use $easy-uiauto-learning to deeply learn the currently open WeChat window with
the safe policy, at most 30 actions, and recursion depth 3. Do not send messages,
delete data, log out, or run any confirmation-required operation.
```

```bash
easy_uiauto_ui explore <app-id> --policy safe --max-actions 30 --max-depth 3
easy_uiauto_ui interactions <app-id>
```

For each operation, the explorer saves before/after screenshots, local pixel
differences, changed UIA properties, new or transient windows, the observed
success condition, and the recovery result. It deduplicates page/command states
and stops when recovery fails or another user/window interrupts the run.

`safe` executes only commands classified as safe. `supervised` may also execute
reversible state-changing commands. External, destructive, and
confirmation-required commands are never explored automatically. Scrolling and
dragging are not implemented in the explorer.

### Run Learned Commands

```bash
easy_uiauto_ui search <app-id> "search terms"
easy_uiauto_ui show <app-id> --include executable
easy_uiauto_ui run <app-id> <page.region.control.action> --text "optional text"
easy_uiauto_ui batch <app-id> '["main.keypad.enter-digit-6.click", "main.keypad.enter-addition-operation.click"]'
easy_uiauto_ui learn-effect <app-id> <command> --recover
easy_uiauto_ui teach <app-id> <control-id> "Meaning" intent "Description"
```

Runtime lookup follows contextual XPath with the selected mode → property selectors
combination → saved image states → local OCR → opt-in remote vision. Enable the last step with `--allow-vision-fallback` or
`allow_vision_fallback=true`. Stale, missing, or mismatched controls are moved to
quarantine instead of being clicked. Single and batch commands preview their
resolved targets in red by default; pass `--no-highlight` or `highlight=false`
to remove the roughly 100 ms visual-preview wait.

`set-text` first verifies UIA value assignment, then falls back to clipboard paste
for Unicode text. It reports success only after an accessible value or exact clipboard
readback confirms the write; a local image change is diagnostic evidence only. The user's
previous text clipboard value is restored after pasting.

Use a batch only for commands on the same stable page. Split the sequence after
navigation. Commands with external or destructive effects require `--confirm`
or `confirm=true`.

### Knowledge Vault

The default vault is `~/easy_uiauto_vault`. Set
`EASY_UIAUTO_KNOWLEDGE_DIR` to use another location. Markdown/YAML and PNG files
are the source of truth:

```text
applications/<app-id>/
├── pages/                 page records
├── regions/               functional regions
├── controls/              verified and observed controls
├── interactions/          before/after effect records
├── references/            imported manuals and reference documents
├── usage/                 user-written application instructions
├── workflows/             GUI combination actions and latest run results
├── learning/              Region exploration states, branches and progress
├── images/                page, control, and interaction images
├── quarantine/            stale or ambiguous controls
└── operations/UI-CLI.md   generated command catalog
```

`.easy_uiauto/index.json` is a disposable search cache. Rebuild it with
`easy_uiauto_ui reindex <app-id>` after editing Markdown by hand.

Image cleanup runs after a scan or an effect-learning record is committed. Each
control keeps its current template and up to eight recent distinct image states;
unused older state files are removed from disk. New interaction snapshots use PNG
content hashes, so identical before/after or desktop images share one file.
By default, image sets are retained for the latest 50 interactions. Textual
interaction records remain available after their images expire.

Referenced evidence, interactions marked `retain_images: true`, and the latest
available failed interaction for each control/action are protected, even outside
these limits. Active legacy quarantines without an image manifest are preserved
conservatively. Set `EASY_UIAUTO_CONTROL_IMAGE_VARIANTS` (default `8`, minimum `1`)
and `EASY_UIAUTO_INTERACTION_IMAGE_RECORDS` (default `50`, minimum `0`) to change
the defaults. These are retention limits, not a hard storage quota.

For an existing app, call
`cleanup_ui_knowledge_images(app_id="notepad")` to preview the files and bytes
eligible for removal, then pass `dry_run=false` to apply the cleanup. Optional
`keep_control_variants` and `keep_interaction_images` override the limits for
that call. Collection checks Markdown/YAML references and only removes managed
PNGs in that application's control/interaction image directories. Page images
and other apps are excluded. Unreadable knowledge defers cleanup; a per-vault
file lock prevents cooperating MCP writers from losing pending images.

Control and region geometry uses a window-relative `normalized_rect`. Visual hints
support annotation and comparison. GUI regions picked through UIA also retain their
native `LOCATION`; image targets use a saved template. Operations resolve the target
in the current window before clicking. Rebuilding older vault indexes removes legacy
absolute desktop rectangles, PIDs and window handles.

### Privacy and Safety

- CLI / MCP visual-first scanning sends the selected target-window screenshot to the
  configured endpoint. GUI basic learning can run locally; images are sent only when API descriptions are enabled.
- Effect learning sends target-window before/after images and crops of related
  new windows. Full desktop snapshots remain local in the vault.
- API keys are read from Windows Credential Manager first, with compatibility for legacy
  environment variables and the application's old MCP configuration. They are not written
  into the vault. Key fields are masked, and network errors omit provider error bodies.
- PIDs, native window handles, and absolute desktop coordinates are runtime
  observations only and are not persisted as application knowledge.
- Inferred control meanings remain separate from locator verification and
  observed operation effects. Use `teach` to correct a meaning; it cannot bypass
  failed location checks.
- Existing reliable controls are retained when a visual-first rescan omits them.

The same workflow is exposed through `get_ui_learning_readiness`,
`get_ui_learning_status`, `scan_window_knowledge`, `show_ui_controls`,
`list_ui_knowledge_apps`, `search_ui_knowledge`, `search_ui_knowledge_batch`,
`list_ui_commands`,
`run_ui_command`, `run_ui_commands`, `learn_ui_command_effect`,
`explore_ui_workflows`, `list_ui_interactions`, `teach_ui_control`, and
`rebuild_ui_knowledge_index`, and `cleanup_ui_knowledge_images`.

`--full-setup-codex` installs or updates both bundled skills. Use
`--install-codex-skills` when only the skills need to be refreshed.

For MCP client configuration, start the server with `python -m easy_uiauto.mcp.server`.
GUI, MCP and Python share one Markdown knowledge vault. Save captured observations
with `upsert_control_record(..., app_id=..., vault=..., page_id=..., region_id=...)`;
no external vector-store module is required. Mixed mode writes to the same vault
and reports archival results in the action's `learning` field. Imports do not grant
locator or business verification. Use `import_control_records` to preview and migrate
legacy JSON/JSONL exports while preserving originals. See the
[shared-library guide](docs/shared-library.zh-CN.md).

Control lookup uses the library's canonical `LOCATION` object rather than a
flat selector. Obtain it from a recorded action or from
`get_control_at_position`, then pass the returned `LOCATION` object directly to
`find_control`:

```json
{
  "WindowName": "My Application",
  "Name": "Save",
  "ClassName": "ButtonClass",
  "ControlType": "ButtonControl",
  "foundIndex": 1,
  "AutomationId": "saveButton",
  "Xpath": [
    {"ControlType": "WindowControl", "Name": "My Application", "searchDepth": 1},
    {"ControlType": "ButtonControl", "Name": "Save", "foundIndex": 1, "searchDepth": 2}
  ],
  "Img": "",
  "PARAMETERS": {}
}
```

`find_control` also accepts a complete recorded action containing `LOCATION`
and the complete result from `get_control_at_position`. Legacy flat arguments
remain supported.

`LOCATION.WindowName` and window XPath `Name` values are UIA names, which may
differ from the native window caption. Playback binds UIA through native HWNDs,
checks the recorded UIA identity, then activates the resolved top-level HWND
and waits 5 ms before checking foreground state. Handles are resolved anew on
each playback rather than stored permanently. Explicit `activate_window` and
`set_top_window` calls take the exact native caption.

Python, recorded playback, MCP, and TCP share two selection modes:

- `identity` (default) returns the first matching Name within the window/parent
  path, using type and class as context. Five cells named `1.0` select the first;
  recorded ordinals are ignored. AutomationId is used when Name is absent.
- `position` selects a direct child by its 1-based same-type `foundIndex`,
  ignoring recorded Name, AutomationId and class. Type and a positive index are
  required; invalid or out-of-range indices fail without switching modes.
  Window scoping remains in effect; this is not an absolute screen coordinate.

```python
from easy_uiauto import find_control, run_action, run_record

control = find_control(location)                         # identity
control = find_control(location, match_mode="position")
run_action(recorded_action, match_mode="position")        # leaves the record unchanged
run_record(match_mode="position")
```

MCP `find_control`, `click`, `type_text`, `set_text`, and `run_action` also accept
`match_mode`. Each XPath step can store its own mode; an explicit method argument
overrides the entire path. A LOCATION-level `match_mode` is normalized into the
existing PARAMETERS and XPath fields, preserving legacy action signatures.
Unmarked older records now default to identity; select position explicitly when
the recorded ordinal is intended. Positional paths need complete parent ancestry;
re-record older paths that omitted intermediate containers. Lookup alone does not
activate a window.

## Python API Examples

### Import MCP tools in Python

Starting with 0.9.2, all MCP tools are importable from `easy_uiauto.mcp` after
installing or upgrading `easy-uiauto[mcp]>=0.9.2`. Source checkout users should install `-e ".[mcp]"` in the
same interpreter selected by their editor.

```python
import json
from easy_uiauto.mcp import list_windows, get_control_tree, find_control

print(json.loads(list_windows()))
# Use an actual window title and control properties returned by inspection.
tree = json.loads(get_control_tree("Your file.txt - Notepad", max_nodes=500, timeout_seconds=15))
```

Imports call the functions in your Python process without starting an MCP server.
Most tools return JSON strings; `take_screenshot` returns an MCP Image object.
Await `scan_window_knowledge`, `explore_ui_workflows`, `analyze_ui_image`, and
`correct_ui_image_annotations`; `ctx` may be omitted in ordinary Python.
The traditional package-root Controller API remains available.
Run `python demo/mcp_import.py --list-tools` to list the exports. See the
[complete import guide and interpreter checks](docs/python-imports.zh-CN.md).

### Basic Control Operations

```python
from easy_uiauto.ctrl import Controller

# Left click on a control
Controller.left_click(
    ActionTitle="Click OK Button",
    WindowName="My Application",
    Name="OK",
    ClassName=None,
    ControlType="ButtonControl",
    foundIndex=0,
    AutomationId="",
    Xpath=[],
    Img="",
    PARAMETERS={}
)

# Input text into a field
Controller.input_text(
    ActionTitle="Enter Username",
    WindowName="Login Dialog",
    Name="Username",
    ClassName=None,
    ControlType="EditControl",
    foundIndex=0,
    AutomationId="",
    Xpath=[],
    Img="",
    PARAMETERS={"输入文本": "test_user"}
)

# Keyboard shortcut
Controller.key_group(
    ActionTitle="Save File",
    WindowName="Notepad",
    Name="",
    ClassName=None,
    ControlType="",
    foundIndex=0,
    AutomationId="",
    Xpath=[],
    Img="",
    PARAMETERS={"组合键": "ctrl+s"}
)
```

### Recording User Actions

```python
from easy_uiauto.record import run_record

# Start recording user actions
run_record(write_file=True)
# Press ESC to stop recording
# Generated script will be saved to Record{timestamp}.py
```

## Project Structure

```text
easyautomation
├── .github/
│   └── workflows/
│       ├── ci.yml
│       ├── publish.yml
│       ├── build-gui.yml
│       └── build-config-exe.yml
├── src/
│   └── easy_uiauto/
│       ├── __init__.py
│       ├── qt_ui/           # Knowledge GUI
│       ├── knowledge_library.py  # Shared controls and workflows
│       ├── ctrl.py          # Core controller (mouse/keyboard actions)
│       ├── draw.py          # Visual feedback (control highlighting)
│       ├── record.py        # Action recording
│       ├── utils.py         # Control location and utilities
│       ├── mcp/             # MCP server, scanner, vault, and UI CLI
│       └── skills/          # Bundled Codex learning and operation skills
├── tests/
├── CHANGELOG.md
├── LICENSE
├── README.md
├── README.zh-CN.md
└── pyproject.toml
```

## Release Automation

The repository uses GitHub Actions for validation and publishing:

- **CI** tests Python 3.11, 3.12, and 3.13, then builds the package.
- **Tagged releases** build and publish through PyPI Trusted Publishing.
- **Build artifacts** include a wheel, an sdist, the complete GUI ZIP and the offline
  installation ZIP. Publication waits for tests and package checks to pass.

## Development

```bash
pip install -e .[dev]
pytest
ruff check .
```

## More Examples

See `demo/` for runnable examples and the source docstrings for API details.

## License

This project uses the [Personal and Enterprise License](LICENSE).
Individuals may use it free for their own independent projects, including projects
that earn revenue. Use for or on behalf of an enterprise requires a paid license.
The GUI, MCP and Python API share this policy. Source visibility does not make
this an unrestricted open-source license.

Third-party components and models retain their own licenses. See [commercial services](docs/commercial-services.md)
for enterprise licensing, customization, setup and automation solutions.

## Contact

Enterprise licensing and services: **2322806855@qq.com**.

WeChat ID: **AXMISSZJY**.
