How AI Agents Control Mobile Phones: Architecture and Practices

    This article explains how AI agents can operate mobile devices by separating reasoning from execution. It presents a four-layer architecture, a tool abstraction layer that turns device capabilities into callable functions, accessibility-based screen reading, and a closed execution loop for taps and text input. It also covers deployment models, security and compliance requirements, common failure modes, and tuning strategies, giving readers a reusable technical blueprint for building controllable and observable device automation.

    1. Background: Why “Thinking” Is Not the Same as “Acting”

    LLM-powered agents are already mature in text and structured-data scenarios. Once a task moves to a real phone, however, a natural gap appears: the model can only output intent and cannot directly touch the operating system. When a user says “open Settings, take a screenshot, and describe the current screen,” the model can plan the steps but has no hands to tap the screen.

    The solution is to split the capability into two layers: one that handles understanding, planning, and decision-making, and another that executes screen reading, tapping, typing, swiping, screenshots, and result reporting on the device. This separation of “brain and hands” is currently the most common and easiest-to-maintain engineering paradigm for agent-driven device automation.

    This article does not focus on any specific product. Instead, it abstracts a reusable technical architecture. Regardless of the underlying coding tool or in-house agent framework, the layering principles and interface contracts remain the same.

    2. Overall Architecture: Four Decoupled Layers

    A robust solution is typically divided into four layers:

    1. Decision layer: the LLM agent, responsible for task decomposition, tool selection, retry on failure, and result summarization.
    2. Tool abstraction layer: packages device capabilities into a set of semantically clear functions, such as open app, screenshot, tap, type text, swipe, and read UI structure.
    3. Bridge and forwarding layer: a relay service running locally or at the edge that handles unified authentication, rate limiting, logging, and protocol conversion while hiding device differences.
    4. Device execution layer: a companion app running inside the phone system that performs actual operations using the accessibility and screen-capture capabilities provided by the OS.

    The four layers communicate only through explicit contracts. Replacing any layer does not affect the others, which is the key to making the system testable and extensible.

    3. Tool Abstraction: Turning Device Capabilities into “Callable Verbs”

    The goal of the tool layer is to free the model from low-level details. A common approach is to expose a set of functions with a unified prefix, semantic naming, and simple parameters:

    1. # Illustrative interface only; it expresses the abstraction and does not point to any specific implementation
    2. def open_app(name: str) -> dict: ...
    3. def screenshot() -> bytes: ...
    4. def tap(x: int, y: int) -> dict: ...
    5. def tap_text(text: str) -> dict: ...
    6. def type_text(text: str) -> dict: ...
    7. def swipe(x1: int, y1: int, x2: int, y2: int, duration_ms: int = 300) -> dict: ...
    8. def dump_ui() -> dict: ...

    There are three design points. First, return values are unified structured results containing a success flag, elapsed time, error code, and human-readable description, making it easier for the model to decide the next step. Second, coordinate-based and semantic operations coexist: the former serves as a fallback, while the latter (such as tapping by text) is more stable. Third, all tools are idempotent or retryable to avoid side effects from repeated taps.

    4. Screen Reading: Letting the Agent “See” the Interface

    What really makes an agent robust is not the screenshot but the UI structure. A system-level accessibility service can read the control tree of the current window, including control type, text, clickability, bounds, and hierarchy. After this information is organized into a compact structured node tree and returned, the model can accurately determine where the buttons are, where the input fields are, and which areas are clickable.

    Three practices are recommended. First, pruning: filter out invisible and semantically empty nodes to control context length. Second, labeling: assign a stable ID to each interactive node so the model operates by ID rather than raw coordinates. Third, snapshot comparison: capture the structure before and after an action and use the diff to determine whether the action took effect.

    1. // Simplified UI structure example
    2. {
    3. "screen": "settings",
    4. "nodes": [
    5. {"id": "n1", "type": "button", "text": "WLAN", "clickable": true, "bounds": [0,120,1080,240]},
    6. {"id": "n2", "type": "text", "text": "Connected", "clickable": false, "bounds": [40,250,600,300]}
    7. ]
    8. }

    5. Tapping and Typing: Closing the Execution Loop

    A tap can be completed through semantic tapping via accessibility, or it can fall back to coordinate injection. Text input usually calls the system input capability to write a string into the currently focused control. Screenshots and screen recording depend on the system’s screen-capture authorization. A typical call chain is: the model issues open app -> wait for the UI to stabilize -> read the structure -> locate the target node -> perform a tap or input -> read the structure again to verify -> summarize the result.

    The “wait” problem must be handled in engineering. UI loading is inherently uncertain. Polling with a timeout is recommended: repeatedly read the structure until the target node appears or the operation times out and fails, instead of using a fixed sleep.

    1. Model: open_app("Settings")
    2. Bridge: forward execution -> return {ok:true, cost:820ms}
    3. Model: dump_ui()
    4. Bridge: return node tree (pruned, 12 interactive nodes)
    5. Model: tap_text("WLAN")
    6. Bridge: verify structural diff before/after -> {ok:true, changed:3}
    7. Model: summarize the current screen state

    6. Deployment Models: On-Device Execution and Edge Collaboration

    There are two common models. The first is device self-contained: the agent CLI runs in a terminal emulation environment on the phone, the bridge app runs on the same device, and the two communicate over the local loopback address without external network access. The second is edge collaboration: the agent runs on a personal computer or edge node, and the phone connects as the execution end on the same local network.

    Pairing uses a one-time short-code mechanism: the bridge app displays a six-digit pairing code, and the agent side submits the code via natural language or a command to complete binding. The binding information is persisted and reused later. The advantages are zero configuration and offline availability; the drawback is limited device compute and battery life, making it suitable for lightweight tasks.

    7. Security and Compliance: A Checklist You Cannot Skip

    Device control is inherently a high-risk capability and must default to least privilege:

    • Explicit authorization: sensitive permissions such as accessibility, floating windows, and screen capture are enabled manually by the user and can be revoked at any time.
    • Local channels: prefer loopback or LAN and avoid exposing control commands to the public internet.
    • Command allowlist: actions involving payment, deletion, or sending require secondary confirmation or are placed on a deny list.
    • Full audit: log the input parameters, results, screenshot summaries, and elapsed time of every tool call for traceability.
    • Sensitive-data masking: fields such as account credentials and verification codes that appear in the structure tree and screenshots are masked before being returned.
    • Circuit breaker: automatically stop when consecutive failures occur or an abnormal screen is detected, and hand control back to the user.

    8. Common Failure Modes and Tuning

    The first is localization failure, where a semantic tap misses because the control text changes; fall back to the structural ID or coordinates and add candidate retries. The second is timing failure, where an operation happens before the UI is ready; replace fixed waits with polling. The third is context bloat, where the full control tree is too long and needs pruning and pagination. The fourth is repeated side effects, where retries cause multiple submissions; introduce an idempotency key for actions. The fifth is permission drift, where authorization is reset after a system upgrade; run a capability self-check at startup and prompt for re-authorization.

    9. Conclusion

    The essence of an agent controlling a phone is to fully decouple “understanding” from “execution” and connect both ends with stable tool contracts. By adhering to layered design, structured screen reading, explicit authorization, and full auditing, you can build a controllable, observable, and extensible automation capability on your own device, and add logging services, monitoring alerts, and containerized scheduling on demand on general cloud infrastructure such as Baidu AI Cloud to form a complete engineering loop.