android-pilot 0.2.0a1__tar.gz → 0.2.0a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: android-pilot
3
- Version: 0.2.0a1
3
+ Version: 0.2.0a2
4
4
  Summary: MCP server that lets an AI agent drive an Android device over adb
5
5
  Keywords: mcp,model-context-protocol,android,adb,automation,ai-agent
6
6
  Author: minhalvp
@@ -104,7 +104,11 @@ Add these after `"android-pilot"` in `args`:
104
104
  | `--device <serial>` | first device in `adb devices` | Choose a device when several are connected: a serial (`13b22d7f`), emulator (`emulator-5554`) or wireless device (`192.168.1.10:5555`, after `adb connect`) |
105
105
  | `--adb-path <path>` | `$ADB_PATH`, then `adb` on `PATH` | Pin the adb binary to use |
106
106
 
107
- The server prints the device and adb binary it chose to stderr.
107
+ The server starts even if adb or the device isn't ready yet, so you can plug
108
+ the phone in after starting your client. Until then, tools return an error
109
+ that says what's missing, and the next call looks again. A wrong `--adb-path`
110
+ (or `ADB_PATH`) stops the server at startup instead. The device and adb binary
111
+ it picks are printed to stderr.
108
112
 
109
113
  ## Tools
110
114
 
@@ -185,11 +189,14 @@ Pass `--adb-path` to pin a binary you trust instead of relying on `PATH`.
185
189
  | Symptom | Fix |
186
190
  |---------|-----|
187
191
  | Client can't start the server | Use the full path to `uvx` (`which uvx`) as `command`; GUI clients often don't share your shell's `PATH` |
188
- | `adb is not installed or not in PATH` | Install [platform-tools](https://developer.android.com/tools/releases/platform-tools), or pass `--adb-path /full/path/to/adb` |
189
- | `No devices connected` | Check the cable, enable USB debugging, run `adb devices` |
190
- | Device shows `unauthorized` | Accept the "Allow USB debugging" prompt; if it doesn't appear, run `adb kill-server` and retry |
191
- | `Device … not found` | `--device` must match the first column of `adb devices` exactly |
192
- | `adb … timed out after 30s` | The device or adb server is stuck: replug, or run `adb kill-server` |
192
+ | `adb is not on PATH` | Install [platform-tools](https://developer.android.com/tools/releases/platform-tools), or pass `--adb-path /full/path/to/adb` |
193
+ | Server exits with `adb not found at …` or `… is not executable` | `--adb-path` / `ADB_PATH` must point to the adb binary itself |
194
+ | `no devices connected` | Check the cable, enable USB debugging, run `adb devices`. No restart needed: the next tool call looks again |
195
+ | `device … is unauthorized` | Unlock the phone and accept the "Allow USB debugging" prompt; if it doesn't appear, run `adb kill-server` and retry |
196
+ | `device … is offline` | Reconnect the device (cable or wireless debugging), or run `adb kill-server` |
197
+ | `adb can't access device … no permissions` | Linux: install udev rules for Android devices (e.g. the `android-udev` package) and replug |
198
+ | `device … not found` | `--device` must match the first column of `adb devices` exactly |
199
+ | `adb … timed out after 15s` | The device or adb server is stuck: replug, or run `adb kill-server` |
193
200
  | `… changed or is gone; call snapshot again` | The screen changed since the snapshot. Call `snapshot` and retry |
194
201
  | `… moved and N elements now match it` | The element moved, and several identical ones (e.g. repeated "Details" rows) are now on screen, so the server won't guess. Call `snapshot` and retry |
195
202
  | `type` fails on non-ASCII | adb text entry supports printable ASCII only |
@@ -79,7 +79,11 @@ Add these after `"android-pilot"` in `args`:
79
79
  | `--device <serial>` | first device in `adb devices` | Choose a device when several are connected: a serial (`13b22d7f`), emulator (`emulator-5554`) or wireless device (`192.168.1.10:5555`, after `adb connect`) |
80
80
  | `--adb-path <path>` | `$ADB_PATH`, then `adb` on `PATH` | Pin the adb binary to use |
81
81
 
82
- The server prints the device and adb binary it chose to stderr.
82
+ The server starts even if adb or the device isn't ready yet, so you can plug
83
+ the phone in after starting your client. Until then, tools return an error
84
+ that says what's missing, and the next call looks again. A wrong `--adb-path`
85
+ (or `ADB_PATH`) stops the server at startup instead. The device and adb binary
86
+ it picks are printed to stderr.
83
87
 
84
88
  ## Tools
85
89
 
@@ -160,11 +164,14 @@ Pass `--adb-path` to pin a binary you trust instead of relying on `PATH`.
160
164
  | Symptom | Fix |
161
165
  |---------|-----|
162
166
  | Client can't start the server | Use the full path to `uvx` (`which uvx`) as `command`; GUI clients often don't share your shell's `PATH` |
163
- | `adb is not installed or not in PATH` | Install [platform-tools](https://developer.android.com/tools/releases/platform-tools), or pass `--adb-path /full/path/to/adb` |
164
- | `No devices connected` | Check the cable, enable USB debugging, run `adb devices` |
165
- | Device shows `unauthorized` | Accept the "Allow USB debugging" prompt; if it doesn't appear, run `adb kill-server` and retry |
166
- | `Device … not found` | `--device` must match the first column of `adb devices` exactly |
167
- | `adb … timed out after 30s` | The device or adb server is stuck: replug, or run `adb kill-server` |
167
+ | `adb is not on PATH` | Install [platform-tools](https://developer.android.com/tools/releases/platform-tools), or pass `--adb-path /full/path/to/adb` |
168
+ | Server exits with `adb not found at …` or `… is not executable` | `--adb-path` / `ADB_PATH` must point to the adb binary itself |
169
+ | `no devices connected` | Check the cable, enable USB debugging, run `adb devices`. No restart needed: the next tool call looks again |
170
+ | `device … is unauthorized` | Unlock the phone and accept the "Allow USB debugging" prompt; if it doesn't appear, run `adb kill-server` and retry |
171
+ | `device … is offline` | Reconnect the device (cable or wireless debugging), or run `adb kill-server` |
172
+ | `adb can't access device … no permissions` | Linux: install udev rules for Android devices (e.g. the `android-udev` package) and replug |
173
+ | `device … not found` | `--device` must match the first column of `adb devices` exactly |
174
+ | `adb … timed out after 15s` | The device or adb server is stuck: replug, or run `adb kill-server` |
168
175
  | `… changed or is gone; call snapshot again` | The screen changed since the snapshot. Call `snapshot` and retry |
169
176
  | `… moved and N elements now match it` | The element moved, and several identical ones (e.g. repeated "Details" rows) are now on screen, so the server won't guess. Call `snapshot` and retry |
170
177
  | `type` fails on non-ASCII | adb text entry supports printable ASCII only |
@@ -0,0 +1,220 @@
1
+ """The phone, driven through the adb binary. The only module that runs anything."""
2
+
3
+ import os
4
+ import shlex
5
+ import shutil
6
+ import stat
7
+ import subprocess
8
+ import sys
9
+ import threading
10
+ import warnings
11
+ from typing import Literal, Protocol, get_args
12
+
13
+ Key = Literal["BACK", "HOME", "ENTER", "ESCAPE", "APP_SWITCH", "TAB", "DEL"]
14
+ _KEYS = frozenset(get_args(Key))
15
+
16
+ # Long enough for a slow uiautomator dump or screencap, short enough that a
17
+ # wedged device or adb server can't hold a tool call open forever.
18
+ ADB_TIMEOUT_SECONDS = 15
19
+
20
+
21
+ class DeviceError(Exception):
22
+ """adb is missing or failed, or no device is ready. The message says how to fix it."""
23
+
24
+
25
+ class Device(Protocol):
26
+ """What the server needs from a phone. AdbDevice is the real one; tests use a fake."""
27
+
28
+ def ui_dump(self) -> str: ...
29
+ def screenshot(self) -> bytes: ...
30
+ def tap(self, x: int, y: int) -> None: ...
31
+ def long_press(self, x: int, y: int, duration_ms: int) -> None: ...
32
+ def swipe(self, x1: int, y1: int, x2: int, y2: int, duration_ms: int) -> None: ...
33
+ def key(self, key: Key) -> None: ...
34
+ def type_text(self, text: str) -> None: ...
35
+ def delete_text(self, count: int) -> None: ...
36
+ def shell(self, command: str) -> str: ...
37
+
38
+
39
+ class AdbDevice:
40
+ """A phone reached through adb, found on first use so the server can start before it's plugged in.
41
+
42
+ adb_path pins the binary; without it, adb is looked up on PATH on first use and
43
+ kept. serial pins the device; without it, the first ready device is used. When
44
+ a command fails because the device went away, the error says so and the next
45
+ command looks again, so a phone that reconnected under a new serial (as
46
+ `adb connect` to a new wireless-debugging port does) is found.
47
+ """
48
+
49
+ def __init__(self, adb_path: str | None = None, serial: str | None = None) -> None:
50
+ self._pinned_adb = adb_path
51
+ self._pinned_serial = serial or None
52
+ self.adb_path: str | None = None
53
+ self.serial: str | None = None
54
+ self._lock = threading.Lock() # tools run on worker threads
55
+
56
+ def connect(self) -> tuple[str, str]:
57
+ """The adb binary and the serial of a ready device, looking them up if needed."""
58
+ with self._lock:
59
+ if self.adb_path is None:
60
+ self.adb_path = _resolve_adb(self._pinned_adb)
61
+ if self.serial is None:
62
+ self.serial = _pick_serial(_device_states(self.adb_path), self._pinned_serial)
63
+ print(f"android-pilot: using device {self.serial} via {self.adb_path}", file=sys.stderr)
64
+ return self.adb_path, self.serial
65
+
66
+ def _adb(self, *args: str) -> bytes:
67
+ adb, serial = self.connect()
68
+ try:
69
+ return _run(adb, "-s", serial, *args)
70
+ except DeviceError as error:
71
+ # Never retry here: an action could land twice. Just find out whether
72
+ # the device went away, to say so plainly and look again next time.
73
+ try:
74
+ states = _device_states(adb)
75
+ except DeviceError:
76
+ states = None # adb itself is in trouble; its first error says more
77
+ if states is not None and states.get(serial) == "device":
78
+ raise # the device is fine; the command itself failed
79
+ with self._lock:
80
+ if self.serial == serial:
81
+ self.serial = None
82
+ if states is None:
83
+ raise
84
+ raise self._gone(serial, states) from error
85
+
86
+ def _gone(self, serial: str, states: dict[str, str]) -> DeviceError:
87
+ """Why serial, which was in use, can't be used now."""
88
+ if serial in states:
89
+ return _not_ready(serial, states[serial])
90
+ try:
91
+ other = _pick_serial(states, self._pinned_serial)
92
+ except DeviceError as e:
93
+ return e
94
+ return DeviceError(f"device {serial} disconnected; the next call will use {other}")
95
+
96
+ def ui_dump(self) -> str:
97
+ return self.shell(
98
+ "uiautomator dump /sdcard/window_dump.xml > /dev/null && "
99
+ "cat /sdcard/window_dump.xml && rm -f /sdcard/window_dump.xml"
100
+ )
101
+
102
+ def screenshot(self) -> bytes:
103
+ """A full-resolution PNG, captured in memory and never written to disk."""
104
+ return self._adb("exec-out", "screencap -p")
105
+
106
+ def tap(self, x: int, y: int) -> None:
107
+ self.shell(f"input tap {x} {y}")
108
+
109
+ def long_press(self, x: int, y: int, duration_ms: int) -> None:
110
+ self.swipe(x, y, x, y, duration_ms)
111
+
112
+ def swipe(self, x1: int, y1: int, x2: int, y2: int, duration_ms: int) -> None:
113
+ self.shell(f"input swipe {x1} {y1} {x2} {y2} {duration_ms}")
114
+
115
+ def key(self, key: Key) -> None:
116
+ if key not in _KEYS: # it is pasted into a shell command
117
+ raise ValueError(f"unsupported key {key!r}; expected one of {', '.join(sorted(_KEYS))}")
118
+ self.shell(f"input keyevent KEYCODE_{key}")
119
+
120
+ def type_text(self, text: str) -> None:
121
+ if any(not 32 <= ord(c) <= 126 for c in text):
122
+ raise ValueError("adb can only type printable ASCII")
123
+ if text:
124
+ self.shell(f"input text {shlex.quote(text.replace(' ', '%s'))}")
125
+
126
+ def delete_text(self, count: int) -> None:
127
+ """Delete count characters from the end of the focused field."""
128
+ if count > 0:
129
+ self.shell("input keyevent KEYCODE_MOVE_END" + " KEYCODE_DEL" * count)
130
+
131
+ def shell(self, command: str) -> str:
132
+ output = self._adb("shell", command).decode(errors="replace")
133
+ return output.replace("\r\n", "\n").rstrip("\n")
134
+
135
+
136
+ # What to do about each state `adb devices` can report other than "device" (ready).
137
+ _NOT_READY_HINTS = {
138
+ "unauthorized": 'unlock the phone and accept the "Allow USB debugging" prompt',
139
+ "authorizing": 'unlock the phone and accept the "Allow USB debugging" prompt',
140
+ "offline": "reconnect it (cable or wireless debugging), or run `adb kill-server`",
141
+ "connecting": "wait a moment and retry",
142
+ }
143
+
144
+
145
+ def _device_states(adb: str) -> dict[str, str]:
146
+ """Each device `adb devices` lists, and its state ("device" when ready)."""
147
+ states: dict[str, str] = {}
148
+ for line in _run(adb, "devices").decode(errors="replace").splitlines()[1:]: # skip "List of devices attached"
149
+ name, sep, state = line.strip().partition("\t")
150
+ if sep:
151
+ states[name] = state.strip()
152
+ return states
153
+
154
+
155
+ def _pick_serial(states: dict[str, str], serial: str | None) -> str:
156
+ """The serial of the device to use: this one if given, else the first ready one."""
157
+ ready = [name for name, state in states.items() if state == "device"]
158
+ if serial:
159
+ if serial in ready:
160
+ return serial
161
+ if serial in states:
162
+ raise _not_ready(serial, states[serial])
163
+ raise DeviceError(f"device {serial} not found; connected: {', '.join(ready) or 'none'}")
164
+ if ready:
165
+ return ready[0]
166
+ if states:
167
+ raise _not_ready(*next(iter(states.items())))
168
+ raise DeviceError("no devices connected; check the cable and that USB debugging is allowed")
169
+
170
+
171
+ def _not_ready(serial: str, state: str) -> DeviceError:
172
+ if state.startswith("no permissions"): # Linux, missing udev rules; adb's message says how to fix it
173
+ return DeviceError(f"adb can't access device {serial}: {state}")
174
+ hint = _NOT_READY_HINTS.get(state, "it isn't ready for commands")
175
+ return DeviceError(f"device {serial} is {state}: {hint}")
176
+
177
+
178
+ def _resolve_adb(explicit: str | None) -> str:
179
+ """Pick the adb binary once, on first use, so a changed PATH can't swap it under a running server.
180
+
181
+ adb can shell into every connected device as this user, so an
182
+ attacker-controlled adb on PATH is code execution; ``explicit`` pins a trusted one.
183
+ The result is absolute: subprocess searches PATH again for a bare name like "adb".
184
+ """
185
+ if explicit:
186
+ if not os.path.isfile(explicit):
187
+ raise DeviceError(f"adb not found at {explicit}")
188
+ return os.path.abspath(explicit)
189
+ found = shutil.which("adb")
190
+ if found is None:
191
+ raise DeviceError("adb is not on PATH; install platform-tools or pass --adb-path")
192
+ found = os.path.abspath(found) # which() returns a bare name for an empty PATH entry
193
+ try:
194
+ mode = os.stat(found).st_mode
195
+ except OSError as exc: # removed between which() and here
196
+ raise DeviceError(f"adb not found at {found}") from exc
197
+ if mode & stat.S_IWOTH:
198
+ warnings.warn(f"{found} is world-writable, so anyone on this machine can replace it", RuntimeWarning, 3)
199
+ return found
200
+
201
+
202
+ def _run(adb: str, *args: str) -> bytes:
203
+ try:
204
+ result = subprocess.run(
205
+ [adb, *args],
206
+ capture_output=True,
207
+ # The server's stdin is the MCP transport, and "adb shell" forwards
208
+ # stdin to the device, where a command like "cat" would eat it.
209
+ stdin=subprocess.DEVNULL,
210
+ timeout=ADB_TIMEOUT_SECONDS,
211
+ )
212
+ except FileNotFoundError as exc:
213
+ raise DeviceError(f"adb not found at {adb}") from exc
214
+ except OSError as exc: # e.g. not executable
215
+ raise DeviceError(f"can't run adb at {adb}: {exc.strerror or exc}") from exc
216
+ except subprocess.TimeoutExpired as exc:
217
+ raise DeviceError(f"adb {' '.join(args)} timed out after {ADB_TIMEOUT_SECONDS}s; is the device stuck?") from exc
218
+ if result.returncode != 0:
219
+ raise DeviceError(result.stderr.decode(errors="replace").strip() or f"adb {' '.join(args)} failed")
220
+ return result.stdout
@@ -14,7 +14,7 @@ from mcp.server.mcpserver.exceptions import ToolError
14
14
  from PIL import Image as PILImage
15
15
 
16
16
  from . import __version__
17
- from .device import Device, DeviceError, Key, connect
17
+ from .device import AdbDevice, Device, DeviceError, Key
18
18
  from .screen import EMPTY, FLAGS, Bounds, Element, Point, RefError, Role, Snapshot
19
19
 
20
20
  P = ParamSpec("P")
@@ -199,10 +199,17 @@ def main() -> None:
199
199
  help="adb binary to use (default: $ADB_PATH, then adb on PATH); set it to pin a trusted binary",
200
200
  )
201
201
  args = parser.parse_args()
202
+ # A wrong value the user configured is fatal. Anything missing from the
203
+ # environment (adb, the phone) is reported by the tools instead, where the
204
+ # agent can see it, and fixing it doesn't need a restart.
205
+ if args.adb_path:
206
+ if not os.path.isfile(args.adb_path):
207
+ parser.error(f"adb not found at {args.adb_path}")
208
+ if not os.access(args.adb_path, os.X_OK):
209
+ parser.error(f"adb at {args.adb_path} is not executable")
210
+ device = AdbDevice(args.adb_path, args.device)
202
211
  try:
203
- device = connect(args.device, args.adb_path)
212
+ device.connect() # only to report the device in the client's log; stdout is the MCP transport
204
213
  except DeviceError as e:
205
- parser.error(str(e))
206
- # stdout is the MCP transport.
207
- print(f"android-pilot: using device {device.serial} via {device.adb_path}", file=sys.stderr)
214
+ print(f"android-pilot: {e}; tools will keep looking when called", file=sys.stderr)
208
215
  create_server(device).run(transport="stdio")
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "android-pilot"
7
- version = "0.2.0a1"
7
+ version = "0.2.0a2"
8
8
  description = "MCP server that lets an AI agent drive an Android device over adb"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "android-pilot"
7
- version = "0.2.0a1"
7
+ version = "0.2.0a2"
8
8
  description = "MCP server that lets an AI agent drive an Android device over adb"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -0,0 +1,370 @@
1
+ """AdbDevice, with subprocess and the PATH lookup patched."""
2
+
3
+ import subprocess
4
+ from contextlib import contextmanager
5
+ from unittest.mock import patch
6
+
7
+ import pytest
8
+
9
+ from android_pilot.device import ADB_TIMEOUT_SECONDS, AdbDevice, DeviceError
10
+
11
+ ADB = "/usr/bin/adb"
12
+ TWO_DEVICES = "List of devices attached\ndevice123\tdevice\ndevice456\tdevice\n"
13
+ NO_DEVICES = "List of devices attached\n\n"
14
+
15
+
16
+ def result(stdout: str | bytes = "", stderr: str = "", returncode=0):
17
+ out = stdout.encode() if isinstance(stdout, str) else stdout
18
+ return subprocess.CompletedProcess([ADB], returncode, out, stderr.encode())
19
+
20
+
21
+ def listing(*lines: str) -> subprocess.CompletedProcess:
22
+ return result("List of devices attached\n" + "".join(f"{line}\n" for line in lines))
23
+
24
+
25
+ @contextmanager
26
+ def adb(*results, which: str | None = ADB):
27
+ """Yields the subprocess.run mock, which returns one of results per call, then empty successes."""
28
+ queue = list(results)
29
+ with (
30
+ patch("android_pilot.device.shutil.which", return_value=which),
31
+ patch("android_pilot.device.os.stat") as fake_stat,
32
+ patch(
33
+ "android_pilot.device.subprocess.run", side_effect=lambda *a, **k: queue.pop(0) if queue else result()
34
+ ) as run,
35
+ ):
36
+ fake_stat.return_value.st_mode = 0o755
37
+ yield run
38
+
39
+
40
+ def connected(serial: str | None = None) -> AdbDevice:
41
+ """A device that has already found device123 (or serial)."""
42
+ device = AdbDevice(serial=serial)
43
+ with adb(result(TWO_DEVICES)):
44
+ device.connect()
45
+ return device
46
+
47
+
48
+ def commands(run) -> list[str]:
49
+ return [call.args[0][-1] for call in run.call_args_list]
50
+
51
+
52
+ def executable(tmp_path, mode=0o755) -> str:
53
+ binary = tmp_path / "adb"
54
+ binary.write_text("#!/bin/sh\n")
55
+ binary.chmod(mode)
56
+ return str(binary)
57
+
58
+
59
+ class TestFindingTheDevice:
60
+ @pytest.mark.parametrize("serial", [None, ""])
61
+ def test_defaults_to_the_first_device(self, serial):
62
+ with adb(result(TWO_DEVICES)):
63
+ assert AdbDevice(serial=serial).connect() == (ADB, "device123")
64
+
65
+ def test_specific_device(self):
66
+ with adb(result(TWO_DEVICES)):
67
+ assert AdbDevice(serial="device456").connect() == (ADB, "device456")
68
+
69
+ def test_only_ready_devices_count(self):
70
+ devices = listing("device456\toffline", "device787\tunauthorized", "device123\tdevice", "")
71
+ with adb(devices):
72
+ assert AdbDevice().connect()[1] == "device123"
73
+
74
+ def test_no_devices(self):
75
+ with adb(result(NO_DEVICES)), pytest.raises(DeviceError, match="no devices connected"):
76
+ AdbDevice().connect()
77
+
78
+ def test_specific_device_missing_lists_the_ready_ones(self):
79
+ with (
80
+ adb(listing("device123\tdevice", "device787\tunauthorized")),
81
+ pytest.raises(DeviceError, match="device456 not found; connected: device123$"),
82
+ ):
83
+ AdbDevice(serial="device456").connect()
84
+
85
+ @pytest.mark.parametrize(
86
+ ("state", "message"),
87
+ [
88
+ (
89
+ "unauthorized",
90
+ 'device device123 is unauthorized: unlock the phone and accept the "Allow USB debugging" prompt',
91
+ ),
92
+ (
93
+ "offline",
94
+ "device device123 is offline: reconnect it (cable or wireless debugging), or run `adb kill-server`",
95
+ ),
96
+ ("recovery", "device device123 is recovery: it isn't ready for commands"),
97
+ (
98
+ "no permissions (missing udev rules? user is in the plugdev group); see [http://developer.android.com/tools/device.html]",
99
+ "adb can't access device device123: no permissions (missing udev rules?",
100
+ ),
101
+ ],
102
+ )
103
+ @pytest.mark.parametrize("serial", [None, "device123"])
104
+ def test_a_device_that_isnt_ready_says_how_to_fix_it(self, state, message, serial):
105
+ with adb(listing(f"device123\t{state}")), pytest.raises(DeviceError) as error:
106
+ AdbDevice(serial=serial).connect()
107
+ assert str(error.value).startswith(message)
108
+
109
+ def test_tolerates_daemon_startup_lines_crlf_and_spaces_in_states(self):
110
+ output = (
111
+ "* daemon not running; starting now at tcp:5037\r\n"
112
+ "* daemon started successfully\r\n"
113
+ "List of devices attached\r\n"
114
+ "device456\tno permissions (missing udev rules?); see [http://developer.android.com/tools/device.html]\r\n"
115
+ "device123\tdevice \r\n"
116
+ "\r\n"
117
+ )
118
+ with adb(result(output)):
119
+ assert AdbDevice().connect()[1] == "device123"
120
+ with adb(result(output)), pytest.raises(DeviceError, match="adb can't access device device456: no permissions"):
121
+ AdbDevice(serial="device456").connect()
122
+
123
+ def test_announces_the_device_on_stderr(self, capsys):
124
+ connected()
125
+ assert capsys.readouterr().err == f"android-pilot: using device device123 via {ADB}\n"
126
+
127
+
128
+ class TestFindingAdb:
129
+ def test_uses_the_adb_found_on_path(self):
130
+ with adb(result(TWO_DEVICES)) as run:
131
+ AdbDevice().connect()
132
+ assert run.call_args.args[0] == [ADB, "devices"]
133
+
134
+ def test_no_adb_on_path_fails_before_running_anything(self):
135
+ with adb(which=None) as run, pytest.raises(DeviceError, match="not on PATH"):
136
+ AdbDevice().shell("ls")
137
+ run.assert_not_called()
138
+
139
+ def test_adb_installed_later_is_found_without_a_restart(self):
140
+ device = AdbDevice()
141
+ with adb(which=None), pytest.raises(DeviceError, match="not on PATH"):
142
+ device.shell("ls")
143
+ with adb(result(TWO_DEVICES), result("ok")):
144
+ assert device.shell("ls") == "ok"
145
+
146
+ def test_adb_is_looked_up_once(self):
147
+ device = connected()
148
+ with adb(which="/somewhere/else/adb") as run:
149
+ device.shell("ls")
150
+ assert run.call_args.args[0][0] == ADB
151
+
152
+ def test_explicit_adb_is_used_without_searching_path(self, tmp_path):
153
+ binary = executable(tmp_path)
154
+ with (
155
+ patch("android_pilot.device.shutil.which", side_effect=AssertionError("must not search PATH")),
156
+ patch("android_pilot.device.subprocess.run", return_value=result(TWO_DEVICES)) as run,
157
+ ):
158
+ assert AdbDevice(binary).connect() == (binary, "device123")
159
+ assert run.call_args.args[0] == [binary, "devices"]
160
+
161
+ def test_a_relative_explicit_adb_is_pinned_as_an_absolute_path(self, tmp_path, monkeypatch):
162
+ """subprocess searches PATH for a bare "adb", which would let PATH swap the binary."""
163
+ monkeypatch.chdir(tmp_path)
164
+ executable(tmp_path)
165
+ with patch("android_pilot.device.subprocess.run", return_value=result(TWO_DEVICES)) as run:
166
+ assert AdbDevice("adb").connect()[0] == str(tmp_path / "adb")
167
+ assert run.call_args.args[0][0] == str(tmp_path / "adb")
168
+
169
+ def test_a_bare_name_from_path_is_pinned_as_an_absolute_path(self, tmp_path, monkeypatch):
170
+ monkeypatch.chdir(tmp_path) # which() returns "adb" when PATH has an empty entry
171
+ with adb(result(TWO_DEVICES), which="adb"):
172
+ assert AdbDevice().connect()[0] == str(tmp_path / "adb")
173
+
174
+ def test_adb_that_disappears_while_being_checked(self):
175
+ with (
176
+ patch("android_pilot.device.shutil.which", return_value=ADB),
177
+ patch("android_pilot.device.os.stat", side_effect=FileNotFoundError),
178
+ pytest.raises(DeviceError, match=f"adb not found at {ADB}"),
179
+ ):
180
+ AdbDevice().connect()
181
+
182
+ def test_explicit_adb_must_exist(self, tmp_path):
183
+ with pytest.raises(DeviceError, match="adb not found at"):
184
+ AdbDevice(str(tmp_path / "missing")).connect()
185
+
186
+ def test_explicit_adb_that_cannot_run(self, tmp_path):
187
+ with pytest.raises(DeviceError, match="can't run adb at .*: Permission denied"):
188
+ AdbDevice(executable(tmp_path, 0o644)).connect()
189
+
190
+ def test_warns_when_the_adb_on_path_is_world_writable(self, tmp_path):
191
+ with (
192
+ patch("android_pilot.device.shutil.which", return_value=executable(tmp_path, 0o777)),
193
+ patch("android_pilot.device.subprocess.run", return_value=result(TWO_DEVICES)),
194
+ pytest.warns(RuntimeWarning, match="world-writable"),
195
+ ):
196
+ AdbDevice().connect()
197
+
198
+
199
+ class TestConnectingLazily:
200
+ def test_nothing_runs_until_the_device_is_used(self):
201
+ with adb() as run:
202
+ AdbDevice()
203
+ run.assert_not_called()
204
+
205
+ def test_first_command_finds_the_device_then_runs(self):
206
+ with adb(result(TWO_DEVICES), result("ok")) as run:
207
+ assert AdbDevice().shell("ls") == "ok"
208
+ assert [call.args[0] for call in run.call_args_list] == [
209
+ [ADB, "devices"],
210
+ [ADB, "-s", "device123", "shell", "ls"],
211
+ ]
212
+
213
+ def test_fails_until_a_device_appears(self):
214
+ device = AdbDevice()
215
+ with adb(result(NO_DEVICES)), pytest.raises(DeviceError, match="no devices connected"):
216
+ device.shell("ls")
217
+ with adb(result(TWO_DEVICES), result("ok")):
218
+ assert device.shell("ls") == "ok"
219
+
220
+ def test_looks_for_the_device_only_once_while_it_works(self):
221
+ device = connected()
222
+ with adb() as run:
223
+ device.shell("ls")
224
+ device.tap(1, 2)
225
+ assert commands(run) == ["ls", "input tap 1 2"]
226
+
227
+ def test_a_command_that_fails_on_a_working_device_keeps_the_device(self):
228
+ device = connected()
229
+ with adb(result(stderr="boom", returncode=1), result(TWO_DEVICES), result("ok")) as run:
230
+ with pytest.raises(DeviceError, match="^boom$"):
231
+ device.shell("false")
232
+ assert device.shell("ls") == "ok"
233
+ assert [call.args[0][1] for call in run.call_args_list] == ["-s", "devices", "-s"] # no second lookup
234
+
235
+ def test_a_failed_command_is_not_retried(self):
236
+ device = connected()
237
+ with adb(result(stderr="boom", returncode=1), result(TWO_DEVICES)) as run, pytest.raises(DeviceError):
238
+ device.tap(1, 2)
239
+ assert commands(run) == ["input tap 1 2", "devices"]
240
+
241
+ def test_a_device_that_went_away_is_reported_plainly(self):
242
+ device = connected()
243
+ with (
244
+ adb(result(stderr="adb: device 'device123' not found", returncode=1), result(NO_DEVICES)),
245
+ pytest.raises(DeviceError, match="^no devices connected") as error,
246
+ ):
247
+ device.shell("ls")
248
+ assert "not found" in str(error.value.__cause__)
249
+
250
+ def test_a_device_that_went_offline_says_how_to_fix_it(self):
251
+ device = connected()
252
+ with (
253
+ adb(result(stderr="error: device offline", returncode=1), listing("device123\toffline")),
254
+ pytest.raises(DeviceError, match="^device device123 is offline: reconnect it"),
255
+ ):
256
+ device.shell("ls")
257
+
258
+ def test_after_the_device_went_away_the_next_command_looks_again(self):
259
+ device = connected()
260
+ rejoined = listing("192.168.1.10:38817\tdevice")
261
+ with adb(result(stderr="not found", returncode=1), rejoined, rejoined, result("ok")) as run:
262
+ with pytest.raises(DeviceError, match="device device123 disconnected; the next call will use 192"):
263
+ device.shell("ls")
264
+ assert device.shell("ls") == "ok"
265
+ assert run.call_args.args[0] == [ADB, "-s", "192.168.1.10:38817", "shell", "ls"]
266
+
267
+ def test_a_pinned_device_is_never_swapped(self):
268
+ device = connected("device456")
269
+ others = listing("device123\tdevice")
270
+ with adb(result(stderr="not found", returncode=1), others, others) as run:
271
+ with pytest.raises(DeviceError, match="device456 not found; connected: device123"):
272
+ device.shell("ls")
273
+ with pytest.raises(DeviceError, match="device456 not found; connected: device123"):
274
+ device.shell("ls")
275
+ assert len(run.call_args_list) == 3 # the second call stopped at `adb devices`
276
+
277
+ def test_when_adb_itself_fails_too_its_first_error_is_kept(self):
278
+ device = connected()
279
+ with (
280
+ adb(result(stderr="daemon died", returncode=1), result(stderr="cannot connect", returncode=1)),
281
+ pytest.raises(DeviceError, match="^daemon died$"),
282
+ ):
283
+ device.shell("ls")
284
+ assert device.serial is None # looked up again next time
285
+
286
+
287
+ class TestRunningAdb:
288
+ def test_shell_runs_on_the_device_and_normalises_output(self):
289
+ device = connected()
290
+ with adb(result("one\r\ntwo\r\n")) as run:
291
+ assert device.shell("ls") == "one\ntwo"
292
+ assert run.call_args.args[0] == [ADB, "-s", "device123", "shell", "ls"]
293
+
294
+ def test_commands_get_no_stdin(self):
295
+ """The server's stdin is the MCP pipe; device commands must not read it."""
296
+ device = connected()
297
+ with adb() as run:
298
+ device.shell("cat")
299
+ assert run.call_args.kwargs["stdin"] == subprocess.DEVNULL
300
+
301
+ def test_failure_reports_stderr(self):
302
+ device = connected()
303
+ with adb(result(stderr="boom", returncode=1), result(TWO_DEVICES)), pytest.raises(DeviceError, match="^boom$"):
304
+ device.shell("ls")
305
+
306
+ def test_hanging_command_times_out(self):
307
+ device = connected()
308
+ with (
309
+ patch(
310
+ "android_pilot.device.subprocess.run",
311
+ side_effect=subprocess.TimeoutExpired(ADB, ADB_TIMEOUT_SECONDS),
312
+ ),
313
+ pytest.raises(DeviceError, match="timed out"),
314
+ ):
315
+ device.shell("sleep 999")
316
+
317
+ def test_adb_that_vanished_after_it_was_found(self):
318
+ device = connected()
319
+ with (
320
+ patch("android_pilot.device.subprocess.run", side_effect=FileNotFoundError),
321
+ pytest.raises(DeviceError, match=f"adb not found at {ADB}"),
322
+ ):
323
+ device.shell("ls")
324
+
325
+
326
+ class TestDeviceCommands:
327
+ def test_ui_dump_dumps_reads_and_cleans_up_in_one_call(self):
328
+ device = connected()
329
+ with adb(result("<xml/>")) as run:
330
+ assert device.ui_dump() == "<xml/>"
331
+ assert commands(run) == [
332
+ "uiautomator dump /sdcard/window_dump.xml > /dev/null && "
333
+ "cat /sdcard/window_dump.xml && rm -f /sdcard/window_dump.xml"
334
+ ]
335
+
336
+ def test_screenshot_comes_through_exec_out_unaltered(self):
337
+ device = connected()
338
+ with adb(result(b"\x89PNG\r\n")) as run:
339
+ assert device.screenshot() == b"\x89PNG\r\n"
340
+ assert run.call_args.args[0] == [ADB, "-s", "device123", "exec-out", "screencap -p"]
341
+
342
+ def test_input_commands(self):
343
+ device = connected()
344
+ with adb() as run:
345
+ device.tap(10, 20)
346
+ device.long_press(30, 40, 700)
347
+ device.swipe(10, 100, 10, 20, 300)
348
+ device.key("BACK")
349
+ device.type_text("hi there; rm")
350
+ device.delete_text(2)
351
+ device.type_text("")
352
+ device.delete_text(0)
353
+ assert commands(run) == [
354
+ "input tap 10 20",
355
+ "input swipe 30 40 30 40 700",
356
+ "input swipe 10 100 10 20 300",
357
+ "input keyevent KEYCODE_BACK",
358
+ "input text 'hi%sthere;%srm'",
359
+ "input keyevent KEYCODE_MOVE_END KEYCODE_DEL KEYCODE_DEL",
360
+ ]
361
+
362
+ def test_type_text_rejects_non_ascii(self):
363
+ with adb() as run, pytest.raises(ValueError, match="printable ASCII"):
364
+ AdbDevice().type_text("café")
365
+ run.assert_not_called()
366
+
367
+ def test_key_rejects_anything_outside_the_list(self):
368
+ with adb() as run, pytest.raises(ValueError, match="unsupported key"):
369
+ AdbDevice().key("POWER; reboot") # ty: ignore[invalid-argument-type]
370
+ run.assert_not_called()
@@ -3,13 +3,15 @@
3
3
  import asyncio
4
4
  import base64
5
5
  import io
6
+ from unittest.mock import patch
6
7
 
7
8
  import pytest
8
9
  from mcp import Client
9
10
  from mcp.types import ImageContent
10
11
  from PIL import Image as PILImage
11
12
 
12
- from android_pilot.server import create_server
13
+ from android_pilot.device import AdbDevice, DeviceError
14
+ from android_pilot.server import create_server, main
13
15
 
14
16
  from .fakes import EMPTY_SCREEN, FakeDevice
15
17
 
@@ -200,6 +202,70 @@ class TestKeyAndShell:
200
202
  assert device.actions == [("shell", "ls")]
201
203
 
202
204
 
205
+ def test_device_errors_reach_the_agent():
206
+ class Unplugged(FakeDevice):
207
+ def ui_dump(self) -> str:
208
+ raise DeviceError("no devices connected; check the cable and that USB debugging is allowed")
209
+
210
+ result = call(Unplugged(), ("snapshot", {}))
211
+ assert result.is_error is True
212
+ assert text(result).endswith(": no devices connected; check the cable and that USB debugging is allowed")
213
+
214
+
215
+ class TestMain:
216
+ def run_main(self, *argv: str):
217
+ with (
218
+ patch("sys.argv", ["android-pilot", *argv]),
219
+ patch("android_pilot.server.create_server") as create,
220
+ ):
221
+ main()
222
+ return create
223
+
224
+ def test_starts_without_a_device(self, capsys):
225
+ with patch.object(AdbDevice, "connect", side_effect=DeviceError("no devices connected")):
226
+ create = self.run_main()
227
+ create.return_value.run.assert_called_once_with(transport="stdio")
228
+ assert "no devices connected; tools will keep looking when called" in capsys.readouterr().err
229
+
230
+ def test_starts_without_adb(self):
231
+ with patch.object(AdbDevice, "connect", side_effect=DeviceError("adb is not on PATH")):
232
+ self.run_main().return_value.run.assert_called_once()
233
+
234
+ def test_passes_the_options_to_the_device(self, tmp_path):
235
+ binary = tmp_path / "adb"
236
+ binary.touch(0o755)
237
+ with patch.object(AdbDevice, "connect") as connect:
238
+ create = self.run_main("--device", "emulator-5554", "--adb-path", str(binary))
239
+ [device] = create.call_args.args
240
+ connect.assert_called_once()
241
+ assert (device._pinned_adb, device._pinned_serial) == (str(binary), "emulator-5554")
242
+
243
+ @pytest.mark.parametrize(
244
+ ("name", "mode", "message"),
245
+ [
246
+ ("missing", None, "adb not found at"),
247
+ ("adb", 0o644, "is not executable"),
248
+ ("dir", "dir", "adb not found at"),
249
+ ],
250
+ )
251
+ def test_a_wrong_adb_path_is_fatal(self, tmp_path, capsys, name, mode, message):
252
+ path = tmp_path / name
253
+ if mode == "dir":
254
+ path.mkdir()
255
+ elif mode is not None:
256
+ path.touch(mode)
257
+ with patch.object(AdbDevice, "connect") as connect, pytest.raises(SystemExit) as exit:
258
+ self.run_main("--adb-path", str(path))
259
+ assert exit.value.code == 2
260
+ assert message in capsys.readouterr().err
261
+ connect.assert_not_called()
262
+
263
+ def test_a_wrong_adb_path_env_var_is_fatal_too(self, tmp_path, capsys):
264
+ with patch.dict("os.environ", {"ADB_PATH": str(tmp_path / "missing")}), pytest.raises(SystemExit):
265
+ self.run_main()
266
+ assert "adb not found at" in capsys.readouterr().err
267
+
268
+
203
269
  def test_screenshot_is_downscaled():
204
270
  source = io.BytesIO()
205
271
  PILImage.new("RGB", (1000, 2000), "red").save(source, "PNG")
@@ -1,130 +0,0 @@
1
- """The phone, driven through the adb binary. The only module that runs anything."""
2
-
3
- import os
4
- import shlex
5
- import shutil
6
- import stat
7
- import subprocess
8
- import warnings
9
- from typing import Literal, Protocol, get_args
10
-
11
- Key = Literal["BACK", "HOME", "ENTER", "ESCAPE", "APP_SWITCH", "TAB", "DEL"]
12
- _KEYS = frozenset(get_args(Key))
13
-
14
- # Long enough for a slow uiautomator dump or screencap, short enough that a
15
- # wedged device or adb server can't hold a tool call open forever.
16
- ADB_TIMEOUT_SECONDS = 15
17
-
18
-
19
- class DeviceError(Exception):
20
- """adb is missing or failed, or the requested device isn't connected."""
21
-
22
-
23
- class Device(Protocol):
24
- """What the server needs from a phone. AdbDevice is the real one; tests use a fake."""
25
-
26
- def ui_dump(self) -> str: ...
27
- def screenshot(self) -> bytes: ...
28
- def tap(self, x: int, y: int) -> None: ...
29
- def long_press(self, x: int, y: int, duration_ms: int) -> None: ...
30
- def swipe(self, x1: int, y1: int, x2: int, y2: int, duration_ms: int) -> None: ...
31
- def key(self, key: Key) -> None: ...
32
- def type_text(self, text: str) -> None: ...
33
- def delete_text(self, count: int) -> None: ...
34
- def shell(self, command: str) -> str: ...
35
-
36
-
37
- def connect(serial: str | None = None, adb_path: str | None = None) -> "AdbDevice":
38
- """The device with this serial, or the first connected one."""
39
- adb = _resolve_adb(adb_path)
40
- lines = _run(adb, "devices").decode(errors="replace").splitlines()[1:] # skip "List of devices attached"
41
- ready = [line.split("\t")[0] for line in lines if line.endswith("\tdevice")]
42
- if serial:
43
- if serial not in ready:
44
- raise DeviceError(f"device {serial} not found; connected: {', '.join(ready) or 'none'}")
45
- return AdbDevice(serial, adb)
46
- if not ready:
47
- raise DeviceError("no devices connected; check the cable and that USB debugging is allowed")
48
- return AdbDevice(ready[0], adb)
49
-
50
-
51
- class AdbDevice:
52
- def __init__(self, serial: str, adb_path: str) -> None:
53
- self.serial = serial
54
- self.adb_path = adb_path
55
-
56
- def ui_dump(self) -> str:
57
- return self.shell(
58
- "uiautomator dump /sdcard/window_dump.xml > /dev/null && "
59
- "cat /sdcard/window_dump.xml && rm -f /sdcard/window_dump.xml"
60
- )
61
-
62
- def screenshot(self) -> bytes:
63
- """A full-resolution PNG, captured in memory and never written to disk."""
64
- return _run(self.adb_path, "-s", self.serial, "exec-out", "screencap -p")
65
-
66
- def tap(self, x: int, y: int) -> None:
67
- self.shell(f"input tap {x} {y}")
68
-
69
- def long_press(self, x: int, y: int, duration_ms: int) -> None:
70
- self.swipe(x, y, x, y, duration_ms)
71
-
72
- def swipe(self, x1: int, y1: int, x2: int, y2: int, duration_ms: int) -> None:
73
- self.shell(f"input swipe {x1} {y1} {x2} {y2} {duration_ms}")
74
-
75
- def key(self, key: Key) -> None:
76
- if key not in _KEYS: # it is pasted into a shell command
77
- raise ValueError(f"unsupported key {key!r}; expected one of {', '.join(sorted(_KEYS))}")
78
- self.shell(f"input keyevent KEYCODE_{key}")
79
-
80
- def type_text(self, text: str) -> None:
81
- if any(not 32 <= ord(c) <= 126 for c in text):
82
- raise ValueError("adb can only type printable ASCII")
83
- if text:
84
- self.shell(f"input text {shlex.quote(text.replace(' ', '%s'))}")
85
-
86
- def delete_text(self, count: int) -> None:
87
- """Delete count characters from the end of the focused field."""
88
- if count > 0:
89
- self.shell("input keyevent KEYCODE_MOVE_END" + " KEYCODE_DEL" * count)
90
-
91
- def shell(self, command: str) -> str:
92
- output = _run(self.adb_path, "-s", self.serial, "shell", command).decode(errors="replace")
93
- return output.replace("\r\n", "\n").rstrip("\n")
94
-
95
-
96
- def _resolve_adb(explicit: str | None) -> str:
97
- """Pick the adb binary once, at startup, so a changed PATH can't swap it under a running server.
98
-
99
- adb can shell into every connected device as this user, so an
100
- attacker-controlled adb on PATH is code execution; ``explicit`` pins a trusted one.
101
- """
102
- if explicit:
103
- if not os.path.isfile(explicit):
104
- raise DeviceError(f"adb not found at {explicit}")
105
- return explicit
106
- found = shutil.which("adb")
107
- if found is None:
108
- raise DeviceError("adb is not on PATH; install platform-tools or pass --adb-path")
109
- if os.stat(found).st_mode & stat.S_IWOTH:
110
- warnings.warn(f"{found} is world-writable, so anyone on this machine can replace it", RuntimeWarning, 3)
111
- return found
112
-
113
-
114
- def _run(adb: str, *args: str) -> bytes:
115
- try:
116
- result = subprocess.run(
117
- [adb, *args],
118
- capture_output=True,
119
- # The server's stdin is the MCP transport, and "adb shell" forwards
120
- # stdin to the device, where a command like "cat" would eat it.
121
- stdin=subprocess.DEVNULL,
122
- timeout=ADB_TIMEOUT_SECONDS,
123
- )
124
- except FileNotFoundError as exc:
125
- raise DeviceError(f"adb not found at {adb}") from exc
126
- except subprocess.TimeoutExpired as exc:
127
- raise DeviceError(f"adb {' '.join(args)} timed out after {ADB_TIMEOUT_SECONDS}s; is the device stuck?") from exc
128
- if result.returncode != 0:
129
- raise DeviceError(result.stderr.decode(errors="replace").strip() or f"adb {' '.join(args)} failed")
130
- return result.stdout
@@ -1,173 +0,0 @@
1
- """AdbDevice and connect(), with subprocess and the PATH lookup patched."""
2
-
3
- import subprocess
4
- from contextlib import contextmanager
5
- from unittest.mock import patch
6
-
7
- import pytest
8
-
9
- from android_pilot.device import ADB_TIMEOUT_SECONDS, AdbDevice, DeviceError, connect
10
-
11
- ADB = "/usr/bin/adb"
12
- TWO_DEVICES = "List of devices attached\ndevice123\tdevice\ndevice456\tdevice\n"
13
-
14
-
15
- def result(stdout: str | bytes = "", stderr: str = "", returncode=0):
16
- out = stdout.encode() if isinstance(stdout, str) else stdout
17
- return subprocess.CompletedProcess([ADB], returncode, out, stderr.encode())
18
-
19
-
20
- @contextmanager
21
- def adb(*results, which: str | None = ADB):
22
- """Yields the subprocess.run mock, which returns one of results per call, then empty successes."""
23
- queue = list(results)
24
- with (
25
- patch("android_pilot.device.shutil.which", return_value=which),
26
- patch("android_pilot.device.os.stat") as fake_stat,
27
- patch(
28
- "android_pilot.device.subprocess.run", side_effect=lambda *a, **k: queue.pop(0) if queue else result()
29
- ) as run,
30
- ):
31
- fake_stat.return_value.st_mode = 0o755
32
- yield run
33
-
34
-
35
- def commands(run) -> list[str]:
36
- return [call.args[0][-1] for call in run.call_args_list]
37
-
38
-
39
- def executable(tmp_path, mode=0o755) -> str:
40
- binary = tmp_path / "adb"
41
- binary.write_text("#!/bin/sh\n")
42
- binary.chmod(mode)
43
- return str(binary)
44
-
45
-
46
- class TestConnect:
47
- @pytest.mark.parametrize("serial", [None, ""])
48
- def test_defaults_to_the_first_device(self, serial):
49
- with adb(result(TWO_DEVICES)):
50
- assert connect(serial).serial == "device123"
51
-
52
- def test_specific_device(self):
53
- with adb(result(TWO_DEVICES)):
54
- assert connect("device456").serial == "device456"
55
-
56
- def test_only_ready_devices_count(self):
57
- listing = "List of devices attached\ndevice456\toffline\ndevice787\tunauthorized\ndevice123\tdevice\n\n"
58
- with adb(result(listing)):
59
- assert connect(None).serial == "device123"
60
- with adb(result(listing)), pytest.raises(DeviceError, match="device456 not found; connected: device123"):
61
- connect("device456")
62
-
63
- def test_no_devices(self):
64
- with adb(result("List of devices attached\n\n")), pytest.raises(DeviceError, match="no devices connected"):
65
- connect(None)
66
-
67
- def test_uses_the_adb_found_on_path(self):
68
- with adb(result(TWO_DEVICES)) as run:
69
- assert connect(None).adb_path == ADB
70
- assert run.call_args.args[0] == [ADB, "devices"]
71
-
72
- def test_no_adb_on_path_fails_before_running_anything(self):
73
- with adb(which=None) as run, pytest.raises(DeviceError, match="not on PATH"):
74
- connect(None)
75
- run.assert_not_called()
76
-
77
- def test_explicit_adb_is_used_without_searching_path(self, tmp_path):
78
- binary = executable(tmp_path)
79
- with (
80
- patch("android_pilot.device.shutil.which", side_effect=AssertionError("must not search PATH")),
81
- patch("android_pilot.device.subprocess.run", return_value=result(TWO_DEVICES)) as run,
82
- ):
83
- assert connect(None, binary).adb_path == binary
84
- assert run.call_args.args[0] == [binary, "devices"]
85
-
86
- def test_explicit_adb_must_exist(self, tmp_path):
87
- with pytest.raises(DeviceError, match="adb not found at"):
88
- connect(None, str(tmp_path / "missing"))
89
-
90
- def test_warns_when_the_adb_on_path_is_world_writable(self, tmp_path):
91
- with (
92
- patch("android_pilot.device.shutil.which", return_value=executable(tmp_path, 0o777)),
93
- patch("android_pilot.device.subprocess.run", return_value=result(TWO_DEVICES)),
94
- pytest.warns(RuntimeWarning, match="world-writable"),
95
- ):
96
- connect(None)
97
-
98
-
99
- class TestRunningAdb:
100
- def test_shell_runs_on_the_device_and_normalises_output(self):
101
- with adb(result("one\r\ntwo\r\n")) as run:
102
- assert AdbDevice("device123", ADB).shell("ls") == "one\ntwo"
103
- assert run.call_args.args[0] == [ADB, "-s", "device123", "shell", "ls"]
104
-
105
- def test_commands_get_no_stdin(self):
106
- """The server's stdin is the MCP pipe; device commands must not read it."""
107
- with adb() as run:
108
- AdbDevice("device123", ADB).shell("cat")
109
- assert run.call_args.kwargs["stdin"] == subprocess.DEVNULL
110
-
111
- def test_failure_reports_stderr(self):
112
- with adb(result(stderr="boom", returncode=1)), pytest.raises(DeviceError, match="boom"):
113
- AdbDevice("device123", ADB).shell("ls")
114
-
115
- def test_hanging_command_times_out(self):
116
- with (
117
- patch(
118
- "android_pilot.device.subprocess.run",
119
- side_effect=subprocess.TimeoutExpired(ADB, ADB_TIMEOUT_SECONDS),
120
- ),
121
- pytest.raises(DeviceError, match="timed out"),
122
- ):
123
- AdbDevice("device123", ADB).shell("sleep 999")
124
-
125
- def test_adb_that_vanished_after_startup(self):
126
- with (
127
- patch("android_pilot.device.subprocess.run", side_effect=FileNotFoundError),
128
- pytest.raises(DeviceError, match=f"adb not found at {ADB}"),
129
- ):
130
- AdbDevice("device123", ADB).shell("ls")
131
-
132
-
133
- class TestDeviceCommands:
134
- def test_ui_dump_dumps_reads_and_cleans_up_in_one_call(self):
135
- with adb(result("<xml/>")) as run:
136
- assert AdbDevice("device123", ADB).ui_dump() == "<xml/>"
137
- assert commands(run) == [
138
- "uiautomator dump /sdcard/window_dump.xml > /dev/null && "
139
- "cat /sdcard/window_dump.xml && rm -f /sdcard/window_dump.xml"
140
- ]
141
-
142
- def test_screenshot_comes_through_exec_out_unaltered(self):
143
- with adb(result(b"\x89PNG\r\n")) as run:
144
- assert AdbDevice("device123", ADB).screenshot() == b"\x89PNG\r\n"
145
- assert run.call_args.args[0] == [ADB, "-s", "device123", "exec-out", "screencap -p"]
146
-
147
- def test_input_commands(self):
148
- device = AdbDevice("device123", ADB)
149
- with adb() as run:
150
- device.tap(10, 20)
151
- device.long_press(30, 40, 700)
152
- device.swipe(10, 100, 10, 20, 300)
153
- device.key("BACK")
154
- device.type_text("hi there; rm")
155
- device.delete_text(2)
156
- device.type_text("")
157
- device.delete_text(0)
158
- assert commands(run) == [
159
- "input tap 10 20",
160
- "input swipe 30 40 30 40 700",
161
- "input swipe 10 100 10 20 300",
162
- "input keyevent KEYCODE_BACK",
163
- "input text 'hi%sthere;%srm'",
164
- "input keyevent KEYCODE_MOVE_END KEYCODE_DEL KEYCODE_DEL",
165
- ]
166
-
167
- def test_type_text_rejects_non_ascii(self):
168
- with pytest.raises(ValueError, match="printable ASCII"):
169
- AdbDevice("device123", ADB).type_text("café")
170
-
171
- def test_key_rejects_anything_outside_the_list(self):
172
- with pytest.raises(ValueError, match="unsupported key"):
173
- AdbDevice("device123", ADB).key("POWER; reboot") # ty: ignore[invalid-argument-type]
File without changes