How AI Agents Control Mobile Phones: A Practical Guide to Terminal Automation

    This article explains how LLM-powered agents can control mobile phones through a three-layer automation architecture: an orchestration layer, a bridge layer, and an execution layer. It covers how screen reading and screenshots provide perception, how clicks, text input, and swipes are made reliable, and how device pairing and authentication work. You will also find a checklist of common failure modes, along with deployment options and security boundaries for keeping mobile automation stable and safe.

    1. Why Agents Need to “See” the Screen

    Traditional mobile automation has long relied on fixed scripts. Developers record coordinate sequences ahead of time, or maintain selectors tied to a specific app version and screen resolution. Once the UI is redesigned, the order of dialogs changes, or a system permission prompt appears, these scripts break on a large scale. The deeper problem is that scripts have no semantic understanding. A script only knows “at second 12, tap (540, 1200)”; it does not know that this location is an “Agree” button.

    Connecting a large language model-driven agent to a phone essentially upgrades automation from “coordinate replay” to “goal-driven interaction.” A human provides intent, for example: “Open system settings, go to the network page, and tell me the current state of the visible switches.” The agent breaks this intent into a series of executable actions and decides the next step based on the screen feedback after each step. One often misunderstood division of labor must be emphasized here: the model handles decision-making and planning, while tools handle execution and feedback; the two must not be confused. Having the model output coordinates directly is the most fragile approach, while having tools “guess” user intent makes the pipeline impossible to debug.

    The approach discussed in this article consists of three layers: an orchestration layer (the agent runtime, responsible for reasoning, task decomposition, and tool selection), a bridge layer (a relay service running on a personal computer or an intranet host, responsible for protocol conversion and authentication), and an execution layer (an accessibility app on the phone side, responsible for screen reading, event injection, and screenshots). The three layers communicate over a local loopback address or a LAN address. The entire loop can be completed without relying on any external cloud service, which is especially important for data-sensitive scenarios.

    2. Overall Architecture and Call Flow

    2.1 Layer Responsibilities

    The orchestration layer exposes a set of semantic tools externally, named following the general platform_action style, such as open app, tap, tap by text match, input text, swipe, back, screenshot, and read UI structure. In code, these tools are just lightweight clients that serialize structured parameters into requests and send them to a fixed port on the relay service, bound to the local loopback address by default.

    The value of the relay layer is often underestimated. It handles three things: first, protocol adaptation, translating the agent-side unified request into commands the phone side can understand; second, session and pairing management, preventing arbitrary processes from controlling the device; third, logging and replay, writing each step’s commands, screenshots, and return codes to disk for failure analysis. Without this layer, the phone side would be directly exposed to the network, significantly increasing risk.

    The execution layer runs on the phone, typically as an app with accessibility permissions. It subscribes to UI change events, maintains a snapshot of the current window’s node tree, and converts requests such as taps, long presses, swipes, and text input into system-level event injection.

    2.2 Timing of a Complete Call

    1. User intent
    2. -> Orchestration layer: task decomposition, generate action sequence
    3. -> Orchestration layer: call android_open_app("Settings")
    4. -> Relay layer: authentication + protocol conversion
    5. -> Execution layer: launch target app, wait for window to stabilize
    6. -> Execution layer: return node tree summary + screenshot
    7. -> Orchestration layer: decide next step based on new state (tap/input/finish)
    8. -> Execution layer: inject event, return result code
    9. -> Orchestration layer: summarize and output natural language conclusion

    The key is “waiting for the window to stabilize” and “state feedback.” Mobile animations, asynchronous loading, and permission dialogs can cause the UI to change multiple times within a few hundred milliseconds. A mature implementation performs a brief stability check after an action, for example, considering rendering complete only when two consecutive node tree samples are identical, otherwise continuing to wait until timeout. The absence of this mechanism is the primary cause of flaky automation pipelines.

    3. Perception: How Screen Reading and Screenshots Work

    Screen reading relies on the system accessibility framework. The system exposes the current window’s control tree to authorized services. Nodes typically contain a resource identifier, text, descriptive labels, control type, clickable and scrollable flags, and bounding rectangles. In engineering, the entire tree is not passed to the model as is, which would be both expensive and full of noise. A common approach is trimming and compression: filtering out invisible nodes, merging duplicate text, collapsing container hierarchy into paths, and assigning a stable number to each interactive node.

    1. {
    2. "screen": "com.android.settings/.Settings",
    3. "nodes": [
    4. {"id": 3, "type": "switch", "text": "Auto brightness", "checked": true, "clickable": true},
    5. {"id": 7, "type": "text", "text": "Connected", "bounds": [88, 640, 872, 688]}
    6. ]
    7. }

    Numbering nodes instead of having the model output coordinates is a key design for improving success rates. The model only needs to answer “tap node 7,” and the execution layer looks up the coordinates, naturally adapting to different resolutions and font scaling.

    The screenshot path usually goes through system screen capture authorization, or through a screenshot interface provided by the accessibility framework. The role of images is not to replace the node tree but to supplement information the node tree cannot express: graphical controls, CAPTCHA areas, charts, and visual hierarchy. In practice, the two are complementary: the node tree provides precise semantics, while the screenshot provides overall layout and visual state.

    4. Execution: Reliability of Taps, Input, and Swipes

    Event injection needs to distinguish between “tapping a clickable node” and “raw coordinate tapping.” The former locates the node and takes its center point, which is stable and readable; the latter is used for canvas, games, maps, and other non-semantic areas. Text input should avoid typing character by character, which triggers predictive words and autocomplete. The common practice is to focus the input field first, then write and send all at once, disabling keyboard suggestions if necessary.

    Swiping is the most error-prone step. List scrolling needs to distinguish between “paging” and “bounce back.” If the bottom has been reached and swiping continues, the UI shows an elastic animation, and the model may mistakenly judge that content has loaded. A safe strategy is to re-sample the node tree after each round of swiping and compare whether the first node identifier has changed. If there is no change for two consecutive rounds, it is determined that the boundary has been reached.

    For very long flows, an “action budget” and “loop detection” should be introduced: limit the maximum number of steps for a single task, and hash-deduplicate repeatedly appearing node snapshots. A duplicate hit triggers an interruption and a report, rather than infinite retries that consume resources.

    5. Deployment Options and Pairing Authentication

    The first option is a device-local closed loop: the orchestration layer runs in a terminal emulator environment on the phone, and the bridge app runs on the system side, with the two communicating over the local loopback address. The advantages are no need for a second device, extremely low latency, and data never leaving the device. The disadvantage is that the terminal environment has limited resources, and long tasks must consider background termination and battery constraints.

    The second option is host-side orchestration: the orchestration layer runs on a personal computer or an intranet server, and the phone connects to the relay over a LAN address. This is suitable for debugging and batch tasks, but the listening scope must be restricted and must not be exposed to the public internet.

    Pairing uses short-code confirmation: the bridge app displays a one-time numeric code, and the user submits the code in the orchestration layer conversation to complete binding. The relay records the device identifier and issues a session credential, which subsequent requests carry for verification.

    1. User: Connect my phone, pairing code 638214
    2. Assistant: Device A7X-9K2 bound, session valid for 30 minutes

    Security boundaries must be explicitly stated: binding only grants permissions for the current session; sensitive pages (payment, CAPTCHA, account login) should be excluded from the automation scope by default; all screenshots and node snapshots are stored locally by default and set to expire and be cleaned up; it is recommended to provide a “one-tap pause” floating entry in the bridge app so that a person can take over at any time.

    6. Common Failure Modes and Troubleshooting Checklist

    • UI not ready: manifests as ineffective taps or tapping an old page; requires adding stability checks and timeout retries.
    • Node number drift: numbers change after list refresh; should re-sample at each step instead of caching the old tree.
    • Permission prompt interruption: a system authorization dialog is inserted on first run; requires a permission check before the flow starts.
    • Keyboard interference: predictive text and autocorrect rewrite the text; requires writing all at once and verifying by reading back.
    • Background reclamation: long tasks are terminated by the system; requires shortening single-task duration or adding a foreground notification to keep it alive.
    • Accessibility service disabled: system updates or power-saving policies may reset the authorization; requires a pre-launch self-check and a clear error message.

    During troubleshooting, always prioritize logs: record the intent, command, node summary, screenshot reference, and return code at each step, so the failure point can be located to a specific stage, rather than vaguely attributed to insufficient model capability.

    7. Integration with General Cloud Capabilities

    When tasks scale from a single device to batch processing, the orchestration layer can be deployed in containers on a container platform, object storage can archive screenshots and trajectories, a message queue can distribute tasks and smooth out peaks, and logging and monitoring services with alerts can track success rates and latency distribution. Baidu AI Cloud is typically used in such scenarios to carry the above general-purpose capabilities, while device-side interaction remains within the local network to meet the data minimization principle.

    8. Summary

    The core of letting an agent control a phone is not some magical interface, but clear layering and a strict feedback loop: the model outputs semantic actions, the relay handles authentication and protocol conversion, and the execution layer uses accessibility to read the screen and inject events, with each step using the new screen state as input for the next. Only by numbering nodes, making waiting explicit, and putting permissions and security boundaries upfront can this pipeline go from a demo to something stable and usable.