Agent-Based Mobile UI Replication and Automated Acceptance Testing: A Practical Guide

    This article describes a practical workflow for replicating mobile interfaces and validating them automatically with the help of AI agents. It covers the scope and compliance boundaries of such work, a six-level grading model for replication goals, a five-step technical pipeline (device connection, structure and visual data collection, specification generation, code rebuilding, and on-device acceptance), best practices for agent operation, common pitfalls with solutions, and engineering recommendations for turning one-off UI replication into a repeatable automated acceptance process.

    1. Applicable Scenarios and Boundaries

    In mobile development, teams frequently encounter several types of requirements: migrating legacy interfaces, validating functional prototypes, checking cross-platform UI consistency, and running automated regression tests. These requirements share a common trait: an existing interface and its interaction flows must be fully described, re-implemented with self-developed code, and then verified for behavioral consistency.

    The entire process can be carried out with the help of an AI agent. The agent takes control of a phone through the device’s debugging channel, reads the UI hierarchy, captures screenshots, performs taps and text input, organizes observations into specification documents, and then drives developers to write code and complete acceptance testing.

    This approach has clear boundaries that must be defined upfront:

    • Use only publicly visible information. The observation targets are the rendered UI and user-triggerable interactions. No decompilation, no scraping of private data from third-party servers, and no bypassing of access controls.
    • Self-developed implementation; no copied assets. Icons, fonts, copy, trademarks, and illustrations protected by copyright or trademark law must not be copied directly and should be replaced with your own resources.
    • Use only within authorized scope. This applies to your own products, internal systems, applications you are authorized to work on, or research on publicly available functional prototypes.
    • Comply with platform terms of service. Use of debugging channels must not violate the target platform’s terms or local regulations.

    Define the boundaries first, then discuss technical details. For projects with ambiguous boundaries, subsequent technical choices and acceptance criteria lose their foundation.

    2. Define the Target Level First

    Replication work easily falls into disputes over “when is it done.” The solution is to grade the goal in advance, with verifiable criteria for each level.

    Level Name Acceptance Criteria
    L0 Static display Pages look similar but respond to nothing
    L1 Interactive shell Buttons are tappable, pages switch, data is fixed mock data
    L2 Basic state List add/remove, form submission, and simple state persistence work
    L3 Core flow parity Inputs, state transitions, and outputs of core flows match the original
    L4 Edge-case parity Behavior matches for network failure, empty data, permission denial, etc.
    L5 High-fidelity detail Animation timing, font sizes, spacing, and colors match at near-pixel level

    In practice, the recommended default target is L3. L0 and L1 pages look complete but cannot verify functionality and tend to produce deliverables full of static fake data. L3 requires core flows to run for real without excessive investment in pixel-level details. Only proceed to L4 and L5 when design review or visual regression explicitly requires it.

    3. The Five-Step Technical Pipeline

    The overall workflow can be divided into five stages, each producing inspectable artifacts.

    Step 1: Connect the Device

    Enable developer debugging options on the device, connect it to the workstation via cable, and confirm authorization on the device. The workstation then issues commands to the device over the debugging channel. Three things must be confirmed at this step: the device is reliably recognized, commands return results, and reconnection works automatically after disconnection.

    It is recommended to write device information into a configuration file rather than hardcoding it in scripts:

    1. device:
    2. serial: "<device serial number>"
    3. connect_timeout_s: 10
    4. reconnect_attempts: 3

    Step 2: Collect Structural and Visual Data

    This step collects two categories of data simultaneously.

    Structural data comes from the UI widget tree. Exported nodes typically include widget type, displayed text, resource identifiers, bounding coordinates, and flags such as clickable and scrollable.

    Visual data comes from screenshots. Screenshots can be used to extract primary and secondary colors, corner radii, estimated font sizes, and spacing. A common approach for color extraction is sampling key regions and counting the most frequent colors:

    1. from collections import Counter
    2. def dominant_colors(image, region, top_k=5):
    3. """Count the most frequent colors in a region for palette replication."""
    4. x, y, w, h = region
    5. pixels = [
    6. image.get_pixel(px, py)
    7. for px in range(x, x + w)
    8. for py in range(y, y + h)
    9. ]
    10. counter = Counter(pixels)
    11. return [color for color, _ in counter.most_common(top_k)]

    Two caveats during collection. First, the widget tree only describes widgets the system can recognize; custom-drawn controls and image buttons may be missing information and should be manually annotated against screenshots. Second, the same page collected at different times will differ in dynamic content (timestamps, avatars, randomized recommendations). Record these regions during collection so they can be masked during later comparison.

    Step 3: Produce Structured Specifications

    The raw collected data should be organized into two tables, which serve as the basis for both development and acceptance.

    Per-screen UI difference table records each element’s attributes by page:

    Page Element Position Size Color Corner Radius Font Size Notes
    Home Top title Top left Height 48 #1A1A1A None 18 Text centered
    Home Feature card Center Width 340 #FFFFFF 12 14 Subtle shadow

    Behavior audit table records state changes before and after each action:

    Step Action Pre-State Post-State Expected Result
    1 Tap “New” List is empty Input dialog appears Input field gains focus
    2 Enter text and confirm Input field focused New item added to list List count increases by 1
    3 Disconnect network and confirm Network normal Failure message shown Data preserved, retry possible

    The behavior audit table is the core of L3 and above. It turns “looks the same” into “transitions the same,” making acceptance verifiable item by item.

    Step 4: Rebuild the Code

    The rebuild consists of client and server parts.

    The client handles UI rendering and interaction. It should use the target platform’s native development framework and reproduce layouts, colors, and font sizes according to the difference table. The server handles business state and data persistence. Its APIs are designed by the developers themselves and must not copy any external API’s paths or field names.

    A reference state model:

    1. from dataclasses import dataclass, field
    2. from enum import Enum
    3. class PageState(Enum):
    4. EMPTY = "empty"
    5. LOADING = "loading"
    6. READY = "ready"
    7. ERROR = "error"
    8. @dataclass
    9. class ListPage:
    10. state: PageState = PageState.EMPTY
    11. items: list = field(default_factory=list)
    12. def on_add(self, text: str) -> None:
    13. if not text.strip():
    14. return
    15. self.items.append(text.strip())
    16. self.state = PageState.READY

    The state model should map directly to the “pre-state” and “post-state” columns of the behavior audit table, so every code branch has an explicit acceptance basis.

    Step 5: On-Device Acceptance

    Acceptance runs on the same device. The original app and the rebuilt version are installed side by side, navigated to the same pages in sequence, and compared screen by screen via screenshots.

    There are three comparison methods:

    1. Screenshot comparison: Compute pixel differences between two screenshots of the same page and highlight regions exceeding a threshold. Mask dynamic regions according to the records from Step 2.
    2. Widget tree comparison: Check whether key widgets exist, whether positions fall within tolerance, and whether text matches.
    3. Flow replay: Execute the steps from the behavior audit table and verify that each step’s post-state matches expectations.

    Acceptance results should be saved as a report, including passed items, failed items, failure screenshots, and reproduction steps.

    4. How to Use the Agent

    The agent handles execution and organization in this workflow, but it cannot replace the specification. The recommended division of labor is:

    • Specifications (difference table and audit table) are confirmed by humans before being handed to the agent for rebuilding tasks.
    • The agent takes a screenshot before each action and verifies the current page matches expectations, avoiding operations on the wrong page.
    • The action scope is restricted by a whitelist: only basic actions such as tap, scroll, and input are allowed; task-irrelevant system-level commands are forbidden.
    • Irreversible operations—deleting data, submitting forms, changing settings—require human confirmation.

    These constraints reduce losses from agent misoperation and make the execution process auditable.

    5. Common Problems and Solutions

    Problem 1: Missing or incomplete widget trees. Custom-drawn controls, game-style interfaces, and some image buttons cannot be captured from the widget tree. Solution: use screenshots as the primary basis, manually annotate key regions, and note the data source in the specification.

    Problem 2: Dynamic content causes frequent comparison failures. Timestamps, avatars, recommendation slots, and randomized data differ every time. Solution: maintain a masked-region list, skip these regions during comparison, and separately verify that their structures exist.

    Problem 3: Fixed waits make execution unstable. When network loading is slow, fixed sleep durations cause false failures. Solution: wait for explicit conditions—such as a widget appearing or a text disappearing—with a timeout ceiling.

    Problem 4: Permission dialogs and exception states interrupt flows. First-launch authorization requests and network-failure prompts change the page state. Solution: model these situations as independent branches in the state model rather than handling them ad hoc in scripts.

    Problem 5: Long flows are hard to debug. Solution: split flows into independent sub-flows and save a state snapshot at the end of each segment. When a step fails, resume investigation from the nearest snapshot.

    6. Compliance and Engineering Recommendations

    The technology can be used in legitimate R&D scenarios, but the following requirements should be made explicit at project initiation:

    • The replication target must be your own product, an authorized product, or a publicly available functional prototype.
    • All produced code, APIs, data structures, and UI assets are self-developed, with no direct copying of third-party resources.
    • Do not collect, store, or forward users’ personal information. If testing requires real accounts, use dedicated test accounts and clean up data after testing.
    • Released products must not use names, logos, or promotional copy identical or similar to third parties, to avoid confusion.

    At the engineering level, the following practices are recommended:

    1. Put specification files under version control so every change is recorded.
    2. Run the full regression acceptance after every code change, not just on the modified pages.
    3. Save logs and screenshots from every run so failures can be reproduced.
    4. Move masked regions, tolerance thresholds, and similar parameters into configuration instead of hardcoding them.

    Following this approach, a team can turn one-off UI replication work into a repeatable automated acceptance pipeline. Specification, execution, and acceptance are separated, each stage has explicit outputs, and the project’s controllability and handover quality improve significantly.