ui-test-automation-agent

AI-Powered UI Test Automation Agent

This project is a Java-based agent that leverages Generative AI models and Retrieval-Augmented Generation (RAG) to execute automated test cases at the graphical user interface (GUI) level. It understands explicit natural language test case instructions (both actions and verifications), performs corresponding actions using the mouse and keyboard, locates the required UI elements on the screen (if needed), and verifies whether actual results correspond to the expected ones using computer vision capabilities.

Package Project

Here the corresponding article on Medium: AI Agent That’s Rethinking UI Test Automation

Key Features

Test Case Execution Workflow

The test execution process, orchestrated by the Agent class, follows these steps:

  1. Test Case Processing: The agent loads the test case defined in a JSON file (e.g., this one). This file contains the overall test case name and a list of TestSteps. Each TestStep includes a stepDescription (natural language instruction), optional testData (inputs for the step), and expectedResults (natural language description of the expected state after the step).
  2. Step Iteration: The agent iterates through each TestStep sequentially.
  3. Action Processing (for each Action step):
    • Screenshot: A screenshot of the current screen is taken.
    • Instruction Model Interaction: The action execution prompt is sent to the model with the test step action description, the current screenshot, and any testData. The model analyzes the action and determines which tool(s) to call and with what arguments (including extracting the description of the target UI element if needed). The response is expected to contain a selected tool.
    • Tool Execution: The appropriate tool method with the arguments provided by the model is invoked.
    • Element Location (if required by the tool): If the requested tool needs to interact with a specific UI element (e.g., clicking an element), the element is located using the ElementLocator class based on the element’s description (provided as a parameter for the tool). (See “UI Element Location Workflow” below for details).
    • Retry/Rerun Logic: If a tool execution reports that retrying makes sense (e.g., an element was not found on the screen), the agent retries the execution after a short delay, up to a configured timeout (test.step.execution.retry.timeout.millis). If the error persists after the deadline, the test case execution is interrupted.
  4. Verification Processing (for each Verification step):
    • Delay: A short delay (action.verification.delay.millis) is introduced to allow the UI state to change after the preceding action.
    • Screenshot: A screenshot of the current screen is taken.
    • Vision Model Interaction: A verification prompt containing the expected results description and the current screenshot is sent to the configured vision AI model. The model analyzes the screenshot and compares it against the expected results description.
    • Result Parsing: The model’s response contains information indicating whether the verification passed, and extended information with the justification for the result.
    • Retry Logic: If the verification fails, the agent retries the verification process after a short interval ( test.step.execution.retry.interval.millis) until a timeout (verification.retry.timeout.millis) is reached. If it still fails after the deadline, the test case execution is interrupted.
  5. Completion/Termination: Execution continues until all steps are processed successfully or an interruption (error, verification failure, user termination) occurs.

UI Element Location Workflow

The ElementLocator class is responsible for finding the coordinates of a target UI element based on its natural language description provided by the instruction model during an action step. This involves a combination of RAG, computer vision, analysis, and potentially user interaction (if run in attended mode):

  1. RAG Retrieval: The provided UI element’s description is used to query the vector database, where the top N (retriever.top.n) most semantically similar UiElement records are retrieved based on their stored names, using embeddings generated by the all-MiniLM-L6-v2 model. Results are filtered based on configured minimum similarity scores (element.retrieval.min.target.score for high confidence, element.retrieval.min.general.score for potential matches).
  2. Handling Retrieval Results:
    • High-Confidence Match(es) Found: If one or more elements exceed the MIN_TARGET_RETRIEVAL_SCORE:
      • Visual Template Matching: OpenCV’s template matching function is used to find potential occurrences of each high-confidence element’s stored screenshot on the current screen image. Multiple matches might be found for a single element screenshot due to visual similarities or repeating patterns if they exceed the similarity threshold (element.locator.visual.similarity.threshold).
      • Disambiguation (if needed): The vision model is employed to find the single element that matches the target element’s description and the description of surrounding elements (anchors), based on the screenshot showing all found visual matches highlighted with distinctly colored bounding boxes. If the vision model identified no match at all, user interaction is required in attended mode (see below); otherwise, the element location returns no results.
    • Low-Confidence/No Match(es) Found: If no elements meet the MIN_TARGET_RETRIEVAL_SCORE, but some meet the MIN_GENERAL_RETRIEVAL_SCORE:
      • Attended Mode: The agent displays a popup showing a list of the low-scoring potential UI element candidates. The user can choose to:
        • Update one of the candidates by refining its name, description, or anchors and save the updated information to the vector DB.
        • Delete a deprecated element from the vector DB.
        • Create New Element (see below).
        • Retry Search (useful if elements were manually updated).
        • Terminate the test execution (e.g., due to an AUT bug).
      • Unattended Mode: The location process fails.
    • No Matches Found: If no elements meet even the MIN_GENERAL_RETRIEVAL_SCORE:
      • Attended Mode: The user is guided through the new element creation flow:
        1. The user draws a bounding box around the target element on a full-screen capture.
        2. The captured element screenshot with its description are sent to the vision model to generate a suggested detailed name, self-description, and surrounding elements (anchors) description.
        3. The user reviews and confirms/edits the information suggested by the model.
        4. The new UiElement record (with UUID, name, descriptions, screenshot) is stored into the vector DB.
      • Unattended Mode: The location process fails.

Setup Instructions

Prerequisites

Maven Setup

This project uses Maven for dependency management and building.

  1. Clone the Repository:
    git clone <repository_url>
    cd <project_directory>
    
  2. Build the Project:
    mvn clean package
    

    This command downloads dependencies, compiles the code, runs tests (if any), and packages the application into a standalone JAR file in the target/ directory.

Vector DB Setup

Instructions for setting up the currently only one supported vector database Chroma DB could be found on its official website.

Configuration

Configure the agent by editing the config.properties file or by setting environment variables. Environment variables override properties file settings.

Key Configuration Properties:

How to Run

Standalone Mode

Runs a single test case defined in a JSON file.

  1. Ensure the project is built (mvn clean package).
  2. Create a JSON file containing the test case (see this one for an example).
  3. Run the Agent class directly using Maven Exec Plugin (add configuration to pom.xml if needed):
    mvn exec:java -Dexec.mainClass="org.tarik.ta.Agent" -Dexec.args="<path/to/your/testcase.json>"
    

    Or run the packaged JAR:

    java -jar target/<your-jar-name.jar> <path/to/your/testcase.json>
    

Server Mode

Starts a web server that listens for test case execution requests.

  1. Ensure the project is built.
  2. Run the Server class using Maven Exec Plugin:
    mvn exec:java -Dexec.mainClass="org.tarik.ta.Server"
    

    Or run the packaged JAR:

    java -jar target/<your-jar-name.jar>
    
  3. The server will start listening on the configured port (default 7070).
  4. Send a POST request to the /testcase endpoint with the test case JSON in the request body.
  5. The server will respond immediately with 200 OK if it accepts the request (i.e., not already running a test case) or 429 Too Many Requests if it’s busy. The test case execution runs asynchronously.

Contributing

Please refer to the CONTRIBUTING.md file for guidelines on contributing to this project.

TODOs

Final Notes