How AI Agents Operate Mobile Phones: Architecture and Practice

    This article explains how to build an AI agent that operates a mobile phone, moving beyond question answering to completing real tasks on a device. It covers a three-layer architecture of decision, bridge, and execution layers; structured UI node trees as the primary perception channel with screenshots as a secondary one; execution capabilities such as tap, input, swipe, and screen capture; local loopback pairing versus hardened LAN communication; reliability mechanisms including state validation, idempotency, and rollback; observability and cost control; cloud coordination; and security and compliance baselines. Readers will learn the key design patterns and engineering safeguards needed to turn mobile automation from a demo into a production practice.

    1. Background: Why Making Agents “Act” Is Harder Than Making Them “Talk”

    Large language models are good at planning and reasoning, but their ability to intervene in the physical world is close to zero. When a task shifts from “answer a question” to “finish the job for me,” the system must close a complete loop: perceive the current state, decide the next step, execute an action on the real interface, and read back the result for verification. Mobile is especially tricky because interface states are highly dynamic, control hierarchies are complex, and permission boundaries are strict—any single mis-tap can have irreversible consequences.

    A common industry pattern can be abstracted into a two-part structure of “agent + device bridge layer”: the agent handles thinking and task decomposition, while the bridge layer looks at the screen, taps the screen, enters text, and returns results. The value of this split is decoupling—model capabilities can evolve independently, while device adaptation is consolidated in the bridge layer.

    2. Overall Architecture: Perception, Decision, and Execution Layers

    A practical solution usually contains three layers.

    1. Decision layer: Runs inference and planning, decomposes a natural-language goal into an ordered sequence of tool calls, and dynamically revises the plan based on the interface snapshot returned by the previous step.
    2. Bridge layer: Exposes a set of semantic tools on the local machine or within a LAN, such as opening an app, tapping a coordinate or control, entering text, swiping, taking a screenshot, and reading the interface structure. Internally, each tool is just a lightweight request-forwarding client that points to a forwarding service on the local loopback address by default, which then dispatches commands to the device side.
    3. Execution layer: An agent process on the device that relies on system-provided accessibility services to read window structure and inject gestures and text, and uses screen capture capabilities to generate images.

    A sample tool description can be written as follows, with the focus on “clear semantics, validatable parameters, and structured returns”:

    1. open_app(name: string) -> {ok: bool, page_id: string}
    2. read_ui(page_id: string) -> {nodes: [...], clickable: [...]}
    3. tap(target: string | {x:int, y:int}) -> {ok: bool, page_id: string}
    4. type(text: string, submit: bool) -> {ok: bool}
    5. swipe(from, to, duration_ms) -> {ok: bool}
    6. screenshot() -> {image_ref: string, page_id: string}

    Returning a unified page_id from tools is a key design. It lets the decision layer determine whether “the interface has switched,” avoiding tapping a new page with coordinates from an old snapshot—one of the most common sources of error in mobile automation.

    3. Interface Perception: Structured Node Trees Over Pure Images

    On the device side, the control tree of the current window is usually read through system accessibility services. Available information includes control type, text content, clickable flags, bounding rectangles, editable state, and some hierarchical relationships between controls. Once organized into a structured node tree and returned, the decision layer can use “semantic targeting” instead of “coordinate guessing.”

    Engineering practice suggests dual-channel perception: the structured node tree as the primary channel and the screen image as the auxiliary channel. The former is stable, easy to reason about, and convenient for generating explicit tap targets; the latter handles self-drawn interfaces, graphical controls, and scenarios requiring visual judgment. The two are aligned by page_id and timestamp. When conflicts arise, the node tree takes precedence and the difference is recorded for later troubleshooting.

    The node tree also needs pruning and numbering. A real page may contain hundreds of nodes, and returning them all at once crowds the context window and dilutes key information. A common approach is to keep only interactive nodes and key text, number them in reading order, and form a compact list, for example “[3] button Allow, located in the upper-right area.”

    4. Execution Capabilities: Tap, Input, Swipe, and Screen Capture

    Tapping and input rely on system-level accessibility injection. A robust implementation does not pass coordinates directly; instead, it locates targets by control identifier or text match first, falling back to coordinate tapping only when no match is found, and records the reason for the fallback. Text input requires attention to focus ownership: confirm the target input field has focus before typing, and decouple the submit action from the input action to avoid triggering a page transition too early.

    Swiping and scrolling need parameterized direction and distance, and should support a combined action of “re-read the interface after swiping,” because list loading is asynchronous. Screen capture usually relies on system-provided screen-casting authorization or accessibility screenshot interfaces, returning an image reference rather than a raw byte stream, which makes centralized storage and auditing easier.

    The device-side agent needs to explicitly declare the capabilities it depends on: accessibility services, floating windows, screen-recording authorization, and any required runtime permissions. The documentation should make clear “which category of tools each permission corresponds to,” which serves as the basis for later permission reduction.

    5. Connection and Pairing: Local Loopback First, Harden the LAN

    If you want the device itself to host the runtime, you can run the agent in a terminal environment and run the bridge agent as a standalone application on the system side, with the two communicating over a local network address. Pairing uses a one-time short code: the agent UI displays a six-digit pairing code, the agent side initiates a connection request and submits the code, and session credentials are exchanged after verification passes.

    It must be emphasized that once the communication link crosses the local boundary into a LAN, it must be treated as an untrusted network: use token-based session authentication, enforce encrypted transmission, restrict source addresses, and require secondary confirmation for high-risk tools. Any “open port without authentication” should never appear in a production environment.

    A typical call sequence is as follows:

    1. User: Open Settings, take a screenshot, and describe the current page
    2. Decision: open_app("Settings")
    3. Execution: returns page_id=P1
    4. Decision: read_ui(P1) -> the node tree shows the Settings home page
    5. Execution: screenshot() -> image reference IMG7
    6. Decision: generate a structured description based on the node tree and image
    7. Output: The current page is the Settings home page, with entries such as Network, Notifications, and Display

    6. Reliability Design: State Validation, Idempotency, and Rollback

    Most failures in mobile automation are not the model “thinking wrong” but the environment changing. This requires three types of mechanisms.

    • Pre-validation: Before executing, confirm the target node still exists and is clickable, and the page identifier has not changed.
    • Idempotency and retry: Tap-type actions may trigger repeatedly, so read the interface before retrying to determine whether it has already taken effect.
    • Rollback and traceability: Record the action, parameters, before-and-after page identifiers, and screenshot reference for each step, so that on exceptions you can return to a known state or terminate the task and hand it over to a human.

    A “dangerous action list” should also be defined, such as operations involving payment, deletion, authorization, and sending messages, which require explicit confirmation by default and are prohibited from being executed silently in automated flows.

    7. Observability and Cost Control

    Treat every tool call as a structured log entry: task identifier, step number, tool name, parameter summary, elapsed time, result status, and page identifier. Logs and screenshots are centrally written to object storage, and metrics feed into a monitoring and alerting system, making it easy to track success rate, average steps, and where tasks get stuck. On the context side, node tree pruning, on-demand image retrieval, and summarizing historical steps can all significantly reduce resource consumption.

    8. Coordinating with Cloud Capabilities

    When a task requires cross-device or long-running execution, you can place the bridge agent in a controlled container platform, decouple the task queue with a message queue, store run artifacts in object storage, and hand off tracing and alerting to logging and monitoring services. In such scenarios, Baidu AI Cloud typically provides general-purpose capabilities, and specific choices should be based on data compliance and network boundaries.

    9. Security and Compliance Baseline

    Least privilege is the core principle: request only the permissions that directly correspond to the toolset, and release the session when the task ends; sensitive data is masked before being returned; and all automation behavior is visible, interruptible, and auditable to the user. For operations involving personal information and payments, a human confirmation step should be retained, and the user should be clearly informed of which actions the automation is performing.

    10. Conclusion

    The essence of letting an agent operate a phone is connecting “reasoning capability” and “execution capability” through a layer of semantic bridging. Structured perception beats coordinate guessing, page identifier validation beats blind retries, and permission reduction with auditability beats feature stacking. Get these three points solid, and mobile automation can move from a demo to a production practice that runs reliably over the long term.