diff --git a/docs/internal/agent-rules/safety.md b/docs/internal/agent-rules/safety.md index 1ac963978..5b4ebdd8c 100644 --- a/docs/internal/agent-rules/safety.md +++ b/docs/internal/agent-rules/safety.md @@ -21,7 +21,12 @@ never enforce them only inside an individual rule or driver. erases, reboots, shuts down or unpairs a physical device, and never runs a command on one that is not enrolled, except `device add`'s read-only inspection, which a worker with `devices.autoEnroll` runs on a phone plugged in - by USB ([ADR 0073](../adr/0073-a-worker-may-enrol-the-phones-plugged-into-it.md) §5) + by USB ([ADR 0073](../adr/0073-a-worker-may-enrol-the-phones-plugged-into-it.md) §5), or under + `android.networkDevices` one reached over the network ([ADR 0080](../adr/0080-an-android-worker-may-enrol-phones-reached-over-the-network.md) §4), + and, under `android.networkDevices`, `adb connect` for an enrolled + address and the read-only inspection and hardware-serial read that may + reach a phone answering at an enrolled address that is not the enrolled + one ([ADR 0080](../adr/0080-an-android-worker-may-enrol-phones-reached-over-the-network.md) §5) ([ADR 0022](../adr/0022-a-physical-device-is-a-second-device-type-the-core-knows.md) §3). A component (an iOS simulator runtime or an Android system image) is @@ -99,8 +104,9 @@ never enforce them only inside an individual rule or driver. scoped by `simctl --set` and `ANDROID_AVD_HOME` — never the machine's default device locations. (Under iOS `deviceSet: "default"`, reality is Xcode's set read through devices whose durable mark names this instance, ADR 0048 §2.) For a physical device, reality is the platform - tool's list of USB devices, read only for enrolled IDs. The one read made beyond - enrolled IDs is the host-level USB list, `listAttachedPhysical()` (ADR 0073 §5). + tool's list of USB devices (under `android.networkDevices`, network phones too), read only for enrolled IDs. The one read made beyond + enrolled IDs is the host-level USB list, `listAttachedPhysical()` (ADR 0073 §5); under + `android.networkDevices` it also lists network transports, never an emulator (ADR 0080 §5). 8. **Ownership is proven, never inferred.** A device is Simlock's because it lives inside a validly-marked Simlock root, not because of what it is called. `Driver.listManaged()` must answer from root membership; the @@ -112,7 +118,8 @@ never enforce them only inside an individual rule or driver. physical device is Simlock's because an admin enrolled it, or the worker did under `devices.autoEnroll`; `listPresentPhysical()` answers only for enrolled IDs; `listAttachedPhysical()` - is the exception, a host-level list that names no phone and sends nothing to one. + is the exception, a host-level list that names no phone and sends nothing to one; + under `android.networkDevices` it also lists network transports (ADR 0080 §5). 9. **Root validation fails closed.** If a device root is missing its marker, carries another instance's marker, is a symlink, or has the wrong owner or permissions, that platform's driver does not start and Simlock reports why. Under iOS diff --git a/docs/internal/agent-rules/toolchain.md b/docs/internal/agent-rules/toolchain.md index 56fcdd33b..74cd1418a 100644 --- a/docs/internal/agent-rules/toolchain.md +++ b/docs/internal/agent-rules/toolchain.md @@ -212,7 +212,7 @@ The machine can run a line only if: | Physical iOS | `uname -s` is `Darwin`; `SIMLOCK_PHYSICAL_IOS` is the UDID of an iPhone on USB (trusted, Developer Mode on, unlocked, Auto-Lock Never); `SIMLOCK_PHYSICAL_IOS_APP` is a `.app` signed for it. `/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" /Library/Developer/PrivateFrameworks/CoreDevice.framework/Resources/Info.plist` prints a version whose major is 642 or later (streaming a phone needs the CoreDevice of Xcode 27 or later; the framework is machine-wide and does not follow `xcode-select`). DeviceHub and Xcode are not running during the lane. The stream cases need the iPhone on iOS 27 or later; an older iPhone runs the refusal case instead. Run `scripts/slow-e2e.sh --physical e2e/slow-ios-physical.test.ts` | | iOS foldable | the iOS check; `xcrun simctl list runtimes` lists iOS 27.1 or later and `xcrun simctl list devicetypes` lists `iPhone Duo`; `SIMLOCK_E2E_AGENT_DEVICE` names agent-device 0.21.35 or later; `command -v ffmpeg` finds it. Run `scripts/slow-e2e.sh e2e/slow-ios-foldable.test.ts` | | agent-device through simlock | `node -v` is 22.12.0 or later (agent-device's own minimum); the iOS check and `uname -m` is `arm64` (the fixture app is arm64 only), or the Android check; `SIMLOCK_E2E_AGENT_DEVICE` (in `.slow-lane.env`) is the absolute path of `bin/agent-device.mjs` in an install of the agent-device version `package.json` pins for `@agent-device/proxy` (`npm install -g agent-device@`, or a checkout at tag `v` built with `pnpm install && pnpm build && pnpm build:android`, the last building the Android snapshot helper); room for two devices: `node -p "os.totalmem() / 2**30"` prints at least 7 for iOS or 12 for Android (simlock's 4 GiB OS reserve plus two of its default 1.5 GiB iOS or 4 GiB Android per-device budgets). Run `scripts/slow-e2e.sh e2e/slow-agent-device.test.ts` or `scripts/slow-e2e.sh e2e/slow-agent-device-gateway.test.ts` | -| Physical Android | `command -v adb` finds it; `adb devices -l` lists `$SIMLOCK_PHYSICAL_ANDROID` on a USB transport (a `usb:` field) in state `device`; `SIMLOCK_PHYSICAL_ANDROID_APK` names an APK. Run `scripts/slow-e2e.sh --physical e2e/slow-android-physical.test.ts` | +| Physical Android | `command -v adb` finds it; `adb devices -l` lists `$SIMLOCK_PHYSICAL_ANDROID` on a USB transport (a `usb:` field) in state `device`; `SIMLOCK_PHYSICAL_ANDROID_APK` names an APK; `SIMLOCK_PHYSICAL_ANDROID_NETWORK` beside it names an address `adb devices -l` lists in state `device` with no `usb:` field, for the network case. Run `scripts/slow-e2e.sh --physical e2e/slow-android-physical.test.ts` | | agent-device with a physical phone | the agent-device through simlock checks above (the Android or iOS one), and the Physical Android checks with `SIMLOCK_PHYSICAL_ANDROID`, or the Physical iOS checks with `SIMLOCK_PHYSICAL_IOS`; for iOS also `SIMLOCK_E2E_IOS_TEAM_ID` and `SIMLOCK_E2E_IOS_BUNDLE_ID` (in `.slow-lane.env`); set `SIMLOCK_E2E_IOS_PROVISIONING_PROFILE` and `SIMLOCK_E2E_IOS_SIGNING_IDENTITY` only for manual signing, which an Xcode-managed profile fails. Run `scripts/slow-e2e.sh --physical e2e/slow-agent-device-physical.test.ts` | | Physical Android, a person at the phone | the Physical Android checks above, and `SIMLOCK_PHYSICAL_PERSON` is `1`. Run `scripts/slow-e2e.sh --physical-manual e2e/slow-android-physical-manual.test.ts` | | Physical iOS, a person at the phone | the Physical iOS checks above, a passcode set on the phone (locking it then needs the passcode), and `SIMLOCK_PHYSICAL_PERSON` is `1`. Run `scripts/slow-e2e.sh --physical-manual e2e/slow-ios-physical-manual.test.ts` | diff --git a/e2e/slow-android-physical.test.ts b/e2e/slow-android-physical.test.ts index 1e0ff34a7..ac004614c 100644 --- a/e2e/slow-android-physical.test.ts +++ b/e2e/slow-android-physical.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest"; import { deviceStreamUrl, + freeLoopbackPort, type TestEnv, waitFor, waitForDeviceState, @@ -14,6 +15,7 @@ const execFileAsync = promisify(execFile); const SERIAL = process.env["SIMLOCK_PHYSICAL_ANDROID"]; const APK = process.env["SIMLOCK_PHYSICAL_ANDROID_APK"]; +const NETWORK = process.env["SIMLOCK_PHYSICAL_ANDROID_NETWORK"]; const PROBE_INTERVAL_MS = 2_000; const EXEC_TIMEOUT_MS = 5_000; @@ -30,6 +32,14 @@ const missing = ? "SIMLOCK_PHYSICAL_ANDROID_APK" : undefined; +// why: the network case has its own gate, so a lane with a USB phone only still runs the USB cases. +const missingNetwork = + NETWORK === undefined || NETWORK === "" + ? "SIMLOCK_PHYSICAL_ANDROID_NETWORK" + : APK === undefined || APK === "" + ? "SIMLOCK_PHYSICAL_ANDROID_APK" + : undefined; + interface Frame { readonly tag: number; readonly payload: Uint8Array; @@ -45,6 +55,7 @@ interface Rig { readonly env: TestEnv; readonly base: string; readonly auth: Record; + readonly port: number; } async function adbOut(serial: string, args: readonly string[]): Promise { @@ -83,15 +94,19 @@ async function serverPid(): Promise { return stdout.trim().split("\n")[0] ?? ""; } -async function rig(options: { readonly execTimeoutMs?: number } = {}): Promise { +async function rig( + options: { readonly execTimeoutMs?: number; readonly networkDevices?: boolean } = {}, +): Promise { const { env, port } = await withHttpDaemon((port) => ({ configOverrides: { ...(options.execTimeoutMs === undefined ? {} : { exec: { timeoutMs: options.execTimeoutMs } }), + ...(options.networkDevices === true ? { android: { networkDevices: true } } : {}), health: { probeIntervalMs: PROBE_INTERVAL_MS, stableObservations: 2 }, http: { enabled: true, host: "127.0.0.1", port }, capabilities: { + ...(options.networkDevices === true ? { tunnel: { enabled: true } } : {}), stream: { bitrateKbps: 1500, enabled: true, fps: 30, maxDimension: 720 }, }, }, @@ -114,7 +129,7 @@ async function rig(options: { readonly execTimeoutMs?: number } = {}): Promise> { @@ -441,3 +456,78 @@ describe.skipIf(missing !== undefined)( ); }, ); + +// why: the case needs a phone adb lists with no usb: field, which only an operator can connect; it runs when both the address and an APK are named. +describe.skipIf(missingNetwork !== undefined)( + missingNetwork === undefined + ? "Android physical phone over the network (real adb)" + : `Android physical phone over the network (skipped: ${missingNetwork} is not set)`, + { tags: ["slow", "android", "physical"] }, + () => { + const address = NETWORK as string; + const apk = APK as string; + + it( + "under android.networkDevices a phone listed by adb over the network is enrolled under its address and leased with ANDROID_SERIAL set to it, device.exec, the screen and a reverse tunnel work on it, and releasing uninstalls an app installed during the lease", + { timeout: 10 * MINUTE }, + async () => { + const name = await installApk(address, apk); + await uninstall(address, name); + const enrolledApps = await userAppsOf(address); + try { + const daemon = await rig({ networkDevices: true }); + const added = await enroll(daemon.env, address); + expect(added["driverDeviceId"]).toBe(address); + const grant = await leasePhysical(daemon.env); + expect(grant.environment["ANDROID_SERIAL"]).toBe(address); + expect(grant.environment["ANDROID_ADB_SERVER_PORT"]).toBe("5037"); + + const hardwareSerial = ( + await adbOut(address, ["shell", "getprop", "ro.serialno"]) + ).trim(); + expect(await exec(daemon, grant.lease.id, ["shell", "getprop", "ro.serialno"])).toContain( + hardwareSerial, + ); + + const response = await streamOf(daemon, grant.device.id); + if (response.body === null) throw new Error("the stream answered without a body"); + const frames = await readFrames(response.body, (read) => + read.some((frame) => frame.tag === TAG.keyframe), + ); + expect(frames.map((frame) => frame.tag)).toContain(TAG.keyframe); + + const created = await daemon.env.cli(["token", "create", "--role", "operator"]); + expect(created.code, created.stderr).toBe(0); + const callerPort = String(await freeLoopbackPort()); + const tunnel = daemon.env.cliBackground([ + "--token", + (created.json as { secret: string }).secret, + "tunnel", + "reverse", + callerPort, + "--url", + `http://127.0.0.1:${String(daemon.port)}`, + "--lease", + grant.lease.id, + ]); + expect(await tunnel.firstStdoutLine(60_000)).toBe( + `reverse device:${callerPort} -> localhost:${callerPort} (lease ${grant.lease.id})`, + ); + tunnel.kill("SIGINT"); + expect((await tunnel.waitForExit(10_000)).code).toBe(0); + + expect(await installApk(address, apk)).toBe(name); + const released = await daemon.env.cli(["release", grant.lease.id]); + expect(released.code, released.stderr).toBe(0); + await waitForDeviceState(daemon.env, address, "ready", { timeout: 3 * MINUTE }); + + const after = await userAppsOf(address); + expect(after).not.toContain(name); + for (const kept of enrolledApps) expect(after).toContain(kept); + } finally { + await uninstall(address, name).catch(() => undefined); + } + }, + ); + }, +); diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 8646e9ee1..abd5c174e 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -1,6 +1,6 @@ # Android driver -Does: emulators in an owned AVD home behind Simlock's own adb server, and USB phones on the default adb server. +Does: emulators in an owned AVD home behind Simlock's own adb server, and phones on the default adb server. Flows: [device selection](../../../docs/internal/flows/device-selection.md), [drivers](../AGENTS.md), [screen](screen/AGENTS.md), [input](input/AGENTS.md). ## Rules @@ -43,7 +43,7 @@ Boot: Physical phones: -- The 5037 server is never started, stopped or adopted on purpose. A physical `adb` command, `listAttachedPhysical`'s `devices -l` included, may start it as a side effect when nothing listens. Phones are USB transports only. +- The 5037 server is never started, stopped or adopted on purpose. A physical `adb` command, `listAttachedPhysical`'s `devices -l` included, may start it as a side effect when nothing listens. Phones are USB transports; under `android.networkDevices` (ADR 0080) a phone is told by `ro.serialno`, not its address. - Before every command `DefaultAdbServerGate.check`: the 5037 server's protocol must equal Simlock's `adb version`; nothing listening is open. A mismatch or an unreadable answer sends no command and shows as advisory `adb-protocol-mismatch`. Profiles and components: diff --git a/src/drivers/android/definition.test.ts b/src/drivers/android/definition.test.ts index 11003703c..bb5773eee 100644 --- a/src/drivers/android/definition.test.ts +++ b/src/drivers/android/definition.test.ts @@ -71,4 +71,14 @@ describe("the Android driver's keys of the android config section", () => { expect(warn).toHaveBeenCalledWith('Unknown config key: "android.emulator.launchArgs"'); expect(section.emulator).toEqual(defaults); }); + + it("take android.networkDevices true or false, default it to false, and refuse a string naming the key", async () => { + expect((await load({})).section.networkDevices).toBe(false); + expect((await load({ android: { networkDevices: true } })).section.networkDevices).toBe(true); + expect((await load({ android: { networkDevices: false } })).section.networkDevices).toBe(false); + + await expect(load({ android: { networkDevices: "yes" } })).rejects.toThrow( + 'Invalid config value for "android.networkDevices"', + ); + }); }); diff --git a/src/drivers/android/definition.ts b/src/drivers/android/definition.ts index dd0f3d17d..d6b7511df 100644 --- a/src/drivers/android/definition.ts +++ b/src/drivers/android/definition.ts @@ -26,6 +26,8 @@ export interface AndroidDriverConfig { /** why: an emulator boot may take this long, counted from its spawn, before it is given up. */ readonly bootTimeoutMs: number; readonly emulator: AndroidEmulatorLaunchOptions; + /** why: ADR 0080 §1: a worker's opt-in to enrol, list and reconnect phones its adb server reaches over the network. */ + readonly networkDevices: boolean; } export const DEFAULT_ADB_SERVER_PORT = 5038; @@ -43,6 +45,7 @@ export const androidDriverConfig: DriverConfigEntry = { defaults: { bootTimeoutMs: 300_000, emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + networkDevices: false, }, validators: { bootTimeoutMs: positiveNumber, @@ -52,5 +55,6 @@ export const androidDriverConfig: DriverConfigEntry = { audio: booleanValue, bootAnimation: booleanValue, }), + networkDevices: booleanValue, }, }; diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 928529755..769c9265f 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -238,6 +238,7 @@ export class AndroidDriver implements Driver { baseEnv: options.env, filesystem: options.filesystem, isBareShell: (args) => this.#passthroughRules.isBareShell(args), + networkDevices: options.config?.networkDevices ?? false, processRunner: options.processRunner, tcpProbe: options.tcpProbe, }); diff --git a/src/drivers/android/physical-handler-network.test.ts b/src/drivers/android/physical-handler-network.test.ts new file mode 100644 index 000000000..033d0c264 --- /dev/null +++ b/src/drivers/android/physical-handler-network.test.ts @@ -0,0 +1,423 @@ +import { describe, expect, it } from "vitest"; +import { PassthroughRefusedError } from "../../core/index.js"; +import { FakeTcpProbe, FakeTcpStreamConnector } from "../../ports/index.js"; +import { AndroidPhysicalHandler } from "./physical-handler.js"; +import { + adb, + androidFilesystem, + devicesListing, + FAILED, + TIMED_OUT, + PHONE, + passthroughOf, + rejectionOf, + restOf, + world, + isGetprop, + PhoneAdb, + sdk, + USB_LINE, + VERSION_REPLY_40, + VERSION_REPLY_41, +} from "./test-physical-handler.js"; + +const ADDRESS = "192.168.1.5:5555"; +const MDNS = "adb-R58Y61A60HN-r7wg2G._adb-tls-connect._tcp"; +const NETWORK_LINE = `${ADDRESS} device product:o1s model:SM_G991B transport_id:4`; +const MDNS_LINE = `${MDNS} device product:a16nseea model:SM_A165F transport_id:5`; + +// why: the key and the host's platform are the handler's construction options, which the driver surface cannot vary per test. +async function networkHandler( + listing: string, + options: { + readonly networkDevices?: boolean; + readonly platform?: NodeJS.Platform; + readonly reply?: string; + } = {}, +) { + const runner = new PhoneAdb([]); + runner.devicesOutput = listing; + const probe = new FakeTcpProbe([]); + probe.replyWith(options.reply ?? VERSION_REPLY_41); + const handler = new AndroidPhysicalHandler({ + adb, + baseEnv: { ANDROID_HOME: sdk }, + filesystem: await androidFilesystem(), + isBareShell: () => false, + networkDevices: options.networkDevices ?? true, + platform: options.platform ?? "linux", + processRunner: runner, + tcpProbe: probe, + }); + return { handler, runner }; +} + +// why: the physical handler is a part of a decomposed module, so its tests reach it directly. +describe("Android physical handler under android.networkDevices: inspectPhysical", () => { + it("enrols a network phone under its address with its hardware serial, and refuses an unauthorized, offline or unlisted one, one with no hardware serial, and keeps a USB phone as USB", async () => { + const enrollable = (id: string, hardwareSerial: string) => ({ + apps: ["com.example.kept", "com.example.stray", "com.example.other"], + class: "phone", + driverDeviceId: id, + enrollable: true, + hardwareSerial, + model: "SM-G991B", + osVersion: "34", + }); + const cases = [ + { + id: ADDRESS, + listing: NETWORK_LINE, + name: "host:port", + expected: enrollable(ADDRESS, "R58Y61A60HN"), + }, + { + id: MDNS, + listing: MDNS_LINE, + name: "mDNS name", + expected: enrollable(MDNS, "R58Y61A60HN"), + }, + { + expected: enrollable(ADDRESS, "R58Y61A60HN"), + id: ADDRESS, + listing: NETWORK_LINE, + name: "Windows host:port", + platform: "win32", + }, + { + expected: { enrollable: false, reason: "untrusted" }, + id: ADDRESS, + listing: `${ADDRESS} unauthorized transport_id:4`, + name: "unauthorized", + }, + { + expected: { enrollable: false, reason: "not-connected" }, + id: ADDRESS, + listing: `${ADDRESS} offline transport_id:4`, + name: "offline", + }, + { + expected: { enrollable: false, reason: "not-connected" }, + id: ADDRESS, + listing: "", + name: "not listed", + }, + { + expected: { + enrollable: false, + message: /hardware serial \(getprop ro.serialno\)/, + reason: "unreadable", + }, + id: ADDRESS, + listing: NETWORK_LINE, + name: "empty ro.serialno", + serial: "", + }, + ] as const; + for (const { expected, id, listing, name, ...rest } of cases) { + const { handler, runner } = await networkHandler( + devicesListing(...(listing === "" ? [] : [listing])), + { + platform: "platform" in rest ? rest.platform : "linux", + }, + ); + if ("serial" in rest) runner.hardwareSerial = rest.serial; + + const inspection = await handler.inspectPhysical(id); + + expect(inspection, name).toMatchObject(expected); + expect(runner.rests.flat(), name).not.toContain("connect"); + } + + const usb = await networkHandler( + devicesListing(`${ADDRESS} device usb:1-1 product:o1s model:SM_G991B transport_id:5`), + ); + const inspected = await usb.handler.inspectPhysical(ADDRESS); + expect(inspected).toMatchObject({ driverDeviceId: ADDRESS, enrollable: true }); + expect(inspected).not.toHaveProperty("hardwareSerial"); + expect(usb.runner.rests.flat()).not.toContain("ro.serialno"); + }); + + it("refuses an emulator as unsupported-kind whatever its transport, and a network phone that reports neither emulator flag is enrollable", async () => { + const cases = [ + { + id: "emulator-5554", + line: "emulator-5554 device product:sdk transport_id:1", + name: "emulator-N", + }, + { + id: "127.0.0.1:5555", + line: "127.0.0.1:5555 device transport_id:2", + name: "ro.boot.qemu", + boot: "1", + }, + { + id: "127.0.0.1:5555", + line: "127.0.0.1:5555 device transport_id:2", + name: "ro.kernel.qemu", + kernel: "1", + }, + ] as const; + for (const { id, line, name, ...flags } of cases) { + const { handler, runner } = await networkHandler(devicesListing(line)); + runner.qemuBoot = "boot" in flags ? flags.boot : "0"; + runner.qemuKernel = "kernel" in flags ? flags.kernel : "0"; + + const inspection = await handler.inspectPhysical(id); + + expect(inspection, name).toMatchObject({ enrollable: false, reason: "unsupported-kind" }); + if (id === "emulator-5554") expect(runner.rests.some(isGetprop), name).toBe(false); + } + + const phone = await networkHandler(devicesListing(NETWORK_LINE)); + expect(await phone.handler.inspectPhysical(ADDRESS)).toMatchObject({ enrollable: true }); + + const off = await networkHandler( + devicesListing("emulator-5554 device product:sdk transport_id:1"), + { networkDevices: false }, + ); + expect(await off.handler.inspectPhysical("emulator-5554")).toMatchObject({ + enrollable: false, + reason: "network-only", + }); + }); +}); + +describe("Android physical handler under android.networkDevices: listPresentPhysical", () => { + const enrolled = { driverDeviceId: ADDRESS, hardwareSerial: "R58Y61A60HN" }; + + it("reads an enrolled network phone present only when the phone answering has the recorded hardware serial", async () => { + const present = await networkHandler(devicesListing(NETWORK_LINE)); + expect(await present.handler.listPresentPhysical([enrolled])).toEqual([ + { driverDeviceId: ADDRESS, osVersion: "34", present: true }, + ]); + + const other = await networkHandler(devicesListing(NETWORK_LINE)); + other.runner.hardwareSerial = "ZZZ999"; + other.runner.calls.length = 0; + expect(await other.handler.listPresentPhysical([enrolled])).toEqual([ + { driverDeviceId: ADDRESS, present: false, reason: "not-present" }, + ]); + expect(other.runner.rests.at(-1)).toEqual(["-s", ADDRESS, "shell", "getprop", "ro.serialno"]); + + const unauthorized = await networkHandler( + devicesListing(`${ADDRESS} unauthorized transport_id:4`), + ); + expect(await unauthorized.handler.listPresentPhysical([enrolled])).toEqual([ + { driverDeviceId: ADDRESS, present: false, reason: "untrusted" }, + ]); + + for (const failure of [FAILED, TIMED_OUT]) { + const unreadable = await networkHandler(devicesListing(NETWORK_LINE)); + unreadable.runner.override((rest) => (rest.includes("ro.serialno") ? failure : undefined)); + expect(await unreadable.handler.listPresentPhysical([enrolled])).toEqual([ + { driverDeviceId: ADDRESS, present: false, reason: "not-present" }, + ]); + } + + const usb = await networkHandler(devicesListing(USB_LINE)); + expect(await usb.handler.listPresentPhysical([{ driverDeviceId: PHONE }])).toEqual([ + { driverDeviceId: PHONE, osVersion: "34", present: true }, + ]); + expect(usb.runner.rests.flat()).not.toContain("ro.serialno"); + + const off = await networkHandler(devicesListing(NETWORK_LINE), { networkDevices: false }); + expect(await off.handler.listPresentPhysical([enrolled])).toEqual([ + { driverDeviceId: ADDRESS, present: false, reason: "not-present" }, + ]); + expect(off.runner.rests.flat()).not.toContain("connect"); + }); +}); + +describe("Android physical handler under android.networkDevices: reconnecting", () => { + const other = "192.168.1.6:5555"; + const third = "192.168.1.7:5555"; + const listed = (...ids: string[]) => + devicesListing(...ids.map((id) => `${id} device product:o1s transport_id:4`)); + const record = (driverDeviceId: string) => ({ driverDeviceId, hardwareSerial: "R58Y61A60HN" }); + const connects = (runner: PhoneAdb) => runner.rests.filter((rest) => rest[0] === "connect"); + const listings = (runner: PhoneAdb) => runner.rests.filter((rest) => rest[0] === "devices"); + + // why: a connect that "succeeds" only adds the phone to the next listing, as adb's own output is ignored. + function connectAdds(runner: PhoneAdb, reachable: readonly string[], output: string) { + let inFlight = 0; + let mostInFlight = 0; + runner.override((rest) => { + if (rest[0] !== "connect") return undefined; + const address = rest[1] ?? ""; + inFlight += 1; + mostInFlight = Math.max(mostInFlight, inFlight); + return new Promise((resolve) => { + setImmediate(() => { + inFlight -= 1; + if (reachable.includes(address)) { + runner.devicesOutput += `${address} device product:o1s transport_id:9\n`; + } + resolve({ code: 0, stderr: "", stdout: output }); + }); + }); + }); + return { mostInFlight: () => mostInFlight }; + } + + it("runs one adb connect with a 10 s limit for each enrolled host:port the listing lacks, all together, then lists once more and judges by that listing alone", async () => { + const reconnected = await networkHandler(listed()); + const only = connectAdds(reconnected.runner, [ADDRESS], `connected to ${ADDRESS}\n`); + expect(await reconnected.handler.listPresentPhysical([record(ADDRESS)])).toEqual([ + { driverDeviceId: ADDRESS, osVersion: "34", present: true }, + ]); + expect(connects(reconnected.runner)).toEqual([["connect", ADDRESS]]); + expect( + reconnected.runner.commands.find((call) => restOf(call)[0] === "connect")?.options.timeoutMs, + ).toBe(10_000); + expect(listings(reconnected.runner)).toHaveLength(2); + expect(only.mostInFlight()).toBe(1); + + const failed = await networkHandler(listed()); + connectAdds(failed.runner, [], `failed to connect to '${ADDRESS}': Connection refused\n`); + expect(await failed.handler.listPresentPhysical([record(ADDRESS)])).toEqual([ + { driverDeviceId: ADDRESS, present: false, reason: "not-present" }, + ]); + + const wrongExit = await networkHandler(listed()); + connectAdds(wrongExit.runner, [ADDRESS], `failed to connect to '${ADDRESS}'\n`); + expect(await wrongExit.handler.listPresentPhysical([record(ADDRESS)])).toMatchObject([ + { present: true }, + ]); + + const many = await networkHandler(listed()); + const together = connectAdds(many.runner, [], ""); + await many.handler.listPresentPhysical([ADDRESS, other, third].map(record)); + expect(connects(many.runner)).toHaveLength(3); + expect(together.mostInFlight()).toBe(3); + expect(listings(many.runner)).toHaveLength(2); + + const timedOut = await networkHandler(listed()); + timedOut.runner.override((rest) => (rest[0] === "connect" ? TIMED_OUT : undefined)); + expect(await timedOut.handler.listPresentPhysical([record(ADDRESS)])).toEqual([ + { driverDeviceId: ADDRESS, present: false, reason: "not-present" }, + ]); + }); + + it("runs no adb connect for a listed host:port, an mDNS name, a USB ID, a key that is off or a protocol mismatch", async () => { + const cases = [ + { enrolled: [record(ADDRESS)], listing: listed(ADDRESS), name: "listed" }, + { enrolled: [record(MDNS)], listing: listed(), name: "mDNS name" }, + { enrolled: [{ driverDeviceId: PHONE }], listing: listed(), name: "USB ID" }, + { enrolled: [record(ADDRESS)], listing: listed(), name: "key off", networkDevices: false }, + { enrolled: [record(ADDRESS)], listing: listed(), name: "mismatch", reply: VERSION_REPLY_40 }, + ] as const; + for (const { enrolled, listing, name, ...options } of cases) { + const { handler, runner } = await networkHandler(listing, options); + + const present = await handler.listPresentPhysical(enrolled); + + expect(connects(runner), name).toEqual([]); + if (name === "mismatch") { + expect(present, name).toEqual([ + { driverDeviceId: ADDRESS, present: false, reason: "not-present" }, + ]); + } + } + }); +}); + +describe("Android physical handler under android.networkDevices: listAttachedPhysical", () => { + it("lists host:port and mDNS network phones in any state beside the USB phones, once each, and never an emulator; key off lists USB only", async () => { + const listing = devicesListing( + USB_LINE, + NETWORK_LINE, + `${MDNS} offline transport_id:5`, + "192.168.1.6:5555 unauthorized transport_id:6", + `${ADDRESS} device product:o1s transport_id:7`, + "emulator-5554 device product:sdk transport_id:8", + ); + + const on = await networkHandler(listing); + await expect(on.handler.listAttachedPhysical()).resolves.toEqual( + [PHONE, ADDRESS, MDNS, "192.168.1.6:5555"].sort(), + ); + + const off = await networkHandler(listing, { networkDevices: false }); + await expect(off.handler.listAttachedPhysical()).resolves.toEqual([PHONE]); + }); +}); + +describe("Android physical handler under android.networkDevices: reclaim", () => { + const device = { + address: ADDRESS, + deviceId: ADDRESS, + driverData: {}, + enrolledApps: ["com.example.kept"], + hardwareSerial: "R58Y61A60HN", + physical: true, + } as const; + const pmCommands = (runner: PhoneAdb) => runner.rests.filter((rest) => rest.includes("pm")); + + it("uninstalls only from the phone with the recorded hardware serial: another serial or an unreadable one throws before any pm command, and a USB record reads no serial", async () => { + const same = await networkHandler(devicesListing(NETWORK_LINE)); + await expect(same.handler.reclaim(device)).resolves.toMatchObject({ state: "ready" }); + expect(same.runner.rests.findIndex((rest) => rest.includes("ro.serialno"))).toBe(0); + expect(same.runner.installed).toEqual(["com.example.kept"]); + + const another = await networkHandler(devicesListing(NETWORK_LINE)); + another.runner.hardwareSerial = "ZZZ999"; + await expect(another.handler.reclaim(device)).rejects.toThrow( + `the phone at ${ADDRESS} is not the enrolled one (hardware serial ZZZ999, enrolled R58Y61A60HN)`, + ); + expect(pmCommands(another.runner)).toEqual([]); + + for (const failure of [FAILED, TIMED_OUT]) { + const unreadable = await networkHandler(devicesListing(NETWORK_LINE)); + unreadable.runner.override((rest) => (rest.includes("ro.serialno") ? failure : undefined)); + await expect(unreadable.handler.reclaim(device)).rejects.toThrow( + "physical reclaim could not read the hardware serial", + ); + expect(pmCommands(unreadable.runner)).toEqual([]); + } + + const usb = await networkHandler(devicesListing(USB_LINE)); + const { hardwareSerial: _none, ...usbRecord } = { ...device, address: PHONE, deviceId: PHONE }; + await expect(usb.handler.reclaim(usbRecord)).resolves.toMatchObject({ state: "ready" }); + expect(usb.runner.rests.flat()).not.toContain("ro.serialno"); + }); +}); + +describe("Android driver under android.networkDevices: a leased network phone", () => { + const leased = { + address: ADDRESS, + deviceId: ADDRESS, + driverData: {}, + enrolledApps: [], + hardwareSerial: "R58Y61A60HN", + physical: true, + } as const; + + it("is read from android.networkDevices by the driver, and hands its holder the address as the serial, scopes passthrough to it, still refuses transport subcommands and aims the screen at it", async () => { + const off = await world(); + off.runner.devicesOutput = devicesListing(NETWORK_LINE); + expect(await off.driver.inspectPhysical(ADDRESS)).toMatchObject({ reason: "network-only" }); + const { driver, runner } = await world({ config: { networkDevices: true } }); + runner.devicesOutput = devicesListing(NETWORK_LINE); + expect(await driver.inspectPhysical(ADDRESS)).toMatchObject({ + driverDeviceId: ADDRESS, + enrollable: true, + hardwareSerial: "R58Y61A60HN", + }); + + expect(driver.leaseEnvironment(leased)).toEqual({ + ANDROID_ADB_SERVER_PORT: "5037", + ANDROID_SERIAL: ADDRESS, + }); + expect(await passthroughOf(driver, ["shell", "getprop"], leased)).toMatchObject({ + args: ["-P", "5037", "-s", ADDRESS, "shell", "getprop"], + }); + for (const subcommand of ["connect", "disconnect", "pair", "tcpip", "usb"]) { + const error = await rejectionOf(passthroughOf(driver, [subcommand, ADDRESS], leased)); + expect(error, subcommand).toBeInstanceOf(PassthroughRefusedError); + } + + const { handler } = await networkHandler(devicesListing(NETWORK_LINE)); + expect(handler.screenTargetFor(leased, new FakeTcpStreamConnector()).serial).toBe(ADDRESS); + }); +}); diff --git a/src/drivers/android/physical-handler.ts b/src/drivers/android/physical-handler.ts index d4fe0aacf..6281cc723 100644 --- a/src/drivers/android/physical-handler.ts +++ b/src/drivers/android/physical-handler.ts @@ -24,6 +24,7 @@ export const PHYSICAL_RECLAIM_ESTIMATE_MS = 90_000; const READ_TIMEOUT_MS = 30_000; const UNINSTALL_TIMEOUT_MS = 60_000; +const CONNECT_TIMEOUT_MS = 10_000; const PORT = String(DEFAULT_ADB_PORT); const STRIPPED_ENV_KEYS = ["ANDROID_ADB_SERVER_ADDRESS", "ADB_SERVER_SOCKET", "ANDROID_SERIAL"]; @@ -50,6 +51,8 @@ const REFUSED_REBOOT_TARGETS = new Set([ "fastboot", ]); +// why: ADR 0080 §3: only a `host:port` address is connected again; an mDNS name is left to adb. +const NETWORK_ADDRESS = /^[^\s:]+:\d{1,5}$/; const USER_ID = /^\d{1,6}$/; const PACKAGE_LINE = /^package:([A-Za-z0-9_.]+)$/; @@ -57,6 +60,7 @@ interface ListedTransport { readonly serial: string; readonly state: string; readonly usb: boolean; + readonly emulator: boolean; } type Ran = @@ -66,6 +70,12 @@ type Ran = type Refusal = Extract; +const EMULATOR_REFUSAL: Refusal = { + enrollable: false, + message: "an emulator is not a phone, whatever it is connected through", + reason: "unsupported-kind", +}; + export class AndroidPhysicalHandler { readonly #gate: DefaultAdbServerGate; readonly #adb: string; @@ -73,6 +83,7 @@ export class AndroidPhysicalHandler { readonly #processRunner: ProcessRunner; readonly #isBareShell: (args: readonly string[]) => boolean; readonly #platform: NodeJS.Platform; + readonly #networkDevices: boolean; constructor( options: Omit & { @@ -81,9 +92,12 @@ export class AndroidPhysicalHandler { readonly isBareShell: (args: readonly string[]) => boolean; // why: how a USB transport is told apart depends on the host's adb; injected so Windows can be tested anywhere. readonly platform?: NodeJS.Platform; + // why: ADR 0080 §1: the worker's `android.networkDevices`, off by default. + readonly networkDevices?: boolean; }, ) { this.#platform = options.platform ?? process.platform; + this.#networkDevices = options.networkDevices ?? false; this.#isBareShell = options.isBareShell; this.#adb = options.adb; this.#processRunner = options.processRunner; @@ -153,14 +167,21 @@ export class AndroidPhysicalHandler { const listing = await this.#run(["devices", "-l"], READ_TIMEOUT_MS); if (listing.kind !== "ok") return this.#refusal(listing, "the device list (adb devices -l)"); - const unusable = unenrollable( - parseDevices(listing.stdout, this.#platform).filter((entry) => entry.serial === id), + const matching = parseDevices(listing.stdout, this.#platform).filter( + (entry) => entry.serial === id, ); + const unusable = unenrollable(matching, this.#networkDevices); if (unusable !== undefined) return unusable; - return this.#readDevice(id); + return this.#readDevice(id, !matching.some((entry) => entry.usb)); } - async #readDevice(id: string): Promise { + async #readDevice(id: string, network: boolean): Promise { + if (network) { + const emulator = await this.#refuseEmulator(id); + if (emulator !== undefined) return emulator; + } + const serial = network ? await this.#readHardwareSerial(id) : undefined; + if (serial?.kind === "refused") return serial.refusal; const model = await this.#readText(id, ["shell", "getprop", "ro.product.model"]); if (model.kind !== "ok") return this.#refusal(model.ran, "the model (getprop ro.product.model)"); @@ -180,29 +201,64 @@ export class AndroidPhysicalHandler { enrollable: true, model: model.value, osVersion: level.value, + ...(serial === undefined ? {} : { hardwareSerial: serial.value }), }; } + // why: `adb connect 127.0.0.1:` makes an emulator look like a network phone, so the emulator's own flags decide. + async #refuseEmulator(id: string): Promise { + for (const property of ["ro.boot.qemu", "ro.kernel.qemu"]) { + const ran = await this.#run(["-s", id, "shell", "getprop", property], READ_TIMEOUT_MS); + if (ran.kind !== "ok") return this.#refusal(ran, `the emulator flag (getprop ${property})`); + if (ran.stdout.trim() === "1") { + return EMULATOR_REFUSAL; + } + } + return undefined; + } + + async #hasHardwareSerial(id: string, recorded: string | undefined): Promise { + const read = await this.#readText(id, ["shell", "getprop", "ro.serialno"]); + return read.kind === "ok" && read.value === recorded; + } + + async #readHardwareSerial( + id: string, + ): Promise< + | { readonly kind: "ok"; readonly value: string } + | { readonly kind: "refused"; readonly refusal: Refusal } + > { + const serial = await this.#readText(id, ["shell", "getprop", "ro.serialno"]); + if (serial.kind !== "ok") { + return { + kind: "refused", + refusal: this.#refusal(serial.ran, "the hardware serial (getprop ro.serialno)"), + }; + } + return { kind: "ok", value: serial.value }; + } + async listPresentPhysical( enrolled: readonly EnrolledPhysical[], ): Promise { - const listing = await this.#run(["devices", "-l"], READ_TIMEOUT_MS); - const entries = listing.kind === "ok" ? parseDevices(listing.stdout, this.#platform) : []; + const entries = await this.#listWithReconnects(enrolled); const answers: PresentPhysical[] = []; - for (const { driverDeviceId } of enrolled) { - const usb = entries.filter((entry) => entry.serial === driverDeviceId && entry.usb); - if (usb.some((entry) => entry.state === "device")) { - const level = await this.#readText(driverDeviceId, [ - "shell", - "getprop", - "ro.build.version.sdk", - ]); + for (const { driverDeviceId, hardwareSerial } of enrolled) { + const network = this.#networkDevices && hardwareSerial !== undefined; + const matching = entries.filter( + (entry) => entry.serial === driverDeviceId && (entry.usb || network), + ); + if (matching.some((entry) => entry.state === "device")) { + const same = !network || (await this.#hasHardwareSerial(driverDeviceId, hardwareSerial)); + const level = same + ? await this.#readText(driverDeviceId, ["shell", "getprop", "ro.build.version.sdk"]) + : undefined; answers.push( - level.kind === "ok" + level?.kind === "ok" ? { driverDeviceId, osVersion: level.value, present: true } : { driverDeviceId, present: false, reason: "not-present" }, ); - } else if (usb.some((entry) => entry.state === "unauthorized")) { + } else if (matching.some((entry) => entry.state === "unauthorized")) { answers.push({ driverDeviceId, present: false, reason: "untrusted" }); } else { answers.push({ driverDeviceId, present: false, reason: "not-present" }); @@ -211,6 +267,31 @@ export class AndroidPhysicalHandler { return answers; } + // why: ADR 0080 §3: adb forgets a `host:port` transport when its server restarts, so every presence read connects the enrolled addresses the listing lacks, then lists again. + async #listWithReconnects( + enrolled: readonly EnrolledPhysical[], + ): Promise { + const listing = await this.#run(["devices", "-l"], READ_TIMEOUT_MS); + if (listing.kind !== "ok") return []; + const first = parseDevices(listing.stdout, this.#platform); + const missing = this.#networkDevices + ? enrolled.filter( + ({ driverDeviceId }) => + NETWORK_ADDRESS.test(driverDeviceId) && + !first.some((entry) => entry.serial === driverDeviceId), + ) + : []; + if (missing.length === 0) return first; + // why: `adb connect` exits 0 when it fails, so its result is ignored and the next listing is the outcome. + await Promise.all( + missing.map(({ driverDeviceId }) => + this.#run(["connect", driverDeviceId], CONNECT_TIMEOUT_MS), + ), + ); + const again = await this.#run(["devices", "-l"], READ_TIMEOUT_MS); + return again.kind === "ok" ? parseDevices(again.stdout, this.#platform) : []; + } + async listAttachedPhysical(): Promise { const listing = await this.#run(["devices", "-l"], READ_TIMEOUT_MS); if (listing.kind === "blocked") throw new Error(listing.answer.message); @@ -218,13 +299,23 @@ export class AndroidPhysicalHandler { throw new Error("could not read the device list (adb devices -l)"); } const serials = parseDevices(listing.stdout, this.#platform) - .filter((entry) => entry.usb) + .filter((entry) => entry.usb || (this.#networkDevices && !entry.emulator)) .map((entry) => entry.serial); return [...new Set(serials)].sort(); } async reclaim(device: PhysicalDriverDevice): Promise { const serial = device.deviceId; + if (device.hardwareSerial !== undefined) { + // why: a lease can end before the watcher sees the address change hands, so nothing is uninstalled before the phone proves it is the enrolled one (ADR 0080 §2). + const read = await this.#readText(serial, ["shell", "getprop", "ro.serialno"]); + if (read.kind !== "ok") throw failure("the hardware serial", read.ran); + if (read.value !== device.hardwareSerial) { + throw new Error( + `the phone at ${serial} is not the enrolled one (hardware serial ${read.value}, enrolled ${device.hardwareSerial})`, + ); + } + } const user = await this.#readUser(serial); if (user.kind !== "ok") throw failure("the current user id", user.ran); const before = await this.#readPackages(serial, user.value); @@ -366,7 +457,7 @@ function parseDevices(output: string, platform: NodeJS.Platform): ListedTranspor const usb = tokens.some((token) => token.startsWith("usb:")) || (platform === "win32" && !isNetworkOrEmulatorSerial(serial)); - entries.push({ serial, state, usb }); + entries.push({ emulator: /^emulator-\d+$/.test(serial), serial, state, usb }); } return entries; } @@ -380,17 +471,25 @@ function isNetworkOrEmulatorSerial(serial: string): boolean { return /:\d+$/.test(serial) || serial.includes("._tcp") || /^emulator-\d+$/.test(serial); } -function unenrollable(matching: readonly ListedTransport[]): Refusal | undefined { +function unenrollable( + matching: readonly ListedTransport[], + networkDevices: boolean, +): Refusal | undefined { const usb = matching.filter((entry) => entry.usb); if (usb.some((entry) => entry.state === "device")) return undefined; - if (usb.some((entry) => entry.state === "unauthorized")) { + const network = networkDevices ? matching.filter((entry) => !entry.usb && !entry.emulator) : []; + if (networkDevices && usb.length === 0 && matching.some((entry) => entry.emulator)) { + return EMULATOR_REFUSAL; + } + if (network.some((entry) => entry.state === "device")) return undefined; + if (usb.concat(network).some((entry) => entry.state === "unauthorized")) { return { enrollable: false, message: "USB debugging is not authorized for this host on the device", reason: "untrusted", }; } - if (usb.length === 0 && matching.length > 0) { + if (!networkDevices && usb.length === 0 && matching.length > 0) { return { enrollable: false, message: "only USB-connected devices can be enrolled", diff --git a/src/drivers/android/test-physical-handler.ts b/src/drivers/android/test-physical-handler.ts index 33dcff93d..aab98ecb0 100644 --- a/src/drivers/android/test-physical-handler.ts +++ b/src/drivers/android/test-physical-handler.ts @@ -13,6 +13,7 @@ import { type ProcessStreamOptions, type StreamingProcessHandle, } from "../../ports/index.js"; +import type { AndroidDriverConfig } from "./definition.js"; import { AndroidDriver } from "./index.js"; import { memoryAndroidSourceDatabase } from "./testing.js"; @@ -60,7 +61,9 @@ export interface Call { readonly options: ProcessRunOptions; } -export type Override = (rest: readonly string[]) => ProcessResult | "hang" | undefined; +export type Override = ( + rest: readonly string[], +) => ProcessResult | Promise | "hang" | undefined; export const OK = (stdout = ""): ProcessResult => ({ code: 0, stderr: "", stdout }); @@ -80,6 +83,9 @@ export class PhoneAdb implements ProcessRunner { packagesOutput: string | undefined; model = "SM-G991B"; sdkLevel = "34"; + hardwareSerial = "R58Y61A60HN"; + qemuBoot = ""; + qemuKernel = "0"; onCall: ((rest: readonly string[]) => void) | undefined; readonly #overrides: Override[] = []; @@ -132,6 +138,9 @@ export class PhoneAdb implements ProcessRunner { ["shell am get-current-user", this.userOutput], ["shell getprop ro.build.version.sdk", `${this.sdkLevel}\n`], ["shell getprop ro.product.model", `${this.model}\n`], + ["shell getprop ro.serialno", `${this.hardwareSerial}\n`], + ["shell getprop ro.boot.qemu", `${this.qemuBoot}\n`], + ["shell getprop ro.kernel.qemu", `${this.qemuKernel}\n`], ]); const answered = fixed.get(body); if (answered !== undefined) return OK(answered); @@ -204,6 +213,7 @@ export async function world( readonly processRunner?: (phone: PhoneAdb) => ProcessRunner; readonly serverReply?: string; readonly listeners?: FakeTcpListenerFactory; + readonly config?: Partial; } = {}, ): Promise { const log: string[] = []; @@ -220,6 +230,7 @@ export async function world( clock: new FakeClock(), database: await memoryAndroidSourceDatabase(), driverConfig: {}, + ...(options.config === undefined ? {} : { config: options.config }), env: { ANDROID_HOME: sdk, ...options.env }, filesystem, homeDirectory: home, diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index ad79a6fba..7e10a9049 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -210,6 +210,7 @@ The warm pool never downloads. A gateway never asks a worker to download for a l | `android.defaultModels.` | model name, or non-empty list | not set | The same for Android models. | Worker | | `android.defaultImageTag` | image tag: 1 to 64 letters, digits, `_`, `.` or `-` | not set | Image tag for an Android request that names none, such as `google_apis_playstore`. The worker tries an image of that tag built for its own CPU first, never downloading, and falls back to what the request gets without the setting when none fits. See [Choose the system image](/simlock/docs/using-devices/choosing-a-device#choose-the-system-image-android). | Worker | | `android.bootTimeoutMs` | positive number | `300000` (5 min) | Boot deadline for an Android emulator, counted from its start. A new seed boots twice, each within this time. Waiting for an emulator to exit stays at 3 minutes. | Worker | +| `android.networkDevices` | boolean | `false` | `true` lets `simlock device add --platform android` enrol a phone the worker's adb server reaches over the network (`host:port` or a wireless-debugging name), and makes the worker run `adb connect` for an enrolled `host:port` phone adb no longer lists. With `devices.autoEnroll` on too, every network phone connected on the worker is enrolled. See [Android phones reached over the network](/simlock/docs/worker/enrolling-physical-devices#android-phones-reached-over-the-network). | Worker | | `android.emulator.headless` | boolean | `false` | Start emulators without a window. Needed on a machine with no display. | Worker | | `android.emulator.gpu` | non-empty string | `auto` | Emulator GPU mode, such as `host` or `swiftshader_indirect`. `auto` leaves the emulator's own choice. A mode the emulator rejects fails the next boot, not the config load. | Worker | | `ios.simulator.audio` | boolean | `true` | `false` sets each simulator's volume to 0 after every boot; apps still play, unheard. A Mac still counts audio as playing while an app plays. On a busy Mac the volume can take up to 2 minutes after boot to reach 0. | Worker | diff --git a/website/src/content/docs/docs/using-devices/physical-devices.mdx b/website/src/content/docs/docs/using-devices/physical-devices.mdx index 1f8af5040..4bb01ac24 100644 --- a/website/src/content/docs/docs/using-devices/physical-devices.mdx +++ b/website/src/content/docs/docs/using-devices/physical-devices.mdx @@ -18,7 +18,7 @@ When a physical lease ends, Simlock uninstalls every app that wasn't on the devi ## Before you start - **The device is enrolled.** An admin enrols it on the worker it is plugged into, or the worker does it for every plugged-in phone when its admin turned on `devices.autoEnroll`. Simlock never leases a device that isn't enrolled. See [Enrolling physical devices](/simlock/docs/worker/enrolling-physical-devices). -- **The device is ready to use.** It is plugged in by USB, trusted, and usable when the lease is granted. A device that isn't is skipped, and your request waits for it. +- **The device is ready to use.** It is plugged in by USB (an Android phone may instead be reached over the network when the worker sets `android.networkDevices`, and then its ID, and `ANDROID_SERIAL` in the grant, is its address), trusted, and usable when the lease is granted. A device that isn't is skipped, and your request waits for it. - **An iPhone or iPad is unlocked.** One that asks for its passcode counts as not there. ## See which devices are enrolled diff --git a/website/src/content/docs/docs/worker/enrolling-physical-devices.mdx b/website/src/content/docs/docs/worker/enrolling-physical-devices.mdx index 2958641df..7d87055e7 100644 --- a/website/src/content/docs/docs/worker/enrolling-physical-devices.mdx +++ b/website/src/content/docs/docs/worker/enrolling-physical-devices.mdx @@ -25,7 +25,7 @@ Enrol on the machine the device is plugged into, from the user account that runs - The Android SDK with `platform-tools` (see [Requirements](/simlock/docs/introduction/requirements)). -- Connected by USB, with USB debugging turned on and authorized for this machine. +- Connected by USB, with USB debugging turned on and authorized for this machine. To enrol a phone that adb reaches over the network instead, see [Phones reached over the network](#android-phones-reached-over-the-network). - The adb that is running (the one Android Studio and plain `adb` use) must be the same version as the `adb` in the SDK's `platform-tools`. `simlock doctor` reports `adb-protocol-mismatch` when it is not. See [No Android phone is seen](#no-android-phone-is-seen). - Simlock cannot tell when an Android phone is locked, so a locked phone is still leased. Keep it unlocked, or turn on **Stay awake** in the developer options. @@ -90,6 +90,34 @@ Add `--json` for the full result: {"id":"dev_5b0e7c21-9d4a-4f3e-8a16-c2e47f09d3b8","driverDeviceId":"00008110-001A2B3C4D5E","platform":"ios","model":"iPhone 15 Pro","osVersion":"18.4","class":"phone","appCount":12,"reenrolled":false} ``` +## Android phones reached over the network + +A phone with no USB path to the worker (wired by Ethernet, or on Wi-Fi) can be enrolled when the worker's adb server reaches it. Set `android.networkDevices` to `true` in the worker's `config.json` and restart the daemon: + +```json +{ "android": { "networkDevices": true } } +``` + +Then connect the phone yourself, once, and enrol it by the name adb lists it under: + +```bash +adb connect 192.168.1.5:5555 +simlock device add --platform android 192.168.1.5:5555 +``` + +A phone paired with Android 11 wireless debugging is listed under a name like `adb-R58Y61A60HN-r7wg2G._adb-tls-connect._tcp`; enrol it by that name. Simlock never runs `adb pair` and never handles a pairing code. + +- **The address is the ID.** The enrolled ID is the name adb lists the phone under. Simlock also keeps the phone's own hardware serial (`getprop ro.serialno`) and reads it before it grants the phone or cleans it up. A different phone answering at the address (DHCP gave it away) reads `absent (not-present)`, is never granted, and loses no app. +- **One phone, one record.** A phone whose hardware serial is already enrolled, over USB or under another address, is refused `enrolled-under-other-id`, whatever `android.networkDevices` says. +- **Simlock reconnects it.** Every `health.probeIntervalMs` the worker runs `adb connect` for each enrolled `host:port` phone adb no longer lists, for example after the adb server restarted. A phone listed by an mDNS name is reconnected by adb itself. One that does not answer delays the grants of the worker's other Android phones by up to 10 seconds. +- **Emulators are never phones.** An emulator is refused `unsupported-kind` whatever it is connected through. +- **Moving a phone.** A phone that gets a new address reads absent. Remove it with `simlock device remove` and add it at its new address. +- **Turning the key off** leaves network phones enrolled. They read `absent (not-present)` and are not reconnected. + + + ## Enrol phones automatically An admin can let the worker enrol the phones plugged into it. Set `devices.autoEnroll` to `true` in the worker's `config.json` and restart the daemon: @@ -98,7 +126,7 @@ An admin can let the worker enrol the phones plugged into it. Set `devices.autoE { "devices": { "autoEnroll": true } } ``` -From then on, every `health.probeIntervalMs` (30 seconds by default) the worker enrols each phone plugged in by USB that `simlock device add` would accept, with no command. The `device.enrolled` event of such a phone says `initiator: "auto"`. +From then on, every `health.probeIntervalMs` (30 seconds by default) the worker enrols each phone plugged in by USB that `simlock device add` would accept, with no command. With `android.networkDevices` on too, it also enrols the network phones adb lists; run `adb connect` once for each. The `device.enrolled` event of such a phone says `initiator: "auto"`.