headroid 0.1.0a1__py3-none-any.whl

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.
headroid/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ # Copyright 2026 Anand S Kale and the headroid contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """headroid: host-side SDK for the headroid device server."""
4
+
5
+ from .adb import Adb, AdbError
6
+ from .device import Device, Display
7
+ from .rpc import RpcClient, RpcError
8
+ from .server import ServerProcess
9
+
10
+ __version__ = "0.1.0a1"
11
+ __all__ = [
12
+ "Adb",
13
+ "AdbError",
14
+ "Device",
15
+ "Display",
16
+ "RpcClient",
17
+ "RpcError",
18
+ "ServerProcess",
19
+ "__version__",
20
+ ]
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,35 @@
1
+ headroid
2
+ Copyright 2026 Anand S Kale and the headroid contributors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ Third-party components
7
+ ----------------------
8
+
9
+ headroid combines several open-source projects (see docs/adr/0003-compose-open-source-stack.md).
10
+ Files derived from them keep their original copyright headers and state the
11
+ modifications made, as required by section 4 of the Apache License 2.0.
12
+
13
+ scrcpy (device-server/ is a fork of scrcpy-server v4.1)
14
+ Copyright (C) 2018 Genymobile
15
+ Copyright (C) 2018-2026 Romain Vimont
16
+ Apache License, Version 2.0 - https://github.com/Genymobile/scrcpy
17
+ Upstream files live under device-server/server/src/main/java/com/genymobile/scrcpy/
18
+ and the Gradle files in device-server/. Modified lines are marked "headroid:";
19
+ see device-server/README.md for the list of changes. Upstream licence text:
20
+ device-server/LICENSE-scrcpy.
21
+
22
+ ARTEMIS (selected host modules and integrations/artemis/)
23
+ Copyright 2026 Google LLC
24
+ Apache License, Version 2.0 - https://github.com/google/artemis
25
+
26
+ mobile-use (selected host modules and integrations/mobile-use/)
27
+ Copyright 2025-2026 Minitap, Inc.
28
+ Apache License, Version 2.0 - https://github.com/minitap-ai/mobile-use
29
+
30
+ Used as dependencies (not copied):
31
+ uiautomator2, adbutils - MIT - https://github.com/openatx
32
+ Model Context Protocol Python SDK - MIT - https://github.com/modelcontextprotocol/python-sdk
33
+
34
+ Android SDK Platform-Tools (adb) are not redistributed with headroid; users install them
35
+ separately under Google's Android SDK terms.
Binary file
headroid/adb.py ADDED
@@ -0,0 +1,124 @@
1
+ # Copyright 2026 Anand S Kale and the headroid contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Thin wrapper over the adb command line."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ import subprocess
9
+
10
+
11
+ class AdbError(RuntimeError):
12
+ """adb failed or was used ambiguously."""
13
+
14
+
15
+ def list_devices(adb_path: str = "adb") -> list[dict]:
16
+ """Returns [{"serial", "state", "model"}] from `adb devices -l`."""
17
+ try:
18
+ proc = subprocess.run(
19
+ [adb_path, "devices", "-l"], capture_output=True, text=True, timeout=30, check=False
20
+ )
21
+ except FileNotFoundError as e:
22
+ raise AdbError(f"adb not found: {adb_path}") from e
23
+ except subprocess.TimeoutExpired as e:
24
+ raise AdbError("adb devices timed out") from e
25
+ devices = []
26
+ for ln in (proc.stdout or "").splitlines()[1:]:
27
+ parts = ln.split()
28
+ if len(parts) < 2:
29
+ continue
30
+ m = re.search(r"\bmodel:(\S+)", ln)
31
+ model = m.group(1).replace("_", " ") if m else ""
32
+ devices.append({"serial": parts[0], "state": parts[1], "model": model})
33
+ return devices
34
+
35
+
36
+ class Adb:
37
+ def __init__(self, serial: str | None = None, adb_path: str = "adb"):
38
+ self.serial = serial
39
+ self.adb_path = adb_path
40
+ self._checked = False
41
+
42
+ def _base(self) -> list[str]:
43
+ cmd = [self.adb_path]
44
+ if self.serial:
45
+ cmd += ["-s", self.serial]
46
+ return cmd
47
+
48
+ def _devices(self) -> list[str]:
49
+ try:
50
+ proc = subprocess.run(
51
+ [self.adb_path, "devices"], capture_output=True, text=True, timeout=30, check=False
52
+ )
53
+ except FileNotFoundError as e:
54
+ raise AdbError(f"adb not found: {self.adb_path}") from e
55
+ out = proc.stdout or ""
56
+ return [ln.split()[0] for ln in out.splitlines()[1:] if re.search(r"\sdevice\b", ln)]
57
+
58
+ def relocate(self, hardware_serial: str) -> bool:
59
+ """Finds this phone again after a reconnect and switches to it.
60
+
61
+ A wireless phone can come back under another adb serial (its mDNS name or ip:port), so the attached
62
+ devices are matched on their hardware serial (ro.serialno). Returns False while it is not attached.
63
+ """
64
+ attached = self._devices()
65
+ if self.serial in attached:
66
+ return True
67
+ for serial in attached:
68
+ try:
69
+ found = Adb(serial, self.adb_path).shell("getprop ro.serialno").strip()
70
+ except AdbError:
71
+ continue
72
+ if found == hardware_serial:
73
+ self.serial = serial
74
+ return True
75
+ return False
76
+
77
+ def _ensure_unambiguous(self) -> None:
78
+ if self.serial or self._checked:
79
+ return
80
+ devices = self._devices()
81
+ if len(devices) > 1:
82
+ raise AdbError(
83
+ "multiple adb devices attached (" + ", ".join(devices) + "); "
84
+ "pass an explicit serial"
85
+ )
86
+ self._checked = True
87
+
88
+ def run(self, *args: str, timeout: float = 30) -> str:
89
+ self._ensure_unambiguous()
90
+ cmd = self._base() + [str(a) for a in args]
91
+ try:
92
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
93
+ except FileNotFoundError as e:
94
+ raise AdbError(f"adb not found: {self.adb_path}") from e
95
+ except subprocess.TimeoutExpired as e:
96
+ raise AdbError(f"adb timed out: {' '.join(cmd)}") from e
97
+ if proc.returncode != 0:
98
+ raise AdbError(f"adb failed ({proc.returncode}): {(proc.stderr or proc.stdout).strip()}")
99
+ return proc.stdout or ""
100
+
101
+ def shell(self, cmd: str) -> str:
102
+ return self.run("shell", cmd)
103
+
104
+ def push(self, local: str, remote: str) -> None:
105
+ self.run("push", str(local), remote, timeout=120)
106
+
107
+ def forward(self, remote: str = "localabstract:headroid") -> int:
108
+ out = self.run("forward", "tcp:0", remote).strip()
109
+ m = re.search(r"\d+", out)
110
+ if not m:
111
+ raise AdbError(f"could not parse forwarded port from adb output: {out!r}")
112
+ return int(m.group())
113
+
114
+ def remove_forward(self, port: int) -> None:
115
+ self.run("forward", "--remove", f"tcp:{port}")
116
+
117
+ def popen_shell(self, cmd: str) -> subprocess.Popen:
118
+ self._ensure_unambiguous()
119
+ return subprocess.Popen(
120
+ self._base() + ["shell", cmd],
121
+ stdout=subprocess.PIPE,
122
+ stderr=subprocess.STDOUT,
123
+ text=True,
124
+ )
headroid/cli.py ADDED
@@ -0,0 +1,88 @@
1
+ # Copyright 2026 Anand S Kale and the headroid contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Command line: headroid devices|doctor|launch|info|screenshot|tree."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import json
9
+ import os
10
+ import sys
11
+ import time
12
+
13
+ from .adb import AdbError, list_devices
14
+ from .device import Device
15
+ from .doctor import ok, run_doctor
16
+
17
+
18
+ def _parser() -> argparse.ArgumentParser:
19
+ p = argparse.ArgumentParser(prog="headroid")
20
+ sub = p.add_subparsers(dest="cmd", required=True)
21
+ sub.add_parser("devices", help="list adb devices")
22
+ s = sub.add_parser("doctor", help="check that this machine and phone are ready")
23
+ s.add_argument("--serial", default=None)
24
+ s.add_argument("--jar", default=None)
25
+ s = sub.add_parser("launch", help="launch an app on a hidden display and screenshot it")
26
+ s.add_argument("package")
27
+ s.add_argument("--activity", default=None)
28
+ s.add_argument("--screenshot", default=None, metavar="OUT.png")
29
+ s.add_argument("--wait", type=float, default=3.0, metavar="SECONDS")
30
+ s.add_argument("--serial", default=None)
31
+ s.add_argument("--jar", default=None)
32
+ for name in ("info", "screenshot", "tree"):
33
+ s = sub.add_parser(name)
34
+ s.add_argument("--serial", default=None)
35
+ s.add_argument("--jar", default=None)
36
+ if name == "screenshot":
37
+ s.add_argument("-o", "--output", default="screenshot.png")
38
+ return p
39
+
40
+
41
+ def _devices() -> int:
42
+ try:
43
+ devices = list_devices(os.environ.get("ADB", "adb"))
44
+ except AdbError as e:
45
+ print(f"error: {e}", file=sys.stderr)
46
+ return 1
47
+ if not devices:
48
+ print("no devices attached")
49
+ for d in devices:
50
+ print(f"{d['serial']}\t{d['state']}\t{d['model']}")
51
+ return 0
52
+
53
+
54
+ def _doctor(args) -> int:
55
+ checks = run_doctor(args.serial, args.jar, report=lambda c: print(c.line()))
56
+ return 0 if ok(checks) else 1
57
+
58
+
59
+ def main(argv: list[str] | None = None) -> int:
60
+ args = _parser().parse_args(argv)
61
+ if args.cmd == "devices":
62
+ return _devices()
63
+ if args.cmd == "doctor":
64
+ return _doctor(args)
65
+ dev = Device.connect(serial=args.serial, jar=args.jar)
66
+ try:
67
+ if args.cmd == "info":
68
+ print(json.dumps(dev.info(), indent=2))
69
+ else:
70
+ display = dev.create_display()
71
+ if args.cmd == "launch":
72
+ display.launch(args.package, args.activity)
73
+ time.sleep(args.wait)
74
+ out = args.screenshot or "launch.png"
75
+ data = display.screenshot(out)
76
+ print(f"wrote {out} ({len(data)} bytes)")
77
+ elif args.cmd == "screenshot":
78
+ data = display.screenshot(args.output)
79
+ print(f"wrote {args.output} ({len(data)} bytes)")
80
+ else:
81
+ print(json.dumps(display.tree(), indent=2))
82
+ finally:
83
+ dev.close()
84
+ return 0
85
+
86
+
87
+ if __name__ == "__main__":
88
+ sys.exit(main())
headroid/device.py ADDED
@@ -0,0 +1,209 @@
1
+ # Copyright 2026 Anand S Kale and the headroid contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """High-level Device and Display objects."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import os
9
+ import time
10
+ from collections.abc import Callable
11
+ from typing import Self
12
+
13
+ from .adb import Adb
14
+ from .jar import resolve_jar
15
+ from .rpc import RpcClient, RpcError
16
+ from .server import ServerProcess
17
+
18
+
19
+ class Display:
20
+ def __init__(
21
+ self,
22
+ client: RpcClient,
23
+ info: dict,
24
+ clock: Callable[[], float] = time.monotonic,
25
+ sleep: Callable[[float], None] = time.sleep,
26
+ ):
27
+ self._c = client
28
+ self.info = info
29
+ self.id: int = info["displayId"]
30
+ self._clock = clock
31
+ self._sleep = sleep
32
+
33
+ def launch(
34
+ self,
35
+ package: str,
36
+ activity: str | None = None,
37
+ mute: bool = True,
38
+ mute_notifications: bool = False,
39
+ ) -> None:
40
+ """Starts the app on this display.
41
+
42
+ mute: silence its sound and vibration (app-ops, restored when the app is stopped or the session ends).
43
+ mute_notifications: also block its notifications by revoking the notification permission. The app
44
+ can see this and may ask for the permission again, so it is off by default; skipped if the app is
45
+ already running.
46
+ """
47
+ self._c.call(
48
+ "app.launch",
49
+ displayId=self.id,
50
+ package=package,
51
+ activity=activity,
52
+ mute=mute,
53
+ muteNotifications=mute_notifications,
54
+ )
55
+
56
+ def tap(self, x: int, y: int) -> None:
57
+ self._c.call("input.tap", displayId=self.id, x=x, y=y)
58
+
59
+ def long_press(self, x: int, y: int, duration_ms: int = 600) -> None:
60
+ self._c.call("input.longPress", displayId=self.id, x=x, y=y, durationMs=duration_ms)
61
+
62
+ def swipe(self, x1: int, y1: int, x2: int, y2: int, duration_ms: int = 300) -> None:
63
+ self._c.call(
64
+ "input.swipe", displayId=self.id, x1=x1, y1=y1, x2=x2, y2=y2, durationMs=duration_ms
65
+ )
66
+
67
+ def key(self, code: int, meta_state: int = 0) -> None:
68
+ self._c.call("input.key", displayId=self.id, keyCode=code, metaState=meta_state)
69
+
70
+ def type(self, text: str) -> None:
71
+ self._c.call("input.text", displayId=self.id, text=text)
72
+
73
+ def screenshot(self, path: str | None = None, format: str = "png") -> bytes:
74
+ res = self._c.call("display.screenshot", displayId=self.id, format=format)
75
+ data = base64.b64decode(res["data"])
76
+ if path:
77
+ with open(path, "wb") as f:
78
+ f.write(data)
79
+ return data
80
+
81
+ def tree(self) -> list[dict]:
82
+ return self._c.call("ui.tree", displayId=self.id).get("nodes", [])
83
+
84
+ def find(
85
+ self, text: str | None = None, rid: str | None = None, desc: str | None = None
86
+ ) -> dict | None:
87
+ if text is None and rid is None and desc is None:
88
+ return None
89
+
90
+ def match(n: dict) -> bool:
91
+ if text is not None and n.get("text") != text:
92
+ return False
93
+ if desc is not None and n.get("desc") != desc:
94
+ return False
95
+ if rid is not None:
96
+ nrid = n.get("rid") or ""
97
+ if nrid != rid and nrid.rsplit("/", 1)[-1] != rid:
98
+ return False
99
+ return True
100
+
101
+ def walk(nodes):
102
+ for n in nodes:
103
+ if match(n):
104
+ return n
105
+ found = walk(n.get("children") or [])
106
+ if found:
107
+ return found
108
+ return None
109
+
110
+ return walk(self.tree())
111
+
112
+ def _on_screen(self, node: dict) -> bool:
113
+ left, top, right, bottom = node["bounds"]
114
+ width, height = self.info["width"], self.info["height"]
115
+ return 0 <= left < right <= width and 0 <= top < bottom <= height
116
+
117
+ def wait_for(
118
+ self,
119
+ text: str | None = None,
120
+ rid: str | None = None,
121
+ desc: str | None = None,
122
+ timeout: float = 10.0,
123
+ ) -> dict:
124
+ """Waits until the node is visible, fully on the display and at the same bounds on two reads.
125
+
126
+ During an activity transition the tree reports the incoming window's nodes at their animated
127
+ position (shifted by a display width for ~0.8 s), so acting on the first sighting misses.
128
+ """
129
+ deadline = self._clock() + timeout
130
+ last = None
131
+ while self._clock() < deadline:
132
+ node = self.find(text=text, rid=rid, desc=desc)
133
+ if node is not None and node.get("visible", True) and self._on_screen(node):
134
+ if last is not None and node["bounds"] == last:
135
+ return node
136
+ last = node["bounds"]
137
+ else:
138
+ last = None
139
+ self._sleep(0.2)
140
+ criteria = {k: v for k, v in (("text", text), ("rid", rid), ("desc", desc)) if v is not None}
141
+ raise TimeoutError(f"not found on screen and settled within {timeout}s: {criteria}")
142
+
143
+ def click(
144
+ self,
145
+ text: str | None = None,
146
+ rid: str | None = None,
147
+ desc: str | None = None,
148
+ timeout: float = 10.0,
149
+ ) -> dict:
150
+ node = self.wait_for(text=text, rid=rid, desc=desc, timeout=timeout)
151
+ left, top, right, bottom = node["bounds"]
152
+ self.tap((left + right) // 2, (top + bottom) // 2)
153
+ return node
154
+
155
+ def fill(
156
+ self,
157
+ value: str,
158
+ text: str | None = None,
159
+ rid: str | None = None,
160
+ desc: str | None = None,
161
+ timeout: float = 10.0,
162
+ ) -> dict:
163
+ node = self.click(text=text, rid=rid, desc=desc, timeout=timeout)
164
+ self.type(value)
165
+ return node
166
+
167
+ def release(self) -> None:
168
+ self._c.call("display.release", displayId=self.id)
169
+
170
+
171
+ class Device:
172
+ def __init__(self, client: RpcClient, server: ServerProcess | None = None):
173
+ self.client = client
174
+ self.server = server
175
+ self.displays: list[Display] = []
176
+
177
+ @classmethod
178
+ def connect(cls, serial: str | None = None, jar: str | None = None) -> Self:
179
+ jar = resolve_jar(jar)
180
+ adb = Adb(serial, os.environ.get("ADB", "adb"))
181
+ server = ServerProcess(adb, jar)
182
+ return cls(server.start(), server)
183
+
184
+ def info(self) -> dict:
185
+ return self.client.call("server.info")
186
+
187
+ def create_display(self, width: int = 720, height: int = 1600, dpi: int = 320) -> Display:
188
+ res = self.client.call("display.create", width=width, height=height, dpi=dpi)
189
+ d = Display(self.client, res)
190
+ self.displays.append(d)
191
+ return d
192
+
193
+ def close(self) -> None:
194
+ for d in self.displays:
195
+ try:
196
+ d.release()
197
+ except (OSError, RpcError):
198
+ pass
199
+ self.displays.clear()
200
+ if self.server is not None:
201
+ self.server.stop()
202
+ else:
203
+ self.client.close()
204
+
205
+ def __enter__(self) -> Self:
206
+ return self
207
+
208
+ def __exit__(self, *exc) -> None:
209
+ self.close()
headroid/doctor.py ADDED
@@ -0,0 +1,201 @@
1
+ # Copyright 2026 Anand S Kale and the headroid contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """`headroid doctor`: ordered environment checks, each with a one-line fix."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import subprocess
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+
12
+ from .adb import Adb, AdbError, list_devices
13
+ from .device import Device
14
+ from .jar import BUILD_HINT, resolve_jar
15
+ from .rpc import RpcError
16
+
17
+ PASS, FAIL, WARN = "PASS", "FAIL", "WARN"
18
+ MIN_API = 30
19
+ VERIFIED_API = range(34, 37) # Android 14-16
20
+ PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
21
+ NO_FRAME = -32011
22
+
23
+
24
+ @dataclass
25
+ class Check:
26
+ status: str
27
+ name: str
28
+ detail: str = ""
29
+ fix: str = ""
30
+
31
+ def line(self) -> str:
32
+ s = f"[{self.status}] {self.name}"
33
+ if self.detail:
34
+ s += f": {self.detail}"
35
+ if self.fix:
36
+ s += f" -> {self.fix}"
37
+ return s
38
+
39
+
40
+ def run_doctor(
41
+ serial: str | None = None,
42
+ jar: str | None = None,
43
+ adb_path: str | None = None,
44
+ connect: Callable[..., Device] = Device.connect,
45
+ report: Callable[[Check], None] = lambda c: None,
46
+ ) -> list[Check]:
47
+ """Runs the checks in order, stopping at a FAIL that makes later checks meaningless."""
48
+ adb_path = adb_path or os.environ.get("ADB", "adb")
49
+ checks: list[Check] = []
50
+
51
+ def add(status: str, name: str, detail: str = "", fix: str = "") -> Check:
52
+ c = Check(status, name, detail, fix)
53
+ checks.append(c)
54
+ report(c)
55
+ return c
56
+
57
+ # 1. adb on PATH
58
+ try:
59
+ proc = subprocess.run(
60
+ [adb_path, "version"], capture_output=True, text=True, timeout=30, check=False
61
+ )
62
+ first = (proc.stdout or "").splitlines()[0] if proc.stdout else "version unknown"
63
+ add(PASS, "adb on PATH", first)
64
+ except (FileNotFoundError, subprocess.TimeoutExpired):
65
+ add(
66
+ FAIL,
67
+ "adb on PATH",
68
+ "not found",
69
+ "install Android platform-tools and add it to PATH (or set ADB=/path/to/adb)",
70
+ )
71
+ return checks
72
+
73
+ # 2. device selection
74
+ try:
75
+ devices = list_devices(adb_path)
76
+ except AdbError as e:
77
+ add(FAIL, "adb devices", str(e), "run `adb start-server` and retry")
78
+ return checks
79
+ listing = ", ".join(f"{d['serial']} ({d['state']})" for d in devices)
80
+ if serial is None:
81
+ if not devices:
82
+ add(
83
+ FAIL,
84
+ "device attached",
85
+ "none",
86
+ "connect the phone with USB debugging on, then run `adb devices`",
87
+ )
88
+ return checks
89
+ if len(devices) > 1:
90
+ add(
91
+ FAIL,
92
+ "device attached",
93
+ f"{len(devices)} devices: {listing}",
94
+ "pass --serial <serial>",
95
+ )
96
+ return checks
97
+ serial = devices[0]["serial"]
98
+ match = next((d for d in devices if d["serial"] == serial), None)
99
+ if match is None:
100
+ add(
101
+ FAIL,
102
+ "device attached",
103
+ f"{serial} not listed (attached: {listing or 'none'})",
104
+ "check the serial with `headroid devices`",
105
+ )
106
+ return checks
107
+ add(PASS, "device attached", f"{serial} {match['model']}".strip())
108
+
109
+ # 3. device state
110
+ state = match["state"]
111
+ if state == "unauthorized":
112
+ add(FAIL, "device state", state, "accept the USB debugging prompt on the phone")
113
+ return checks
114
+ if state == "offline":
115
+ add(FAIL, "device state", state, "unplug and reconnect the cable, or run `adb reconnect`")
116
+ return checks
117
+ if state != "device":
118
+ add(FAIL, "device state", state, "make sure the phone shows as `device` in `adb devices`")
119
+ return checks
120
+ add(PASS, "device state", state)
121
+
122
+ # 4. Android version and manufacturer
123
+ adb = Adb(serial, adb_path)
124
+ try:
125
+ api = int(adb.shell("getprop ro.build.version.sdk").strip())
126
+ maker = adb.shell("getprop ro.product.manufacturer").strip()
127
+ except (AdbError, ValueError) as e:
128
+ add(FAIL, "Android API level", str(e), "check `adb -s <serial> shell getprop`")
129
+ return checks
130
+ if api < MIN_API:
131
+ add(FAIL, "Android API level", f"{api}", "the server needs Android 11 (API 30) or newer")
132
+ return checks
133
+ if api not in VERIFIED_API:
134
+ add(WARN, "Android API level", f"{api}", "only Android 14-16 (API 34-36) are verified")
135
+ else:
136
+ add(PASS, "Android API level", f"{api}")
137
+ if maker.lower() in ("xiaomi", "redmi", "poco"):
138
+ add(
139
+ WARN,
140
+ "manufacturer",
141
+ maker,
142
+ "Developer options: enable 'USB debugging (Security settings)' for input "
143
+ "and 'Install via USB' for installs",
144
+ )
145
+
146
+ # 5. jar
147
+ try:
148
+ jar_path = resolve_jar(jar)
149
+ except FileNotFoundError:
150
+ add(FAIL, "server jar", "not found", BUILD_HINT)
151
+ return checks
152
+ if not os.path.isfile(jar_path):
153
+ add(FAIL, "server jar", f"{jar_path} does not exist", BUILD_HINT)
154
+ return checks
155
+ add(PASS, "server jar", jar_path)
156
+
157
+ # 6. server starts and answers, 7. hidden display screenshot
158
+ try:
159
+ dev = connect(serial=serial, jar=jar_path)
160
+ except Exception as e: # noqa: BLE001 - report any startup failure as a check result
161
+ add(FAIL, "server starts", str(e), "keep the phone unlocked and retry")
162
+ return checks
163
+ try:
164
+ try:
165
+ info = dev.info()
166
+ add(
167
+ PASS,
168
+ "server.info",
169
+ f"sdk={info.get('sdk')} model={info.get('model')} "
170
+ f"capabilities={info.get('capabilities')}",
171
+ )
172
+ except Exception as e: # noqa: BLE001
173
+ add(FAIL, "server.info", str(e), "the server started but does not answer")
174
+ return checks
175
+ try:
176
+ display = dev.create_display()
177
+ except Exception as e: # noqa: BLE001
178
+ add(FAIL, "hidden display", str(e), "report this with `adb logcat -s scrcpy`")
179
+ return checks
180
+ add(PASS, "hidden display", f"id {display.id}")
181
+ try:
182
+ png = display.screenshot()
183
+ if png[:8] == PNG_MAGIC:
184
+ add(PASS, "hidden display screenshot", f"{len(png)} bytes PNG")
185
+ else:
186
+ add(FAIL, "hidden display screenshot", "not a PNG", "report this with adb logcat")
187
+ except RpcError as e:
188
+ if e.code == NO_FRAME:
189
+ # an empty display draws nothing, so there is no frame until an app is launched on it
190
+ add(PASS, "hidden display screenshot", "empty display, no frame until an app draws")
191
+ else:
192
+ add(FAIL, "hidden display screenshot", str(e), "report this with adb logcat")
193
+ except Exception as e: # noqa: BLE001
194
+ add(FAIL, "hidden display screenshot", str(e), "report this with adb logcat")
195
+ finally:
196
+ dev.close() # releases the display
197
+ return checks
198
+
199
+
200
+ def ok(checks: list[Check]) -> bool:
201
+ return not any(c.status == FAIL for c in checks)
headroid/jar.py ADDED
@@ -0,0 +1,46 @@
1
+ # Copyright 2026 Anand S Kale and the headroid contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Finds the device-server jar: argument, env, wheel bundle, then a source checkout build."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ from importlib import resources
9
+ from pathlib import Path
10
+
11
+ ENV_VAR = "HEADROID_SERVER_JAR"
12
+ JAR_NAME = "headroid-server.jar"
13
+ BUILD_HINT = (
14
+ "build it with `cd device-server && ./gradlew :server:headroidJar` "
15
+ f"or point {ENV_VAR} at an existing {JAR_NAME}"
16
+ )
17
+
18
+
19
+ def _bundled() -> Path | None:
20
+ try:
21
+ res = resources.files("headroid").joinpath("_server", JAR_NAME)
22
+ with resources.as_file(res) as p:
23
+ return Path(p) if Path(p).is_file() else None
24
+ except (FileNotFoundError, ModuleNotFoundError, OSError):
25
+ return None
26
+
27
+
28
+ def _source_checkout() -> Path:
29
+ repo = Path(__file__).resolve().parents[4]
30
+ return repo / "device-server" / "server" / "build" / "headroid" / JAR_NAME
31
+
32
+
33
+ def resolve_jar(jar: str | None = None) -> str:
34
+ """Returns the jar path. Order: jar argument, HEADROID_SERVER_JAR, wheel bundle, source build."""
35
+ if jar:
36
+ return str(jar)
37
+ env = os.environ.get(ENV_VAR)
38
+ if env:
39
+ return env
40
+ bundled = _bundled()
41
+ if bundled is not None:
42
+ return str(bundled)
43
+ built = _source_checkout()
44
+ if built.is_file():
45
+ return str(built)
46
+ raise FileNotFoundError(f"headroid server jar not found: {BUILD_HINT}")
headroid/rpc.py ADDED
@@ -0,0 +1,53 @@
1
+ # Copyright 2026 Anand S Kale and the headroid contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Newline-delimited JSON-RPC 2.0 client."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import socket
9
+ import threading
10
+
11
+
12
+ class RpcError(Exception):
13
+ def __init__(self, code: int, message: str):
14
+ super().__init__(f"[{code}] {message}")
15
+ self.code = code
16
+ self.message = message
17
+
18
+
19
+ class RpcClient:
20
+ def __init__(self, host: str, port: int, timeout: float = 30):
21
+ self.sock = socket.create_connection((host, port), timeout=timeout)
22
+ self.sock.settimeout(timeout)
23
+ self._file = self.sock.makefile("rb")
24
+ self._lock = threading.Lock()
25
+ self._next_id = 0
26
+ self.events: list[dict] = []
27
+
28
+ def call(self, method: str, **params) -> dict:
29
+ with self._lock:
30
+ self._next_id += 1
31
+ rid = self._next_id
32
+ req = {"jsonrpc": "2.0", "id": rid, "method": method, "params": params}
33
+ self.sock.sendall(json.dumps(req).encode("utf-8") + b"\n")
34
+ while True:
35
+ line = self._file.readline()
36
+ if not line:
37
+ raise ConnectionError("connection closed by server")
38
+ msg = json.loads(line)
39
+ if msg.get("method") == "event" and "id" not in msg:
40
+ self.events.append(msg.get("params", {}))
41
+ continue
42
+ if msg.get("id") != rid:
43
+ continue
44
+ if msg.get("error") is not None:
45
+ err = msg["error"]
46
+ raise RpcError(err.get("code", -32000), err.get("message", ""))
47
+ return msg.get("result") or {}
48
+
49
+ def close(self) -> None:
50
+ try:
51
+ self._file.close()
52
+ finally:
53
+ self.sock.close()
headroid/server.py ADDED
@@ -0,0 +1,154 @@
1
+ # Copyright 2026 Anand S Kale and the headroid contributors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Pushes, starts and stops the headroid device server on the phone."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import secrets
9
+ import time
10
+
11
+ from .adb import Adb, AdbError
12
+ from .rpc import RpcClient, RpcError
13
+
14
+ REMOTE_DIR = "/data/local/tmp"
15
+ MAIN_CLASS = "dev.headroid.server.HeadroidServer"
16
+ # How long the server keeps the session (displays, apps, mutes) without a host. Long enough for a wireless adb
17
+ # reconnect or a short laptop sleep; after it the server tears everything down and exits.
18
+ GRACE_S = 60
19
+
20
+ # Calls that read state only: safe to resend after a reconnect. Actions are not resent, since they may have run.
21
+ SAFE_TO_RETRY = {"server.info", "display.list", "display.screenshot", "ui.tree"}
22
+
23
+
24
+ def remote_jar_path(jar_path: str) -> str:
25
+ """Where the jar goes on the phone, named by its content so a push never overwrites a jar that another
26
+ running server (another session, another headroid version) still has open."""
27
+ with open(jar_path, "rb") as f:
28
+ digest = hashlib.sha256(f.read()).hexdigest()[:12]
29
+ return f"{REMOTE_DIR}/headroid-server-{digest}.jar"
30
+
31
+
32
+ class ReconnectingClient:
33
+ """An RpcClient that survives a dropped connection (wireless adb reconnect, laptop sleep).
34
+
35
+ On a connection error it reconnects to the same server, which kept the session. Read-only calls are then
36
+ resent; for actions it raises ConnectionError saying the action may or may not have run.
37
+ """
38
+
39
+ def __init__(self, server: ServerProcess, client: RpcClient):
40
+ self._server = server
41
+ self._client = client
42
+
43
+ @property
44
+ def events(self) -> list[dict]:
45
+ return self._client.events
46
+
47
+ def call(self, method: str, **params) -> dict:
48
+ try:
49
+ return self._client.call(method, **params)
50
+ except (ConnectionError, OSError) as first:
51
+ if method == "server.shutdown":
52
+ raise
53
+ self._client = self._server.reconnect()
54
+ if method in SAFE_TO_RETRY:
55
+ return self._client.call(method, **params)
56
+ raise ConnectionError(
57
+ f"connection to the phone dropped during {method} and was restored; "
58
+ "the action may or may not have run"
59
+ ) from first
60
+
61
+ def close(self) -> None:
62
+ self._client.close()
63
+
64
+
65
+ class ServerProcess:
66
+ def __init__(
67
+ self, adb: Adb, jar_path: str, socket: str | None = None, grace_s: float = GRACE_S
68
+ ):
69
+ self.adb = adb
70
+ self.jar_path = jar_path
71
+ self.socket = socket or f"headroid-{secrets.token_hex(4)}"
72
+ self.grace_s = grace_s
73
+ self.port: int | None = None
74
+ self.client: ReconnectingClient | None = None
75
+ self.hardware_serial = "" # ro.serialno, to find the phone again under a new adb serial
76
+
77
+ def start(self, connect_timeout: float = 10) -> ReconnectingClient:
78
+ remote = remote_jar_path(self.jar_path)
79
+ self.hardware_serial = self.adb.shell("getprop ro.serialno").strip()
80
+ self.adb.push(self.jar_path, remote)
81
+ # setsid and closed stdio: the server must outlive this adb shell, so a dropped wireless connection
82
+ # does not kill it (it would take the session with it); its own watchdog ends it when no host returns.
83
+ cmd = (
84
+ f"CLASSPATH={remote} setsid app_process / {MAIN_CLASS} socket={self.socket} "
85
+ f"grace_ms={int(self.grace_s * 1000)} </dev/null >/dev/null 2>&1 &"
86
+ )
87
+ self.adb.shell(cmd)
88
+ try:
89
+ client = self._connect(connect_timeout)
90
+ except TimeoutError as e:
91
+ self.stop()
92
+ raise TimeoutError(f"headroid server did not come up in {connect_timeout}s: {e}") from e
93
+ self.client = ReconnectingClient(self, client)
94
+ return self.client
95
+
96
+ def _connect(self, timeout: float) -> RpcClient:
97
+ deadline = time.monotonic() + timeout
98
+ last: Exception | None = None
99
+ while time.monotonic() < deadline:
100
+ client = None
101
+ try:
102
+ if self.port is None:
103
+ if self.hardware_serial and not self.adb.relocate(self.hardware_serial):
104
+ raise AdbError("the phone is not attached (yet)")
105
+ self.port = self.adb.forward(f"localabstract:{self.socket}")
106
+ # adb accepts the forwarded connection even before the server listens,
107
+ # so confirm with a real call.
108
+ client = RpcClient("127.0.0.1", self.port)
109
+ client.call("server.info")
110
+ return client
111
+ except (OSError, RpcError, ValueError, AdbError) as e:
112
+ last = e
113
+ if client is not None:
114
+ try:
115
+ client.close()
116
+ except OSError:
117
+ pass
118
+ time.sleep(0.25)
119
+ raise TimeoutError(str(last))
120
+
121
+ def reconnect(self) -> RpcClient:
122
+ """Connects again to the same server, for up to the grace period. A new adb transport needs a new
123
+ port forward, so the old one is dropped first."""
124
+ if self.port is not None:
125
+ try:
126
+ self.adb.remove_forward(self.port)
127
+ except AdbError:
128
+ pass
129
+ self.port = None
130
+ try:
131
+ return self._connect(self.grace_s)
132
+ except TimeoutError as e:
133
+ raise ConnectionError(
134
+ f"lost the phone and could not reconnect within {self.grace_s:.0f}s; "
135
+ f"the server has torn the session down: {e}"
136
+ ) from e
137
+
138
+ def stop(self) -> None:
139
+ if self.client is not None:
140
+ try:
141
+ self.client.call("server.shutdown")
142
+ except (OSError, RpcError):
143
+ pass
144
+ try:
145
+ self.client.close()
146
+ except OSError:
147
+ pass
148
+ self.client = None
149
+ if self.port is not None:
150
+ try:
151
+ self.adb.remove_forward(self.port)
152
+ except AdbError:
153
+ pass
154
+ self.port = None
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.5
2
+ Name: headroid
3
+ Version: 0.1.0a1
4
+ Summary: Test Android apps on a hidden display of your own phone while you keep using it.
5
+ Project-URL: Homepage, https://github.com/anand-s-kale/headroid
6
+ Project-URL: Documentation, https://github.com/anand-s-kale/headroid/tree/main/packages/headroid#readme
7
+ Project-URL: Issues, https://github.com/anand-s-kale/headroid/issues
8
+ Project-URL: Changelog, https://github.com/anand-s-kale/headroid/blob/main/CHANGELOG.md
9
+ Author: Anand S Kale and the headroid contributors
10
+ License-Expression: Apache-2.0
11
+ Keywords: adb,ai-agents,android,automation,headless,testing,ui-testing,virtual-display
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Testing
20
+ Classifier: Topic :: Software Development :: Testing :: Acceptance
21
+ Requires-Python: >=3.11
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8; extra == 'dev'
24
+ Requires-Dist: ruff; extra == 'dev'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # headroid (Python host)
28
+
29
+ Run Android apps on a hidden virtual display and drive them from Python. No runtime dependencies;
30
+ needs `adb` on PATH and an Android 11+ phone with USB debugging on (Android 14-16 are verified).
31
+
32
+ ## 1. Install
33
+
34
+ ```
35
+ pip install --pre headroid
36
+ ```
37
+
38
+ (`--pre` while headroid is an alpha. The wheel is also attached to each
39
+ [GitHub release](https://github.com/anand-s-kale/headroid/releases).)
40
+
41
+ The wheel bundles the device-server jar, so there is nothing else to build. From a source checkout instead:
42
+ `cd device-server && ./gradlew :server:headroidJar`, then `pip install -e packages/headroid`; the jar is found
43
+ in the build folder (or set `HEADROID_SERVER_JAR`).
44
+
45
+ ## 2. Check your setup
46
+
47
+ ```
48
+ headroid devices
49
+ headroid doctor # add --serial <serial> when more than one device is attached
50
+ ```
51
+
52
+ `doctor` checks adb, the device and its state, the Android version, the server jar, and that the server can
53
+ create a hidden display and take a screenshot. Each line is PASS, WARN or FAIL with a one-line fix. It exits
54
+ 0 unless something FAILed.
55
+
56
+ **Xiaomi / Redmi / POCO:** in Developer options enable "USB debugging (Security settings)" (needed for
57
+ input) and "Install via USB" (needed to install apps).
58
+
59
+ ## 3. See an app on a hidden display
60
+
61
+ ```
62
+ headroid launch dev.headroid.sample --screenshot shot.png
63
+ ```
64
+
65
+ This creates a hidden display, launches the app on it, waits 3 seconds (`--wait`), saves the screenshot and
66
+ releases the display. Nothing appears on the phone's own screen.
67
+
68
+ ## 4. Drive it from Python
69
+
70
+ ```python
71
+ from headroid import Device
72
+
73
+ with Device.connect() as dev: # jar found automatically
74
+ d = dev.create_display(720, 1600, 320) # hidden virtual display
75
+ d.launch("dev.headroid.sample")
76
+ d.click(rid="nav_login") # waits until the node has settled, then taps it
77
+ d.fill("demo@headroid.dev", rid="login_email")
78
+ d.fill("headroid", rid="login_password")
79
+ d.click(rid="login_submit")
80
+ d.wait_for(rid="form_name") # raises TimeoutError naming what it waited for
81
+ d.screenshot("form.png")
82
+ ```
83
+
84
+ `click`, `fill` and `wait_for` take `text=`, `rid=` or `desc=` and a `timeout` (default 10 s). They wait
85
+ until the node is visible, fully on the display and at the same position on two reads in a row, because
86
+ during an activity transition nodes are reported at animated positions and an immediate tap misses.
87
+ Lower-level calls (`tap`, `swipe`, `key`, `type`, `tree`, `find`) are also available.
88
+
89
+ ## What stays with you, and what does not
90
+
91
+ - Taps, typing and the keyboard go to the hidden display only; your screen keeps focus.
92
+ - `launch` mutes the app's **sound and vibration** (app-ops) and restores them when the app is stopped or the
93
+ session ends, even if the server was killed (the next server start restores them). Pass `mute=False` to hear it.
94
+ App-ops are per app: while muted, the same app is silent on your screen too.
95
+ - **Notifications** still reach your notification shade by default. `launch(..., mute_notifications=True)` blocks
96
+ them by revoking the notification permission while the session runs; the app can see that and may ask for the
97
+ permission again, so it is opt-in, and it is skipped when the app is already running.
98
+ - Toasts, dialogs and permission prompts appear on the hidden display.
99
+ - A Wi-Fi drop does not end the session: the server keeps it for 60 s, the host reconnects (finding the phone even
100
+ under a new adb serial) and resends reads; an action that was in flight raises `ConnectionError` saying it may or
101
+ may not have run. If no host returns within 60 s, the server tears everything down and exits.
102
+ - Several sessions can share one phone: each gets its own server socket and its own mute records.
103
+ - At the end, an app is force-stopped only if headroid started it and nobody else has it open. If it was already
104
+ running (your copy on the phone, or another session's), only the hidden display is closed and the app keeps running.
105
+ - Android has one UiAutomation (used for the UI tree and `setText` typing) for every tool on the phone. headroid holds it
106
+ only while reading the screen and releases it after 1 s idle; when another tool (Appium, `uiautomator`, Maestro,
107
+ another session) holds it, a tree read waits up to 10 s, then fails with a message naming the cause.
108
+
109
+ ## Other commands
110
+
111
+ ```
112
+ headroid info | screenshot -o shot.png | tree # all accept --serial and --jar
113
+ ```
114
+
115
+ `--jar` is optional everywhere. Resolution order: `--jar` / `jar=`, then `HEADROID_SERVER_JAR`, then the
116
+ jar bundled in the wheel, then a source-checkout build.
117
+
118
+ ## Development
119
+
120
+ ```
121
+ python -m venv .venv && .venv/Scripts/python -m pip install -e ".[dev]" && python -m pytest -q
122
+ ```
123
+
124
+ Tests use a fake JSON-RPC server and a fake adb; no phone needed. To build a wheel with the jar bundled:
125
+ build the jar, then `python scripts/build_wheel.py` (needs `pip install build`).
@@ -0,0 +1,15 @@
1
+ headroid/__init__.py,sha256=luJ2VylxdOLujtcnXtOlP4c1nz0J89CTAAlEp4PvyCw,467
2
+ headroid/adb.py,sha256=AtkwOv5TYDvktPTo_qK8V_qYyxNZUHt3qOQbm0dCx9E,4512
3
+ headroid/cli.py,sha256=DdOYPBkLajzDOgtIyJ6-1RhEYKbOoPCp-R19NHh_5_0,2958
4
+ headroid/device.py,sha256=c12bA3_XcmnL1Z4zPoee5Vmed4I4p39CMgomDXvrd68,7031
5
+ headroid/doctor.py,sha256=q3UgVYcPXpm7vmdU0hN654Dmd4irqGwPFjmm4lj6JIc,7094
6
+ headroid/jar.py,sha256=EzFMXsnlFdxcGlL5hBT6DcYxc2jAr5Edd2JKf3k2ESo,1451
7
+ headroid/rpc.py,sha256=-4r60p4u8cc-ejYRvJO5nLyyfqMILAT52oApWK4cubQ,1827
8
+ headroid/server.py,sha256=FKE5WhyXhH6XlV7cPfgpod1M3Zb7guhedc-pJN5k1bs,6159
9
+ headroid/_server/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
10
+ headroid/_server/NOTICE,sha256=SQgQGkFlyrtXVstRD9bBaD118sxacHoCcwYoaxFYlk4,1567
11
+ headroid/_server/headroid-server.jar,sha256=AbKb5UMLF7NNy34-uvfvgUTxgsCUb7LnGJy10DfrfFo,2360494
12
+ headroid-0.1.0a1.dist-info/METADATA,sha256=jpmsNu8pnG0SYcNZPA8j26XnHPZAHxAs7PBgmwZDgQI,6175
13
+ headroid-0.1.0a1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ headroid-0.1.0a1.dist-info/entry_points.txt,sha256=BUJQpsPibbrP7LnLEYdcH0lGRvHpVCh5_W_jQtMsbYA,47
15
+ headroid-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ headroid = headroid.cli:main