phonedriver 如何把 AI 智能體的手機畫面讀取降至 59 tokens、13ms,毋須截圖或安裝應用程式
How I got a phone screen down to 59 tokens and 13ms for AI agents (without screenshots or an installed app)
作者開發 phonedriver,讓 AI 智能體無需截圖即可操作 Android、iOS;單次畫面讀取為 59 tokens,Android API 37 模擬器實測 12.7 ms。
Scroll a long list on Android and something sneaky happens behind the glass. The view holding "Row 13" does not scroll off the top and vanish. Android peels off its label and hands the exact same node ID to "Row 29" down at the bottom. An AI agent tracking that ID will happily tap sixteen rows off, and Android will return a polite ok.
Most mobile-agent headaches look like that. Reading an accessibility tree fast is the easy half. The hard half is keeping element references honest across scrolls, knowing when a screen has actually stopped moving without hardcoded sleeps, and returning only what changed so the model isn't paying to re-read the whole phone on every turn.
I built phonedriver (Rust, AGPL-3.0, zero telemetry) to solve this for both Android and iOS—over MCP (Claude Code, Codex, Cursor, VS Code, Gemini CLI) or as a plain CLI. Here are the concrete systems tricks, the benchmarks, and the weird OS bugs that actually bit me along the way.
1. What the model sees: 461 bytes instead of 25 KB of XML
Instead of shipping a screenshot or 25 KB of nested XML on every turn, phonedriver prunes the accessibility tree into a numbered list of things a thumb can touch or an eye needs to read:
$ phonedriver snapshot
app com.android.settings (Settings)
@e1 button "Search Settings"
@e2 group scrollable↓
@e3 button "Google" "Services & preferences"
@e4 button "Network & internet" "Mobile, Wi‑Fi, hotspot"
@e5 button "Connected devices" "Bluetooth, pairing"
...
@e10 button "Display & touch" "Dark theme, font size, touch"
Tap @e10, wait for the Display screen to settle, then tap the Dark theme switch (@e24). Instead of dumping the whole screen again, phonedriver replies with just the diff (~20 tokens):
$ phonedriver tap @e24
ok tapped @e24 "Dark theme"
~ @e23 button "Dark theme" "Will turn on when Bedtime starts" → "Will never turn off automatically"
~ @e24 switch "Dark theme" off → on
+ appeared, - disappeared, ~ changed. If more than 60% of the screen's refs turn over, you navigated somewhere new and phonedriver sends a fresh snapshot.
On a real HONOR X8's Display settings page, adb shell uiautomator dump emitted 25,334 bytes of XML. phonedriver sent 461 bytes. Four pruning rules did most of the work:
- Drop invisible and off-screen nodes.
- Hoist child
TextViewlabels onto clickable wrapper layouts (on Android, the actual tap target is usually an anonymousLinearLayoutwrapping two text nodes). - Collapse single-child decorative containers.
- Render the on-screen keyboard as one
keyboardline instead of 60 individual keys, so opening the keyboard stops looking like a brand-new screen in every diff.
To prevent the recycled-row bug (in my API 37 spike, scrolling a 1,000-row ListView kept node ID -4294967273 alive while its text flipped from "Row 13" to "Row 29"), a ref only follows a platform node ID when the role still matches and either the label is untouched or the bounds drifted less than 8 points. Every tap re-resolves against a fresh tree, failing cleanly with the closest match instead of tapping whoever took its chair.
2. Why adb uiautomator dump burns 2.2 seconds per glance
Every adb shell uiautomator dump greets your phone like a stranger: AOSP's wrapper spawns a fresh app_process, opens a new UiAutomation connection, calls waitForIdle(1000, 10000) (insisting on one full second with zero accessibility events), and writes XML to disk.
On an API 37 emulator (median of 50 runs), that took 2,163.7 ms. Worse, on a real HONOR X8 (Android 13), uiautomator dump sat on the main Settings page for 11.5 seconds and gave up with ERROR: could not get idle state. because something on that page never goes idle.
phonedriver borrows scrcpy's cleanest trick: push a ~40 KB dex jar over adb and start it via app_process as the shell user. No APK installed, no root, no AccessibilityService to toggle in Settings. When the daemon disconnects, the helper exits and leaves nothing behind.
Inside the helper:
-
UiAutomation(Looper, IUiAutomationConnection)+ hiddenconnect(int)keeps the accessibility bridge warm. - Touches go directly through
InputManager. - A
MediaCodecH.264 stream mirrors the display to the host daemon.
| Operation (median of 50 runs) | phonedriver | plain adb
|
|---|---|---|
| Screen read (API 37 emulator) | 12.7 ms | 2,163.7 ms |
| Screen read (HONOR X8, Android 13) | 78.5 ms | 2,507 ms |
| HONOR X8 Settings home page | 110 ms | failed after 11.5 s |
| Screenshot (API 37 emulator) | 9 ms | 291 ms |
| Type 100 characters (API 37 emulator) | 158 ms | 3,638 ms |
Real Android bugs that bit me along the way
-
Stale caches: Because the helper doesn't subscribe to content events,
AccessibilityInteractionClientserves stale trees unless you callclearCache()before every read. On Android 12 (API 31), that method has a different signature (NoSuchMethodException: clearCache [int]), filed in issue #7 at 03:19 UTC and patched via reflection fallback by 07:05. -
Unbinding TalkBack: Passing
0toconnect()quietly kills active accessibility services. PassingFLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICESkeeps TalkBack bound. -
Idle encoder silence:
MediaCodecis not a steady heartbeat. On a motionless screen it burst at ~10 fps and then went silent for up to 5 seconds—breaking 18/40 idle screenshots until we stopped treating silence as a stalled socket. - Samsung silent encoder: On a Galaxy A53 (One UI 8, PR #22), the encoder emitted zero frames at all; a contributor fixed it by routing through an OpenGL relay.
-
Apps that hide their tree: WeChat returns an empty root (
[0,0][0,0], no children), so when a screen is hollow phonedriver automatically falls back to local OCR on pixels.
3. Knowing when the screen stopped moving
Fixed sleep(2) calls are either sluggish or flaky, and accessibility events fire constantly for blinking carets and ticking clocks.
Instead, the host daemon decodes the H.264 stream with OpenH264 and diffs a 4×4-point luma thumbnail of each frame against the previous one.
My first threshold was 4,096 pt² (a 64×64-point square) to ignore blinking cursors and small spinners. Page transitions worked great. Material switches failed completely: 0 of 20 toggle taps ever reached 4,096 pt², so phonedriver kept saying changed: false after flipping a switch.
The fix was a two-phase settle detector:
- Wait up to 500 ms (3 s after
launch) for a window event or any pixel change above 128 pt² (just past a caret). - Once motion starts, wait for 250 ms of quiet with no frame above 4,096 pt².
4. iOS: SimulatorKit HID ports, curled quotes, and 1.2 GB of secret Xcode videos
On iOS, phonedriver runs a minimal Objective-C XCTest runner speaking length-prefixed JSON on TCP port 27753 (skipping WebDriverAgent's HTTP + XPath layers). Querying eight raw accessibility attributes directly read an iPhone 17 Simulator screen in 22.2 ms vs. WDA's 380.4 ms at depth 30 (44.8 ms with every WDA option tuned).
On the Simulator, three wild quirks jumped out during benchmarking:
-
XCTest burns ~330 ms before the app sees a tap. Routing Simulator taps straight through SimulatorKit's private HID port (the path
idbuses) cut tap-and-settle from 0.84 s to 0.32 s onsimulator-use's benchmark. -
HID typing is fast and silently broken. Sixteen characters landed in under 10 ms—and turned
x "q" 'r' -- teh ok. Gary@Mail.comintox ‘q’ ‘r’ — teh ok. gary2mail.com(dropped Shift + smart punctuation). So typing stays on XCTest, which is exact (simulator-usebeats phonedriver on Simulator typing because its hardware keys hide the on-screen keyboard, while phonedriver keeps the keyboard up like a real iPhone). -
Xcode was filming every session. Because the runner is a long UI test,
.xctestrundefaulted toPreferredScreenCaptureFormat = screenRecording. I opened the Simulator'stestmanagerdfolder and found 154 QuickTime movies (1.2 GB total), plus 84DerivedDatafolders eating 940 MB. SettingsystemAttachmentLifetime = keepNeverandpreferredScreenCaptureFormat = screenshotsshut it off.
And as of 0.1.6, a community contributor (Coreho, PRs #23 and #29) wired up physical iPhone control over USB and Wi-Fi from Windows with no Mac, using Sideloadly + idevice!
5. Cutting tokens by 6.9x (and down to 0 in CI)
Across 9 real Android jobs with Claude Sonnet 5.5 (cropping a photo, changing Chrome settings, pinning/archiving Messages, restricting a wakelock app, hunting planted signup bugs—all graded strictly against device state):
| Tool | Passed | Total Tokens (sum of medians) | Wall Time |
|---|---|---|---|
| phonedriver | 27 / 27 | 657,542 | 5.1 min |
| mobile-mcp | 17 / 18 | 4,567,200 | 8.7 min |
| phone-harness | 14 / 18 | 1,130,000 | 22.7 min |
Two small token audits moved the needle even further:
-
Say every fact once: Removing 8 tiny reply habits (like printing
typed 16 chars into @e3 · verifiedright above a diff line showing those exact 16 characters) dropped a sign-in flow from 300 tokens to 173 (a single screen read is 59 tokens). - Starve the MCP schema: Every turn pays for your tool list. Hiding unused optional parameters and tightening descriptions (again in 0.1.7) put all 17 tools under 1,800 tokens, compared to 27,918 tokens (63 tools) and 36,826 tokens (71 tools) on other mobile MCP servers measured in the same harness.
And once an agent works out a flow, you don't need to pay for the LLM again:
phonedriver save signup.steps
phonedriver replay signup.steps --var email=test+{{run}}@example.com
Replay runs deterministically with zero model tokens (109/110 passed across 11 Android jobs), supports PHONEDRIVER_SECRET_1 env vars for unattended CI logins, and ships as a GitHub Action.
6. Stopping the agent before it spends your money
By default, phonedriver pauses any action that would hit Pay, Buy now, Buy with GPay, Place order, Transfer, or Delete account (labels in 11 languages) and triggers MCP elicitation directly to the client UI. The model never sees the prompt and cannot answer it.
After an outside security review in 0.1.7 (giulioc84, #32–#39), that gate now inspects swipes, drags, pinches, scrolls, press enter, and field clears—not just taps—and binds each approval strictly to the exact button and details shown. --secret values are scrubbed before logs, traces, replays, or truncation.
Honest limits
- The payment guard matches text labels, so an icon-only Pay button can slip past it (and
autonomous: truebypasses it by design). - Apps with no accessibility tree (games, custom canvases, WeChat) rely on local OCR, which is slower and less exact than native trees.
- Hidden multi-agent Android virtual displays (Android 13+) only work while the phone is unlocked, and normal single-task Android apps can only live on one display at a time.
- It never enters a passcode or passes biometrics on a physical phone.
Try it in one command
npx -y phonedriver init
That registers phonedriver with Claude Code, Codex, Cursor, VS Code, or Gemini CLI and checks your adb/Xcode/device setup.
- GitHub (AGPL-3.0, zero telemetry): https://github.com/hridaya423/phonedriver
- All raw benchmark runs & CSVs (including the steps we lose): https://phonedriver.dev/benchmarks
來源:DEV Community · dev.to