From d38b30253a034825c718d93af7fe87e8667785f3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:05:52 +0100 Subject: [PATCH 01/16] test: device add refuses a phone whose hardware serial another live record holds (#1604) --- src/contract/errors.ts | 1 + src/contract/protocol.ts | 2 +- src/core/driver.ts | 2 ++ src/core/fake-driver.ts | 2 ++ src/core/physical-enrollment.test.ts | 22 ++++++++++++++++++++++ src/core/physical-enrollment.ts | 5 ++++- src/core/registry-types.ts | 1 + 7 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/contract/errors.ts b/src/contract/errors.ts index 34f11b32d..a672223e6 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -11,6 +11,7 @@ const DEVICE_NOT_ENROLLABLE_REASONS = [ "unreadable", "virtual-device", "enrolled-on-other-platform", + "enrolled-under-other-id", ] as const; export type DeviceNotEnrollableReason = (typeof DEVICE_NOT_ENROLLABLE_REASONS)[number]; diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 122f75e9e..c55b0857a 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 89, max: 91 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 89, max: 92 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/core/driver.ts b/src/core/driver.ts index 7700b3a34..882330267 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -228,6 +228,8 @@ export type PhysicalInspection = readonly osVersion: string; readonly class: PhysicalClass; readonly apps: readonly string[]; + /** why: a network phone's `ro.serialno`, so one phone keeps one record whatever address it is reached at (ADR 0079 §2); absent for USB phones. */ + readonly hardwareSerial?: string; } | { readonly enrollable: false; diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 5ad756778..1009b7250 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -77,6 +77,7 @@ export interface FakePhysicalDevice { readonly osVersion?: string; readonly class?: PhysicalClass; readonly apps?: readonly string[]; + readonly hardwareSerial?: string; readonly refusal?: { readonly reason: DriverRefusalReason; readonly message: string }; } @@ -898,6 +899,7 @@ function readPhysical(device: FakePhysicalDevice, id: string): PhysicalInspectio enrollable: true, model: device.model ?? "Fake Phone", osVersion: device.osVersion ?? "1.0", + ...(device.hardwareSerial === undefined ? {} : { hardwareSerial: device.hardwareSerial }), }; } diff --git a/src/core/physical-enrollment.test.ts b/src/core/physical-enrollment.test.ts index f561cdf18..8a00681fe 100644 --- a/src/core/physical-enrollment.test.ts +++ b/src/core/physical-enrollment.test.ts @@ -597,6 +597,28 @@ describe("PhysicalEnrollment", () => { expect(physicalRecords(harness)).toHaveLength(2); }); + it("refuses a phone whose hardware serial another live record already holds, naming that record, and writes nothing", async () => { + const harness = await build([ + { ids: ["R58Y61A60HN"] }, + { hardwareSerial: "R58Y61A60HN", ids: ["192.168.1.5:5555"] }, + ]); + const control = await build([{ hardwareSerial: "R58Y61A60HN", ids: ["192.168.1.5:5555"] }]); + await control.core.enrollment.add("ios", "192.168.1.5:5555"); + expect(live(control)).toHaveLength(1); + await harness.core.enrollment.add("ios", "R58Y61A60HN"); + + const refused = harness.core.enrollment.add("ios", "192.168.1.5:5555"); + + await expect(refused).rejects.toMatchObject({ + canonicalId: "R58Y61A60HN", + message: + "this phone (hardware serial R58Y61A60HN) is enrolled as R58Y61A60HN; remove that record first", + name: "DeviceNotEnrollableError", + reason: "enrolled-under-other-id", + }); + expect(live(harness).map((device) => device.driverDeviceId)).toEqual(["R58Y61A60HN"]); + }); + it("names the device in its error when the second read names another device or a read fails", async () => { const harness = await build(); await harness.core.enrollment.add("ios", UDID); diff --git a/src/core/physical-enrollment.ts b/src/core/physical-enrollment.ts index 21ae3a440..ab0171570 100644 --- a/src/core/physical-enrollment.ts +++ b/src/core/physical-enrollment.ts @@ -4,7 +4,10 @@ import type { Driver, DriverRefusalReason } from "./driver.js"; import type { PhysicalEnrollmentInput, RegistrySnapshot } from "./registry.js"; import type { SerializedDecision } from "./serialized-decision.js"; -export type DeviceNotEnrollableReason = DriverRefusalReason | "enrolled-on-other-platform"; +export type DeviceNotEnrollableReason = + | DriverRefusalReason + | "enrolled-on-other-platform" + | "enrolled-under-other-id"; export class DeviceNotEnrollableError extends Error { constructor( diff --git a/src/core/registry-types.ts b/src/core/registry-types.ts index 2692d3661..18bcc2074 100644 --- a/src/core/registry-types.ts +++ b/src/core/registry-types.ts @@ -72,6 +72,7 @@ export interface PhysicalEnrollmentInput { readonly osVersion: string; readonly class: PhysicalClass; readonly apps: readonly string[]; + readonly hardwareSerial?: string; /** why: who enrolled the phone, for `device.enrolled`; an operator's `device add` unless the worker's auto-enroller says otherwise. */ readonly initiator?: "operator" | "auto"; } From 2d5dc311a2278b4f202929c2b3c10d3ef0e14b0f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:06:08 +0100 Subject: [PATCH 02/16] feat(core): device add refuses a phone whose hardware serial another record holds (#1604) --- src/core/physical-enrollment.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/core/physical-enrollment.ts b/src/core/physical-enrollment.ts index ab0171570..2ea37b720 100644 --- a/src/core/physical-enrollment.ts +++ b/src/core/physical-enrollment.ts @@ -102,6 +102,7 @@ export class PhysicalEnrollment { return "skipped" as const; } if (existing === undefined) { + this.#requireOneRecord(platform, id, read); return { created: await this.options.registry.enrollPhysical({ ...read, initiator, platform }), }; @@ -199,9 +200,36 @@ export class PhysicalEnrollment { driverDeviceId: inspection.driverDeviceId, model: inspection.model, osVersion: inspection.osVersion, + ...(inspection.hardwareSerial === undefined + ? {} + : { hardwareSerial: inspection.hardwareSerial }), }; } + /** why: one phone keeps one record whatever address it is reached at; this runs under the lock at each commit, never on a stale read (ADR 0079 §2). */ + #requireOneRecord( + platform: Platform, + id: string, + read: Omit, + ): void { + const { hardwareSerial } = read; + const holder = this.options.registry.snapshot.devices.find( + (device): device is PhysicalDevice => + device.physical && + device.state !== "deleted" && + device.driverDeviceId !== read.driverDeviceId && + device.driverDeviceId === hardwareSerial, + ); + if (holder === undefined || hardwareSerial === undefined) return; + throw new DeviceNotEnrollableError( + platform, + id, + "enrolled-under-other-id", + `this phone (hardware serial ${hardwareSerial}) is enrolled as ${holder.driverDeviceId}; remove that record first`, + holder.driverDeviceId, + ); + } + #recordIds(driverDeviceId: string): Set { return new Set( this.options.registry.snapshot.devices From e9ebb64fe56aabed3d788f3cc61a611d44639de9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:06:59 +0100 Subject: [PATCH 03/16] test: a physical record's hardware serial survives a reload (#1604) --- src/core/domain.ts | 2 ++ src/core/registry-physical.test.ts | 13 +++++++++++++ src/core/test-registry.ts | 5 ++++- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/core/domain.ts b/src/core/domain.ts index c4e4ce72f..93d91479b 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -365,6 +365,8 @@ export interface PhysicalDevice extends DeviceRecordFields { readonly spec: PhysicalSpec; readonly state: PhysicalState; readonly enrolledApps: readonly string[]; + /** why: a network phone's `ro.serialno`, kept so every presence read can check the address still reaches that phone (ADR 0079 §2); absent for a USB phone. */ + readonly hardwareSerial?: string; readonly reclaimingSince?: number; readonly absentReason?: AbsentReason; readonly mode?: undefined; diff --git a/src/core/registry-physical.test.ts b/src/core/registry-physical.test.ts index df0ba4ac2..f76851f58 100644 --- a/src/core/registry-physical.test.ts +++ b/src/core/registry-physical.test.ts @@ -32,6 +32,19 @@ describe("Registry: physical devices (ADR 0022 §1)", () => { ]); }); + it("keeps a physical record's hardware serial through a reload, and none for a record enrolled without", async () => { + const { enroll, reload } = await seededWorld(); + await enroll("network", { driverDeviceId: "192.168.1.5:5555", hardwareSerial: "R58Y61A60HN" }); + await enroll("usb"); + + const devices = (await reload()).snapshot.devices; + + expect(devices.map((device) => [device.id, device.physical && device.hardwareSerial])).toEqual([ + ["dev_network", "R58Y61A60HN"], + ["dev_usb", undefined], + ]); + }); + it.each(["ready", "leased", "reclaiming", "quarantined", "deleted"] as const)( "reloads a physical record in the %s state", async (target) => { diff --git a/src/core/test-registry.ts b/src/core/test-registry.ts index c120bede3..2a4dbd121 100644 --- a/src/core/test-registry.ts +++ b/src/core/test-registry.ts @@ -43,7 +43,10 @@ export async function seededWorld() { idGenerator: { generate: () => "unexpected" }, state, }); - const enroll = (name: string, overrides: Partial = {}) => { + const enroll = ( + name: string, + overrides: Partial & { hardwareSerial?: string } = {}, + ) => { names.push(name); return registry.enrollPhysical({ ...physicalInput, ...overrides }); }; From 24d0bb147ab49785c6e334d74ed1a5547c8fa654 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:07:07 +0100 Subject: [PATCH 04/16] feat(registry): a physical record keeps its hardware serial across a restart (#1604) --- src/core/registry-rows.ts | 3 +++ src/core/registry-schema.ts | 16 ++++++++++++++-- src/core/registry.ts | 1 + 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/core/registry-rows.ts b/src/core/registry-rows.ts index d843e985d..c60b5982e 100644 --- a/src/core/registry-rows.ts +++ b/src/core/registry-rows.ts @@ -172,6 +172,7 @@ const DEVICE_COLUMNS = [ "baseline_name", "baseline_version", "except_categories", + "hardware_serial", ] as const; const LEASE_COLUMNS = [ @@ -278,6 +279,7 @@ function deviceValues(device: DeviceRecord): SqliteValue[] { ...physicalColumns(device), ...baselineColumns(device), device.except === undefined ? null : device.except.join(","), + device.physical ? (device.hardwareSerial ?? null) : null, ]; } @@ -513,6 +515,7 @@ function deviceFromRow( driverData: {}, enrolledApps: appsByDevice.get(id) ?? [], physical: true, + ...present("hardwareSerial", reader.optText("hardware_serial")), ...present("reclaimingSince", reader.optInt("reclaiming_since")), ...present("absentReason", reader.optOneOf("absent_reason", ABSENT_REASONS)), spec: { diff --git a/src/core/registry-schema.ts b/src/core/registry-schema.ts index 725b4ff5b..c989dbddb 100644 --- a/src/core/registry-schema.ts +++ b/src/core/registry-schema.ts @@ -140,8 +140,20 @@ CREATE TABLE ended_lease_ids ( ) STRICT; `; +const REGISTRY_V7 = ` +ALTER TABLE devices ADD COLUMN hardware_serial TEXT; +`; + export const registryOwner: SqliteSchemaOwner = { - migrations: [REGISTRY_V1, REGISTRY_V2, REGISTRY_V3, REGISTRY_V4, REGISTRY_V5, REGISTRY_V6], + migrations: [ + REGISTRY_V1, + REGISTRY_V2, + REGISTRY_V3, + REGISTRY_V4, + REGISTRY_V5, + REGISTRY_V6, + REGISTRY_V7, + ], name: "registry", - version: 6, + version: 7, }; diff --git a/src/core/registry.ts b/src/core/registry.ts index cb8e21f7e..2985550eb 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -575,6 +575,7 @@ export class Registry implements LeaseRequestStore { driverData: {}, driverDeviceId: input.driverDeviceId, enrolledApps: [...input.apps], + ...(input.hardwareSerial === undefined ? {} : { hardwareSerial: input.hardwareSerial }), id: `dev_${this.options.idGenerator.generate()}`, physical: true, readyAt: now, From 5832889d3d6afef444fa14896a85d7fb3108bd2f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:07:27 +0100 Subject: [PATCH 05/16] test: a v6 state.db migrates and then stores a hardware serial (#1604) --- src/core/registry.test.ts | 64 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index 31c24ee99..864bf97a0 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -193,6 +193,70 @@ describe("Registry", () => { } }); + it("a state.db at registry version 6 migrates to 7, loads its physical rows with no hardware serial, and then stores one", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-registry-")); + try { + const clock = new FakeClock(1_000); + const deviceData = new Map([ + ["android", fakeDeviceDataTable], + ["ios", fakeDeviceDataTable], + ]); + const openState = (owner: typeof registryOwner) => + openStateDatabase({ + dataDirectory: directory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [owner, fakeDeviceDataTable], + sqlite: new NodeSqliteOpener(), + upgradeStep: "remove it.", + }); + const loadRegistry = (state: StateDatabase) => + Registry.load({ + clock, + deviceData, + eventBus: new EventBus(clock), + idGenerator: { generate: () => "new" }, + state, + }); + const old = await openState({ + ...registryOwner, + migrations: registryOwner.migrations.slice(0, 6), + version: 6, + }); + old.database + .prepare( + "INSERT INTO devices (id, platform, physical, driver_device_id, state, model, os_version, class, created_at) VALUES ('dev_old', 'android', 1, 'R58Y61A60HN', 'ready', 'Pixel 8', '15', 'phone', 5)", + ) + .run(); + old.close(); + + const migrated = await openState(registryOwner); + const registry = await loadRegistry(migrated); + expect(registry.snapshot.devices.map((device) => [device.id, device.physical])).toEqual([ + ["dev_old", true], + ]); + expect(registry.snapshot.devices[0]).not.toHaveProperty("hardwareSerial"); + await registry.enrollPhysical({ + apps: [], + class: "phone", + driverDeviceId: "192.168.1.5:5555", + hardwareSerial: "R58Y61A60HN2", + model: "Pixel 8", + osVersion: "15", + platform: "android", + }); + migrated.close(); + + const reopened = await loadRegistry(await openState(registryOwner)); + expect( + reopened.snapshot.devices.map((device) => device.physical && device.hardwareSerial), + ).toEqual([undefined, "R58Y61A60HN2"]); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); + it("a registry restarted on the same state.db returns every record as committed, optional fields set and absent", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-registry-")); try { From f00c65de6e973ec75217f1e7ee7749b0bcc028ea Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:08:29 +0100 Subject: [PATCH 06/16] test: every presence read passes each record's driverDeviceId and hardwareSerial (#1604) --- ...tine-coordinator-physical-presence.test.ts | 16 +++++++++++++++- src/core/reclaim-coordinator.test.ts | 16 ++++++++++++++++ src/leasing/physical-device-watcher.test.ts | 9 ++++++--- src/leasing/physical-leasing.test.ts | 19 ++++++++++++++++++- 4 files changed, 55 insertions(+), 5 deletions(-) diff --git a/src/core/quarantine-coordinator-physical-presence.test.ts b/src/core/quarantine-coordinator-physical-presence.test.ts index 7484efa71..4baf8a579 100644 --- a/src/core/quarantine-coordinator-physical-presence.test.ts +++ b/src/core/quarantine-coordinator-physical-presence.test.ts @@ -183,7 +183,7 @@ describe("QuarantineCoordinator retry of a physical device that is not present ( const FIRST = "00008110-001A2B3C4D5E"; const PROBE_INTERVAL_MS = 7_000; const DEVICES: readonly FakePhysicalDevice[] = [ - { apps: [], ids: [FIRST], model: "iPhone 15 Pro", osVersion: "18.4" }, + { apps: [], hardwareSerial: "SER-1", ids: [FIRST], model: "iPhone 15 Pro", osVersion: "18.4" }, ]; async function build() { @@ -311,6 +311,20 @@ describe("QuarantineCoordinator retry of a physical device that is not present ( expect(record(harness, id)).toMatchObject({ quarantineAttempts: 1, state: "quarantined" }); }); + it("a physical retry reads presence with the record's driverDeviceId and hardwareSerial", async () => { + const harness = await build(); + await enrollQuarantined(harness); + harness.driver.setPhysicalPresence(FIRST, true); + + await advance(harness, harness.config.warmPool.quarantine.retryBackoffMs); + + expect( + harness.driver.calls + .filter((call) => call.operation === "listPresentPhysical") + .map((call) => call.arguments[0]), + ).toEqual([[{ driverDeviceId: FIRST, hardwareSerial: "SER-1" }]]); + }); + it("a physical retry whose presence read rejects makes no reclaim or destroy call, keeps quarantineAttempts, and re-arms after health.probeIntervalMs", async () => { const harness = await build(); const id = await enrollQuarantined(harness); diff --git a/src/core/reclaim-coordinator.test.ts b/src/core/reclaim-coordinator.test.ts index affea493c..13048635d 100644 --- a/src/core/reclaim-coordinator.test.ts +++ b/src/core/reclaim-coordinator.test.ts @@ -512,6 +512,7 @@ describe("ReclaimCoordinator for a physical device the platform no longer lists options: { readonly driver?: FakeDriver; readonly drivers?: (driver: FakeDriver) => ReclaimDriverCatalog; + readonly hardwareSerial?: string; readonly logger?: Logger; readonly realQuarantine?: boolean; } = {}, @@ -538,6 +539,7 @@ describe("ReclaimCoordinator for a physical device the platform no longer lists apps: [], class: "phone", driverDeviceId: PHYSICAL_ID, + ...(options.hardwareSerial === undefined ? {} : { hardwareSerial: options.hardwareSerial }), model: "iPhone 15 Pro", osVersion: "18.4", platform: "ios", @@ -655,6 +657,20 @@ describe("ReclaimCoordinator for a physical device the platform no longer lists }); }); + it("a failed physical reclaim reads presence with the record's driverDeviceId and hardwareSerial", async () => { + const harness = await physicalHarness("reclaiming", { hardwareSerial: "SER-1" }); + harness.driver.setPhysicalPresence(PHYSICAL_ID, true); + harness.driver.failOn("reclaim", 1, new Error("uninstall exploded")); + + await harness.coordinator.reclaim(releasedPhysical(harness.device())); + + expect( + harness.driver.calls + .filter((call) => call.operation === "listPresentPhysical") + .map((call) => call.arguments[0]), + ).toEqual([[{ driverDeviceId: PHYSICAL_ID, hardwareSerial: "SER-1" }]]); + }); + it("a physical device's purge that fails while present after its lease is handed to quarantine as purge-failed", async () => { const harness = await physicalHarness("reclaiming"); harness.driver.setPhysicalPresence(PHYSICAL_ID, true); diff --git a/src/leasing/physical-device-watcher.test.ts b/src/leasing/physical-device-watcher.test.ts index 095002f9e..79e7c0149 100644 --- a/src/leasing/physical-device-watcher.test.ts +++ b/src/leasing/physical-device-watcher.test.ts @@ -90,7 +90,7 @@ describe("PhysicalDeviceWatcher counting", () => { expect(readsOf(harness.driver)).toHaveLength(2); }); - it("each read asks the driver only for the canonical IDs of that platform's enrolled records, deleted ones left out", async () => { + it("each read asks the driver only for the driverDeviceId, and the hardwareSerial when it has one, of that platform's enrolled records, deleted ones left out", async () => { const harness = await createHarness({ android: true }); await enrollIphone(harness, "UDID-A"); const removed = await enrollIphone(harness, "UDID-B"); @@ -99,6 +99,7 @@ describe("PhysicalDeviceWatcher counting", () => { apps: [], class: "phone", driverDeviceId: "EMU-1", + hardwareSerial: "SER-1", model: "Pixel 8", osVersion: "14", platform: "android", @@ -108,8 +109,10 @@ describe("PhysicalDeviceWatcher counting", () => { await tick(harness); - expect(readsOf(harness.driver)).toEqual([["UDID-A"]]); - expect(readsOf(harness.androidDriver)).toEqual([["EMU-1"]]); + expect(readsOf(harness.driver)).toEqual([[{ driverDeviceId: "UDID-A" }]]); + expect(readsOf(harness.androidDriver)).toEqual([ + [{ driverDeviceId: "EMU-1", hardwareSerial: "SER-1" }], + ]); }); it("a read that rejects changes neither the count nor the state of that platform's devices", async () => { diff --git a/src/leasing/physical-leasing.test.ts b/src/leasing/physical-leasing.test.ts index 458989fb2..a6b475744 100644 --- a/src/leasing/physical-leasing.test.ts +++ b/src/leasing/physical-leasing.test.ts @@ -118,11 +118,16 @@ async function createHarness( type Harness = Awaited>; -async function enrollIphone(harness: Harness, driverDeviceId: string): Promise { +async function enrollIphone( + harness: Harness, + driverDeviceId: string, + hardwareSerial?: string, +): Promise { const device = await harness.registry.enrollPhysical({ apps: [], class: "phone", driverDeviceId, + ...(hardwareSerial === undefined ? {} : { hardwareSerial }), model: "iPhone 15 Pro", osVersion: "18.4", platform: "ios", @@ -241,6 +246,18 @@ describe("createLeasing with physical devices", () => { expect(refused).toBeInstanceOf(UnknownModelError); }); + it("reads a device's presence before the grant with its driverDeviceId and hardwareSerial", async () => { + const harness = await createHarness(); + await enrollIphone(harness, "UDID-A", "SER-A"); + + const result = await outcome(harness.engine.request(physicalRequest, asking("agent"))); + + expect(result).toMatchObject({ device: { driverDeviceId: "UDID-A" } }); + expect(presenceReads(harness)).toEqual([ + [{ driverDeviceId: "UDID-A", hardwareSerial: "SER-A" }], + ]); + }); + it("counts a presence read that rejects as not present and releases the grant claim", async () => { const harness = await createHarness(); const device = await enrollIphone(harness, "UDID-A"); From 3c1ebec2d93d061a07641fee00fda9d87b73f6d1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:10:00 +0100 Subject: [PATCH 07/16] feat(core): every presence read passes each record's driverDeviceId and hardwareSerial (#1604) --- e2e/fake-driver/fake-driver.ts | 9 ++- src/core/domain.ts | 2 +- src/core/driver.ts | 10 +++- src/core/fake-driver.test.ts | 20 +++++-- src/core/fake-driver.ts | 11 ++-- src/core/index.ts | 1 + src/core/physical-enrollment.ts | 2 +- src/core/physical-presence.test.ts | 54 +++++++++++++----- src/core/physical-presence.ts | 25 +++++--- src/core/quarantine-coordinator.ts | 2 +- src/core/reclaim-coordinator.ts | 2 +- src/drivers/android/index.ts | 7 ++- .../physical-handler-inspect-list.test.ts | 21 ++++--- .../android/physical-handler-windows.test.ts | 4 +- src/drivers/android/physical-handler.test.ts | 57 +++++++++++-------- src/drivers/android/physical-handler.ts | 7 ++- src/drivers/ios/index.ts | 7 ++- .../ios/physical-files-and-limits.test.ts | 4 +- src/drivers/ios/physical-presence.test.ts | 45 +++++++++++---- src/leasing/acquisition-workflow.ts | 2 +- .../physical-device-watcher-acting.test.ts | 8 ++- src/leasing/physical-device-watcher.ts | 5 +- 22 files changed, 205 insertions(+), 100 deletions(-) diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index 712f0731f..cfa7191a4 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -28,6 +28,7 @@ import { type PassthroughCommand, type PassthroughContext, type PhysicalInspection, + type EnrolledPhysical, type PresentPhysical, uninstallPlan, PassthroughRefusedError, @@ -604,9 +605,11 @@ export class OutOfProcessFakeDriver implements Driver { }; } - async listPresentPhysical(enrolledIds: readonly string[]): Promise { - const script = await this.#beforeCall("listPresentPhysical", [enrolledIds]); - return enrolledIds.map((driverDeviceId) => { + async listPresentPhysical( + enrolled: readonly EnrolledPhysical[], + ): Promise { + const script = await this.#beforeCall("listPresentPhysical", [enrolled]); + return enrolled.map(({ driverDeviceId }) => { const scripted = script.physicalDevices?.find((candidate) => candidate.ids.includes(driverDeviceId), ); diff --git a/src/core/domain.ts b/src/core/domain.ts index 93d91479b..db39ec693 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -365,7 +365,7 @@ export interface PhysicalDevice extends DeviceRecordFields { readonly spec: PhysicalSpec; readonly state: PhysicalState; readonly enrolledApps: readonly string[]; - /** why: a network phone's `ro.serialno`, kept so every presence read can check the address still reaches that phone (ADR 0079 §2); absent for a USB phone. */ + /** why: a network phone's `ro.serialno`, kept so every presence read can check the address still reaches that phone (ADR 0080 §2); absent for a USB phone. */ readonly hardwareSerial?: string; readonly reclaimingSince?: number; readonly absentReason?: AbsentReason; diff --git a/src/core/driver.ts b/src/core/driver.ts index 882330267..63ccba5a8 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -60,6 +60,12 @@ export function isPhysicalDriverDevice(device: DriverDevice): device is Physical return (device as Partial).physical === true; } +/** why: what a presence read asks about one enrolled phone; the hardware serial lets a driver tell a phone from another one at the same network address (ADR 0080 §2). */ +export interface EnrolledPhysical { + readonly driverDeviceId: string; + readonly hardwareSerial?: string; +} + export interface PresentPhysical { readonly driverDeviceId: string; readonly present: boolean; @@ -228,7 +234,7 @@ export type PhysicalInspection = readonly osVersion: string; readonly class: PhysicalClass; readonly apps: readonly string[]; - /** why: a network phone's `ro.serialno`, so one phone keeps one record whatever address it is reached at (ADR 0079 §2); absent for USB phones. */ + /** why: a network phone's `ro.serialno`, so one phone keeps one record whatever address it is reached at (ADR 0080 §2); absent for USB phones. */ readonly hardwareSerial?: string; } | { @@ -324,7 +330,7 @@ export interface Driver { destroy(device: VirtualDriverDevice): Promise; listManaged(): Promise; inspectPhysical(id: string): Promise; - listPresentPhysical(enrolledIds: readonly string[]): Promise; + listPresentPhysical(enrolled: readonly EnrolledPhysical[]): Promise; /** why: a read made beyond enrolled IDs; canonical IDs of the phones on USB in any state, sorted, no duplicates, and a throw (never an empty list) when the platform cannot be read. */ listAttachedPhysical(): Promise; listCatalog(): Promise; diff --git a/src/core/fake-driver.test.ts b/src/core/fake-driver.test.ts index 43b5eea66..9e3bbe0fe 100644 --- a/src/core/fake-driver.test.ts +++ b/src/core/fake-driver.test.ts @@ -174,9 +174,11 @@ describe("FakeDriver", () => { driver.setPhysicalPresence("A", true); driver.holdPresenceReads("A"); let answer: readonly unknown[] | undefined; - const read = driver.listPresentPhysical(["B", "A"]).then((entries) => { - answer = entries; - }); + const read = driver + .listPresentPhysical([{ driverDeviceId: "B" }, { driverDeviceId: "A" }]) + .then((entries) => { + answer = entries; + }); await new Promise((resolve) => setTimeout(resolve, 5)); expect(answer).toBeUndefined(); @@ -196,7 +198,7 @@ describe("FakeDriver", () => { driver.releasePresenceReads(); const answer = await Promise.race([ - driver.listPresentPhysical(["A"]), + driver.listPresentPhysical([{ driverDeviceId: "A" }]), new Promise((resolve) => setTimeout(() => resolve("held"), 25)), ]); @@ -209,7 +211,13 @@ describe("FakeDriver", () => { driver.setPhysicalPresence("B", true, { osVersion: "18.5" }); driver.setPhysicalPresence("C", false); - await expect(driver.listPresentPhysical(["A", "B", "C"])).resolves.toEqual([ + await expect( + driver.listPresentPhysical([ + { driverDeviceId: "A" }, + { driverDeviceId: "B" }, + { driverDeviceId: "C" }, + ]), + ).resolves.toEqual([ { driverDeviceId: "A", present: false, reason: "locked" }, { driverDeviceId: "B", osVersion: "18.5", present: true }, { driverDeviceId: "C", present: false, reason: "not-present" }, @@ -221,7 +229,7 @@ describe("FakeDriver", () => { driver.setPhysicalPresence("A", true, { osVersion: "18.5" }); driver.setPhysicalPresence("A", true); - await expect(driver.listPresentPhysical(["A"])).resolves.toEqual([ + await expect(driver.listPresentPhysical([{ driverDeviceId: "A" }])).resolves.toEqual([ { driverDeviceId: "A", osVersion: "1.0", present: true }, ]); }); diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 1009b7250..f8a47d055 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -34,6 +34,7 @@ import { type PhysicalDriverDevice, type VirtualDriverDevice, type PhysicalInspection, + type EnrolledPhysical, type PresentPhysical, type ReclaimResult, removeListedComponent, @@ -610,14 +611,16 @@ export class FakeDriver implements Driver { this.#physicalDevices = devices; } - async listPresentPhysical(enrolledIds: readonly string[]): Promise { - await this.#beforeCall("listPresentPhysical", enrolledIds); - if (enrolledIds.some((id) => this.#heldPresenceReads.has(id))) { + async listPresentPhysical( + enrolled: readonly EnrolledPhysical[], + ): Promise { + await this.#beforeCall("listPresentPhysical", enrolled); + if (enrolled.some(({ driverDeviceId }) => this.#heldPresenceReads.has(driverDeviceId))) { await new Promise((resolve) => { this.#pendingPresenceReads.push(resolve); }); } - return enrolledIds.map((driverDeviceId) => { + return enrolled.map(({ driverDeviceId }) => { if (this.#presentPhysical.has(driverDeviceId)) { return { driverDeviceId, diff --git a/src/core/index.ts b/src/core/index.ts index 42fbe2c85..4fc30e3e6 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -98,6 +98,7 @@ export { type DriverRefusalReason, type VirtualDriverDevice, type PhysicalInspection, + type EnrolledPhysical, type PresentPhysical, toDriverDevice, uninstallPlan, diff --git a/src/core/physical-enrollment.ts b/src/core/physical-enrollment.ts index 2ea37b720..608e75513 100644 --- a/src/core/physical-enrollment.ts +++ b/src/core/physical-enrollment.ts @@ -206,7 +206,7 @@ export class PhysicalEnrollment { }; } - /** why: one phone keeps one record whatever address it is reached at; this runs under the lock at each commit, never on a stale read (ADR 0079 §2). */ + /** why: one phone keeps one record whatever address it is reached at; this runs under the lock at each commit, never on a stale read (ADR 0080 §2). */ #requireOneRecord( platform: Platform, id: string, diff --git a/src/core/physical-presence.test.ts b/src/core/physical-presence.test.ts index a8379e2a9..eaee078c8 100644 --- a/src/core/physical-presence.test.ts +++ b/src/core/physical-presence.test.ts @@ -23,7 +23,11 @@ describe("readPhysicalPresence", () => { { driverDeviceId: "B", present: false }, ]); - const presence = await readPhysicalPresence(driver, ["A", "B", "C"]); + const presence = await readPhysicalPresence(driver, [ + { driverDeviceId: "A" }, + { driverDeviceId: "B" }, + { driverDeviceId: "C" }, + ]); expect(presence.get("A")).toBe(true); expect(presence.get("B")).toBe(false); @@ -38,24 +42,30 @@ describe("readPhysicalPresence", () => { ]); return expect( - readPhysicalPresence(driver, ["A"]).then((presence) => [...presence]), + readPhysicalPresence(driver, [{ driverDeviceId: "A" }]).then((presence) => [...presence]), ).resolves.toEqual([["A", true]]); }); - it("asks the driver only for the IDs it is given", async () => { + it("asks the driver only for the entries it is given, each with its hardware serial when it has one and nothing else", async () => { const driver = driverAnswering([{ driverDeviceId: "A", present: true }]); - await readPhysicalPresence(driver, ["A", "B"]); + await readPhysicalPresence(driver, [ + { driverDeviceId: "A", hardwareSerial: "SER-A" }, + { driverDeviceId: "B" }, + ]); expect(driver.listPresentPhysical).toHaveBeenCalledTimes(1); - expect(driver.listPresentPhysical).toHaveBeenCalledWith(["A", "B"]); + expect(driver.listPresentPhysical).toHaveBeenCalledWith([ + { driverDeviceId: "A", hardwareSerial: "SER-A" }, + { driverDeviceId: "B" }, + ]); }); it("rejects when the driver rejects", async () => { const failure = new Error("usbmuxd went away"); const driver = { listPresentPhysical: vi.fn().mockRejectedValue(failure) }; - await expect(readPhysicalPresence(driver, ["A"])).rejects.toBe(failure); + await expect(readPhysicalPresence(driver, [{ driverDeviceId: "A" }])).rejects.toBe(failure); }); }); @@ -66,7 +76,10 @@ describe("readPhysicalPresenceDetail", () => { { driverDeviceId: "B", present: true }, ]); - const detail = await readPhysicalPresenceDetail(driver, ["A", "B"]); + const detail = await readPhysicalPresenceDetail(driver, [ + { driverDeviceId: "A" }, + { driverDeviceId: "B" }, + ]); expect(detail.get("A")).toStrictEqual({ osVersion: "18.5", present: true }); expect(detail.get("B")).toStrictEqual({ present: true }); @@ -78,7 +91,11 @@ describe("readPhysicalPresenceDetail", () => { { driverDeviceId: "B", present: false }, ]); - const detail = await readPhysicalPresenceDetail(driver, ["A", "B", "C"]); + const detail = await readPhysicalPresenceDetail(driver, [ + { driverDeviceId: "A" }, + { driverDeviceId: "B" }, + { driverDeviceId: "C" }, + ]); expect(detail.get("A")).toStrictEqual({ present: false, reason: "locked" }); expect(detail.get("B")).toStrictEqual({ present: false, reason: "not-present" }); @@ -94,7 +111,12 @@ describe("the latest presence read of a device", () => { { driverDeviceId: "LATEST-C", present: false }, ]); - await readPhysicalPresenceDetail(driver, ["LATEST-A", "LATEST-B", "LATEST-C", "LATEST-D"]); + await readPhysicalPresenceDetail(driver, [ + { driverDeviceId: "LATEST-A" }, + { driverDeviceId: "LATEST-B" }, + { driverDeviceId: "LATEST-C" }, + { driverDeviceId: "LATEST-D" }, + ]); expect(latestPresence("LATEST-A")).toStrictEqual({ present: true }); expect(latestPresence("LATEST-B")).toStrictEqual({ present: false, reason: "locked" }); @@ -106,26 +128,30 @@ describe("the latest presence read of a device", () => { expect(latestPresence("LATEST-E")).toBeUndefined(); await readPhysicalPresence( driverAnswering([{ driverDeviceId: "LATEST-E", present: false, reason: "untrusted" }]), - ["LATEST-E"], + [{ driverDeviceId: "LATEST-E" }], ); expect(latestPresence("LATEST-E")).toStrictEqual({ present: false, reason: "untrusted" }); const failing = { listPresentPhysical: vi.fn().mockRejectedValue(new Error("usbmuxd")) }; - await expect(readPhysicalPresence(failing, ["LATEST-E"])).rejects.toThrow("usbmuxd"); - await expect(readPhysicalPresenceDetail(failing, ["LATEST-E"])).rejects.toThrow("usbmuxd"); + await expect(readPhysicalPresence(failing, [{ driverDeviceId: "LATEST-E" }])).rejects.toThrow( + "usbmuxd", + ); + await expect( + readPhysicalPresenceDetail(failing, [{ driverDeviceId: "LATEST-E" }]), + ).rejects.toThrow("usbmuxd"); expect(latestPresence("LATEST-E")).toStrictEqual({ present: false, reason: "untrusted" }); }); it("is changed the same way by the boolean read a grant makes, with the read's reason", async () => { await readPhysicalPresence(driverAnswering([{ driverDeviceId: "LATEST-F", present: true }]), [ - "LATEST-F", + { driverDeviceId: "LATEST-F" }, ]); expect(latestPresence("LATEST-F")).toStrictEqual({ present: true }); await readPhysicalPresence( driverAnswering([{ driverDeviceId: "LATEST-F", present: false, reason: "locked" }]), - ["LATEST-F"], + [{ driverDeviceId: "LATEST-F" }], ); expect(latestPresence("LATEST-F")).toStrictEqual({ present: false, reason: "locked" }); diff --git a/src/core/physical-presence.ts b/src/core/physical-presence.ts index 20d44e9b1..49be4c01f 100644 --- a/src/core/physical-presence.ts +++ b/src/core/physical-presence.ts @@ -1,5 +1,5 @@ import type { AbsentReason } from "./domain.js"; -import type { Driver, PresentPhysical } from "./driver.js"; +import type { Driver, EnrolledPhysical, PresentPhysical } from "./driver.js"; export type PhysicalRead = | { readonly present: true; readonly osVersion?: string } @@ -24,11 +24,14 @@ function remember(answer: ReadonlyMap): void { } function reads( - ids: readonly string[], + enrolled: readonly EnrolledPhysical[], entries: readonly PresentPhysical[], ): ReadonlyMap { const answer = new Map( - ids.map((id) => [id, { present: false, reason: "not-present" }]), + enrolled.map(({ driverDeviceId }) => [ + driverDeviceId, + { present: false, reason: "not-present" }, + ]), ); for (const entry of entries) { if (!answer.has(entry.driverDeviceId)) continue; @@ -45,20 +48,28 @@ function reads( return answer; } +/** why: a caller may hand over whole records; the driver is told only the ID and the hardware serial. */ +function asked(enrolled: readonly EnrolledPhysical[]): EnrolledPhysical[] { + return enrolled.map(({ driverDeviceId, hardwareSerial }) => ({ + driverDeviceId, + ...(hardwareSerial === undefined ? {} : { hardwareSerial }), + })); +} + export async function readPhysicalPresenceDetail( driver: Pick, - ids: readonly string[], + enrolled: readonly EnrolledPhysical[], ): Promise> { - const answer = reads(ids, await driver.listPresentPhysical(ids)); + const answer = reads(enrolled, await driver.listPresentPhysical(asked(enrolled))); remember(answer); return answer; } export async function readPhysicalPresence( driver: Pick, - ids: readonly string[], + enrolled: readonly EnrolledPhysical[], ): Promise> { - const answer = reads(ids, await driver.listPresentPhysical(ids)); + const answer = reads(enrolled, await driver.listPresentPhysical(asked(enrolled))); remember(answer); return new Map([...answer].map(([id, read]) => [id, read.present])); } diff --git a/src/core/quarantine-coordinator.ts b/src/core/quarantine-coordinator.ts index b28b837b3..46ea5335f 100644 --- a/src/core/quarantine-coordinator.ts +++ b/src/core/quarantine-coordinator.ts @@ -275,7 +275,7 @@ export class QuarantineCoordinator { async #presentForRetry(device: PhysicalDevice): Promise { try { const driver = this.options.drivers.get(device.spec.platform); - const presence = await readPhysicalPresence(driver, [device.driverDeviceId]); + const presence = await readPhysicalPresence(driver, [device]); return presence.get(device.driverDeviceId) === true; } catch (error: unknown) { this.#logger.warn("quarantine presence read failed", { diff --git a/src/core/reclaim-coordinator.ts b/src/core/reclaim-coordinator.ts index 93a5dd213..ff20e39aa 100644 --- a/src/core/reclaim-coordinator.ts +++ b/src/core/reclaim-coordinator.ts @@ -401,7 +401,7 @@ export class ReclaimCoordinator { let absentReason: AbsentReason | undefined; try { const driver = this.options.drivers.get(device.spec.platform); - const reads = await readPhysicalPresenceDetail(driver, [device.driverDeviceId]); + const reads = await readPhysicalPresenceDetail(driver, [device]); const read = reads.get(device.driverDeviceId); if (read?.present !== true) absentReason = read?.reason ?? "not-present"; } catch (readError: unknown) { diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 18feb8ae0..928529755 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -25,6 +25,7 @@ import { isPhysicalDriverDevice, type PhysicalDriverDevice, type VirtualDriverDevice, + type EnrolledPhysical, type PresentPhysical, type DriverToolVersion, type InstalledComponent, @@ -703,8 +704,10 @@ export class AndroidDriver implements Driver { }); } - async listPresentPhysical(enrolledIds: readonly string[]): Promise { - return this.#physical.listPresentPhysical(enrolledIds); + async listPresentPhysical( + enrolled: readonly EnrolledPhysical[], + ): Promise { + return this.#physical.listPresentPhysical(enrolled); } async listAttachedPhysical(): Promise { diff --git a/src/drivers/android/physical-handler-inspect-list.test.ts b/src/drivers/android/physical-handler-inspect-list.test.ts index 903ebbbcb..c7f062f6c 100644 --- a/src/drivers/android/physical-handler-inspect-list.test.ts +++ b/src/drivers/android/physical-handler-inspect-list.test.ts @@ -182,7 +182,7 @@ describe("Android physical handler: inspectPhysical", () => { return undefined; }); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); }); @@ -216,11 +216,11 @@ describe("Android physical handler: listPresentPhysical", () => { ); const present = await driver.listPresentPhysical([ - PHONE, - "UNAUTH1", - "OFFLINE1", - "192.168.1.5:5555", - "MISSING1", + { driverDeviceId: PHONE }, + { driverDeviceId: "UNAUTH1" }, + { driverDeviceId: "OFFLINE1" }, + { driverDeviceId: "192.168.1.5:5555" }, + { driverDeviceId: "MISSING1" }, ]); expect(present).toEqual([ @@ -236,7 +236,7 @@ describe("Android physical handler: listPresentPhysical", () => { const { driver, runner } = await world(); runner.devicesOutput = devicesListing(USB_LINE, "OTHER99 device usb:1-2 transport_id:4"); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, osVersion: "34", present: true }]); expect(runner.rests.flat()).not.toContain("OTHER99"); @@ -251,7 +251,10 @@ describe("Android physical handler: listPresentPhysical", () => { const { driver, runner } = await world(); runner.override((rest) => (isDevicesListing(rest) ? result : undefined)); - const present = await driver.listPresentPhysical([PHONE, "SERIAL2"]); + const present = await driver.listPresentPhysical([ + { driverDeviceId: PHONE }, + { driverDeviceId: "SERIAL2" }, + ]); expect(present).toEqual([ { driverDeviceId: PHONE, present: false, reason: "not-present" }, @@ -264,7 +267,7 @@ describe("Android physical handler: listPresentPhysical", () => { const { driver, runner } = await world(); runner.override((rest) => (isGetprop(rest) ? FAILED : undefined)); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); }); diff --git a/src/drivers/android/physical-handler-windows.test.ts b/src/drivers/android/physical-handler-windows.test.ts index 9f00329fb..98b27ff26 100644 --- a/src/drivers/android/physical-handler-windows.test.ts +++ b/src/drivers/android/physical-handler-windows.test.ts @@ -59,7 +59,9 @@ describe("Android physical handler on Windows", () => { async (platform, expected) => { const handler = await windowsHandler(devicesListing(WINDOWS_LINE), platform); - await expect(handler.listPresentPhysical([PHONE])).resolves.toEqual([expected]); + await expect(handler.listPresentPhysical([{ driverDeviceId: PHONE }])).resolves.toEqual([ + expected, + ]); }, ); diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index f1b21ef9a..7cbc57157 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -124,7 +124,7 @@ describe("Android physical handler: the protocol gate", () => { const { driver, runner, probe, log } = await world(); await driver.inspectPhysical(PHONE); - await driver.listPresentPhysical([PHONE]); + await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); await driver.reclaim(PHYSICAL, { clean: "standard" }); const commandsBeforePassthrough = runner.commands.length; const sendsBeforePassthrough = defaultServerSends(probe).length; @@ -177,7 +177,7 @@ describe("Android physical handler: the protocol gate", () => { if (isDevicesListing(rest)) probe.replyWith(VERSION_REPLY_40); }; - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); expect(runner.rests.some(isGetprop)).toBe(false); @@ -228,7 +228,7 @@ describe("Android physical handler: the protocol gate", () => { const { driver, runner, probe } = await world(); await driver.inspectPhysical(PHONE); - await driver.listPresentPhysical([PHONE]); + await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); await driver.reclaim(PHYSICAL, { clean: "standard" }); const command = await passthroughOf(driver, ["shell", "getprop"]); const sendsBefore = defaultServerSends(probe).length; @@ -244,7 +244,10 @@ describe("Android physical handler: the protocol gate", () => { it("with a default server of another protocol, no physical method starts a process after adb version: every serial is not present, inspectPhysical is refused naming both protocol numbers, reclaim rejects", async () => { const { driver, runner } = await world({ serverReply: VERSION_REPLY_40 }); - const present = await driver.listPresentPhysical([PHONE, "SERIAL2"]); + const present = await driver.listPresentPhysical([ + { driverDeviceId: PHONE }, + { driverDeviceId: "SERIAL2" }, + ]); const inspection = await driver.inspectPhysical(PHONE); const failure = await rejectionOf(driver.reclaim(PHYSICAL, { clean: "standard" })); @@ -268,7 +271,7 @@ describe("Android physical handler: the protocol gate", () => { async (_name, reply) => { const { driver, runner } = await world({ serverReply: reply }); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); expect(runner.commands).toEqual([]); @@ -279,7 +282,7 @@ describe("Android physical handler: the protocol gate", () => { const { driver, runner, probe } = await world(); probe.failSendsWith(Object.assign(new Error("reset"), { code: "ECONNRESET" })); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); expect(runner.commands).toEqual([]); @@ -289,7 +292,7 @@ describe("Android physical handler: the protocol gate", () => { const { driver, runner } = await world(); runner.versionOutput = "adb: not a version\n"; - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); expect(runner.commands).toEqual([]); @@ -299,7 +302,7 @@ describe("Android physical handler: the protocol gate", () => { const { driver, runner } = await world(); runner.versionCode = 1; - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); expect(runner.commands).toEqual([]); @@ -309,7 +312,7 @@ describe("Android physical handler: the protocol gate", () => { const { driver, runner, probe } = await world(); probe.failSendsWith(econnrefused()); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, osVersion: "34", present: true }]); expect(runner.rests.some(isDevicesListing)).toBe(true); @@ -320,7 +323,7 @@ describe("Android physical handler: the protocol gate", () => { runner.versionOutput = "adb: not a version\n"; probe.failSendsWith(econnrefused()); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); expect(runner.commands).toEqual([]); @@ -363,12 +366,12 @@ describe("Android physical handler: the protocol gate", () => { it("a server that matched again after a mismatch gets commands on the next call, and nothing restarts it", async () => { const { driver, runner, probe } = await world({ serverReply: VERSION_REPLY_40 }); - expect(await driver.listPresentPhysical([PHONE])).toEqual([ + expect(await driver.listPresentPhysical([{ driverDeviceId: PHONE }])).toEqual([ { driverDeviceId: PHONE, present: false, reason: "not-present" }, ]); probe.replyWith(VERSION_REPLY_41); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(present).toEqual([{ driverDeviceId: PHONE, osVersion: "34", present: true }]); expect(runner.rests.flat()).not.toContain("kill-server"); @@ -378,8 +381,8 @@ describe("Android physical handler: the protocol gate", () => { it("Simlock's adb version runs once across several physical calls", async () => { const { driver, runner } = await world(); - await driver.listPresentPhysical([PHONE]); - await driver.listPresentPhysical([PHONE]); + await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); + await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); await driver.inspectPhysical(PHONE); expect(runner.calls.filter((call) => call.args[0] === "version")).toHaveLength(1); @@ -388,10 +391,10 @@ describe("Android physical handler: the protocol gate", () => { it("after a failed adb version, the next call runs adb version again", async () => { const { driver, runner } = await world(); runner.versionOutput = "adb: not a version\n"; - await driver.listPresentPhysical([PHONE]); + await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); runner.versionOutput = ADB_VERSION_41; - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(runner.calls.filter((call) => call.args[0] === "version")).toHaveLength(2); expect(present).toEqual([{ driverDeviceId: PHONE, osVersion: "34", present: true }]); @@ -399,11 +402,13 @@ describe("Android physical handler: the protocol gate", () => { it("after the adb binary's size changes, the next call runs adb version again and uses the new number", async () => { const { driver, runner, filesystem } = await world(); - expect(await driver.listPresentPhysical([PHONE])).toMatchObject([{ present: true }]); + expect(await driver.listPresentPhysical([{ driverDeviceId: PHONE }])).toMatchObject([ + { present: true }, + ]); runner.versionOutput = ADB_VERSION_40; await filesystem.writeFileAtomic(adb, "a much bigger binary after a platform-tools update"); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(runner.calls.filter((call) => call.args[0] === "version")).toHaveLength(2); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); @@ -422,11 +427,13 @@ describe("Android physical handler: the protocol gate", () => { }, }); const { driver, runner } = await world({ filesystem }); - expect(await driver.listPresentPhysical([PHONE])).toMatchObject([{ present: true }]); + expect(await driver.listPresentPhysical([{ driverDeviceId: PHONE }])).toMatchObject([ + { present: true }, + ]); runner.versionOutput = ADB_VERSION_40; modifiedAtMs = 2_000; - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); expect(runner.calls.filter((call) => call.args[0] === "version")).toHaveLength(2); expect(present).toEqual([{ driverDeviceId: PHONE, present: false, reason: "not-present" }]); @@ -537,7 +544,7 @@ describe("Android physical handler: scope", () => { const { driver, runner } = await world({ env: POISON }); await driver.inspectPhysical(PHONE); - await driver.listPresentPhysical([PHONE]); + await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); await driver.reclaim(PHYSICAL, { clean: "standard" }); expect(runner.commands.length).toBeGreaterThan(5); @@ -763,7 +770,7 @@ describe("Android physical handler: reclaim", () => { await held?.close().catch(() => undefined); await driver.inspectPhysical(PHONE); - await driver.listPresentPhysical([PHONE]); + await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); await driver.reclaim(PHYSICAL, { clean: "standard" }); const uninstalls = runner.commands.filter((call) => isUninstall(restOf(call))); @@ -784,7 +791,9 @@ describe("Android physical handler: independence from emulator calls", () => { const { driver, runner } = await world(); runner.override((rest) => (isDevicesListing(rest) ? "hang" : undefined)); let physicalSettled = false; - void driver.listPresentPhysical([PHONE]).then(() => (physicalSettled = true)); + void driver + .listPresentPhysical([{ driverDeviceId: PHONE }]) + .then(() => (physicalSettled = true)); const reality = await driver.listManaged(); @@ -851,7 +860,7 @@ describe("Android physical handler: independence from emulator calls", () => { ); await new Promise((resolve) => setTimeout(resolve, 20)); - const present = await driver.listPresentPhysical([PHONE]); + const present = await driver.listPresentPhysical([{ driverDeviceId: PHONE }]); const command = await passthroughOf(driver, ["shell", "getprop"]); expect(emulatorSettled).toBe(false); diff --git a/src/drivers/android/physical-handler.ts b/src/drivers/android/physical-handler.ts index 542ef91c6..d4fe0aacf 100644 --- a/src/drivers/android/physical-handler.ts +++ b/src/drivers/android/physical-handler.ts @@ -5,6 +5,7 @@ import { PassthroughRefusedError, type PhysicalDriverDevice, type PhysicalInspection, + type EnrolledPhysical, type PresentPhysical, type ReclaimResult, ScreenUnavailableError, @@ -182,11 +183,13 @@ export class AndroidPhysicalHandler { }; } - async listPresentPhysical(enrolledIds: readonly string[]): Promise { + 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 answers: PresentPhysical[] = []; - for (const driverDeviceId of enrolledIds) { + 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, [ diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 906230f9d..a10f4fa12 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -22,6 +22,7 @@ import { type ReclaimResult, type VirtualDriverDevice, isPhysicalDriverDevice, + type EnrolledPhysical, type PresentPhysical, ensureOwnedRoot, type EnsureOwnedRootOptions, @@ -456,8 +457,10 @@ export class IosSimctlDriver implements Driver { await this.#slimBoot.removeOverrides(udid); } - async listPresentPhysical(enrolledIds: readonly string[]): Promise { - return this.#physical.listPresent(enrolledIds); + async listPresentPhysical( + enrolled: readonly EnrolledPhysical[], + ): Promise { + return this.#physical.listPresent(enrolled.map((entry) => entry.driverDeviceId)); } async listAttachedPhysical(): Promise { diff --git a/src/drivers/ios/physical-files-and-limits.test.ts b/src/drivers/ios/physical-files-and-limits.test.ts index 069f67f1c..1bfbf760d 100644 --- a/src/drivers/ios/physical-files-and-limits.test.ts +++ b/src/drivers/ios/physical-files-and-limits.test.ts @@ -75,7 +75,9 @@ describe("IosSimctlDriver physical handler: files and limits", () => { .lock(UDID_A) .lock(UDID_B); - const result = await (await lab.driver()).listPresentPhysical([UDID_A, UDID_B]); + const result = await ( + await lab.driver() + ).listPresentPhysical([{ driverDeviceId: UDID_A }, { driverDeviceId: UDID_B }]); expect(result).toMatchObject([{ present: true }, { present: true }]); expect(lab.written).toHaveLength(3); diff --git a/src/drivers/ios/physical-presence.test.ts b/src/drivers/ios/physical-presence.test.ts index 713e26f7c..2fc802fd8 100644 --- a/src/drivers/ios/physical-presence.test.ts +++ b/src/drivers/ios/physical-presence.test.ts @@ -121,7 +121,7 @@ describe("IosSimctlDriver physical handler: presence", () => { it("listPresentPhysical answers a paired, wired, unlocked given iPhone present, with its OS version", async () => { const lab = new Lab().list([listed(UDID_A)]).lock(UDID_A); - const result = await (await lab.driver()).listPresentPhysical([UDID_A]); + const result = await (await lab.driver()).listPresentPhysical([{ driverDeviceId: UDID_A }]); expect(result).toEqual([{ driverDeviceId: UDID_A, osVersion: "18.4", present: true }]); }); @@ -129,7 +129,7 @@ describe("IosSimctlDriver physical handler: presence", () => { it("listPresentPhysical answers a paired, wired, unlocked given iPhone with no reality present", async () => { const lab = new Lab().list([listed(UDID_A, { reality: undefined })]).lock(UDID_A); - const result = await (await lab.driver()).listPresentPhysical([UDID_A]); + const result = await (await lab.driver()).listPresentPhysical([{ driverDeviceId: UDID_A }]); expect(result).toEqual([{ driverDeviceId: UDID_A, osVersion: "18.4", present: true }]); }); @@ -137,7 +137,7 @@ describe("IosSimctlDriver physical handler: presence", () => { it("listPresentPhysical answers a wired, paired, simulated entry not present not-present, with no lock read", async () => { const lab = new Lab().list([listed(UDID_A, { reality: "simulated" })]); - const result = await (await lab.driver()).listPresentPhysical([UDID_A]); + const result = await (await lab.driver()).listPresentPhysical([{ driverDeviceId: UDID_A }]); expect(result).toEqual([{ driverDeviceId: UDID_A, present: false, reason: "not-present" }]); expect(lab.calls()).toEqual([LIST_ARGV]); @@ -152,7 +152,14 @@ describe("IosSimctlDriver physical handler: presence", () => { ]) .lock(UDID_A, { file: LOCKED }); - const result = await (await lab.driver()).listPresentPhysical([UDID_A, UDID_B, UDID_C, UDID_D]); + const result = await ( + await lab.driver() + ).listPresentPhysical([ + { driverDeviceId: UDID_A }, + { driverDeviceId: UDID_B }, + { driverDeviceId: UDID_C }, + { driverDeviceId: UDID_D }, + ]); expect(result).toMatchObject([ { driverDeviceId: UDID_A, present: false, reason: "locked" }, @@ -166,7 +173,7 @@ describe("IosSimctlDriver physical handler: presence", () => { it("listPresentPhysical gives no entry for, and never runs a lock read for, a physical device not among the UDIDs it was given", async () => { const lab = new Lab().list([listed(UDID_A), listed(UDID_B)]).lock(UDID_A); - const result = await (await lab.driver()).listPresentPhysical([UDID_A]); + const result = await (await lab.driver()).listPresentPhysical([{ driverDeviceId: UDID_A }]); expect(result).toMatchObject([{ driverDeviceId: UDID_A, present: true }]); expect(result).toHaveLength(1); @@ -182,7 +189,9 @@ describe("IosSimctlDriver physical handler: presence", () => { ]) .lock(UDID_A); - const result = await (await lab.driver()).listPresentPhysical([UDID_A, UDID_B]); + const result = await ( + await lab.driver() + ).listPresentPhysical([{ driverDeviceId: UDID_A }, { driverDeviceId: UDID_B }]); expect(result).toMatchObject([ { driverDeviceId: UDID_A, present: true }, @@ -201,7 +210,9 @@ describe("IosSimctlDriver physical handler: presence", () => { ]) .lock(UDID_A); - const result = await (await lab.driver()).listPresentPhysical([UDID_A, UDID_B]); + const result = await ( + await lab.driver() + ).listPresentPhysical([{ driverDeviceId: UDID_A }, { driverDeviceId: UDID_B }]); expect(result).toMatchObject([ { driverDeviceId: UDID_A, osVersion: "18.4", present: true }, @@ -217,7 +228,10 @@ describe("IosSimctlDriver physical handler: presence", () => { ...failure.script(listDocument([listed(UDID_A), listed(UDID_B)])), }); const driver = await lab.driver(); - const pending = driver.listPresentPhysical([UDID_A, UDID_B]); + const pending = driver.listPresentPhysical([ + { driverDeviceId: UDID_A }, + { driverDeviceId: UDID_B }, + ]); const result = await expireAfter( lab, @@ -243,7 +257,7 @@ describe("IosSimctlDriver physical handler: presence", () => { const result = await expireAfter( lab, - driver.listPresentPhysical([UDID_A, UDID_B]), + driver.listPresentPhysical([{ driverDeviceId: UDID_A }, { driverDeviceId: UDID_B }]), 3, READ_LIMIT_MS, ); @@ -270,7 +284,9 @@ describe("IosSimctlDriver physical handler: presence", () => { .lock(UDID_A, script) .lock(UDID_B); - const result = await (await lab.driver()).listPresentPhysical([UDID_A, UDID_B]); + const result = await ( + await lab.driver() + ).listPresentPhysical([{ driverDeviceId: UDID_A }, { driverDeviceId: UDID_B }]); expect(result).toMatchObject([ { driverDeviceId: UDID_A, present: false, reason: "not-present" }, @@ -284,7 +300,10 @@ describe("IosSimctlDriver physical handler: presence", () => { .lock(UDID_A) .lock(UDID_B); const driver = await lab.driver(new LockReadsTakeTime(lab.runner, lab.clock, 25_000)); - const pending = driver.listPresentPhysical([UDID_A, UDID_B]); + const pending = driver.listPresentPhysical([ + { driverDeviceId: UDID_A }, + { driverDeviceId: UDID_B }, + ]); const state = promiseState(pending); void pending.catch(() => undefined); @@ -305,7 +324,9 @@ describe("IosSimctlDriver physical handler: presence", () => { .lock(UDID_B) .lock(UDID_A); - const result = await (await lab.driver()).listPresentPhysical([UDID_B, UDID_A]); + const result = await ( + await lab.driver() + ).listPresentPhysical([{ driverDeviceId: UDID_B }, { driverDeviceId: UDID_A }]); expect(result).toMatchObject([ { driverDeviceId: UDID_B, osVersion: "18.4", present: true }, diff --git a/src/leasing/acquisition-workflow.ts b/src/leasing/acquisition-workflow.ts index 19d1a3051..34e78a964 100644 --- a/src/leasing/acquisition-workflow.ts +++ b/src/leasing/acquisition-workflow.ts @@ -170,7 +170,7 @@ export class AcquisitionWorkflow { let present = false; try { const reads = await readPhysicalPresence(this.options.drivers.get(device.spec.platform), [ - device.driverDeviceId, + device, ]); present = reads.get(device.driverDeviceId) === true; } catch (error: unknown) { diff --git a/src/leasing/physical-device-watcher-acting.test.ts b/src/leasing/physical-device-watcher-acting.test.ts index 84d55ddfb..b5d9e19b8 100644 --- a/src/leasing/physical-device-watcher-acting.test.ts +++ b/src/leasing/physical-device-watcher-acting.test.ts @@ -105,10 +105,14 @@ describe("PhysicalDeviceWatcher acting on a device", () => { back(harness, "UDID-A"); const gate = deferred(); - vi.spyOn(harness.driver, "listPresentPhysical").mockImplementationOnce(async (ids) => { + vi.spyOn(harness.driver, "listPresentPhysical").mockImplementationOnce(async (enrolled) => { await gate.promise; return answer( - ids.map((driverDeviceId) => ({ driverDeviceId, present: false, reason: "not-present" })), + enrolled.map(({ driverDeviceId }) => ({ + driverDeviceId, + present: false, + reason: "not-present", + })), ); }); harness.clock.advance(PROBE_MS); diff --git a/src/leasing/physical-device-watcher.ts b/src/leasing/physical-device-watcher.ts index adbdc40cf..ef18b85c6 100644 --- a/src/leasing/physical-device-watcher.ts +++ b/src/leasing/physical-device-watcher.ts @@ -152,10 +152,7 @@ export class PhysicalDeviceWatcher { ): Promise | undefined> { try { const driver = this.options.drivers.get(platform); - return await readPhysicalPresenceDetail( - driver, - group.map((device) => device.driverDeviceId), - ); + return await readPhysicalPresenceDetail(driver, group); } catch (error: unknown) { this.#logger.warn("physical presence read failed", { platform, error: stableError(error) }); return undefined; From 47d9a3a96040e1cbcee3e9f5792b67dd0993a0ab Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:11:48 +0100 Subject: [PATCH 08/16] test: presence-read helpers read the IDs of the entries a driver was asked (#1604) --- src/leasing/physical-device-watcher.test.ts | 5 +++-- src/leasing/physical-leasing.test.ts | 12 ++++++++++-- src/leasing/test-physical-device-watcher.ts | 10 +++++++++- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/leasing/physical-device-watcher.test.ts b/src/leasing/physical-device-watcher.test.ts index 79e7c0149..55b2625bb 100644 --- a/src/leasing/physical-device-watcher.test.ts +++ b/src/leasing/physical-device-watcher.test.ts @@ -13,6 +13,7 @@ import { harnesses, holdNextReclaim, physicalRequest, + readEntriesOf, readsOf, recordStateWrites, startWatcher, @@ -109,8 +110,8 @@ describe("PhysicalDeviceWatcher counting", () => { await tick(harness); - expect(readsOf(harness.driver)).toEqual([[{ driverDeviceId: "UDID-A" }]]); - expect(readsOf(harness.androidDriver)).toEqual([ + expect(readEntriesOf(harness.driver)).toEqual([[{ driverDeviceId: "UDID-A" }]]); + expect(readEntriesOf(harness.androidDriver)).toEqual([ [{ driverDeviceId: "EMU-1", hardwareSerial: "SER-1" }], ]); }); diff --git a/src/leasing/physical-leasing.test.ts b/src/leasing/physical-leasing.test.ts index a6b475744..0d403c64a 100644 --- a/src/leasing/physical-leasing.test.ts +++ b/src/leasing/physical-leasing.test.ts @@ -173,12 +173,20 @@ function stateOf(harness: Harness, device: PhysicalDevice): string | undefined { return harness.registry.snapshot.devices.find((candidate) => candidate.id === device.id)?.state; } -function presenceReads(harness: Harness): unknown[] { +function presenceEntries(harness: Harness): unknown[] { return harness.driver.calls .filter((call) => call.operation === "listPresentPhysical") .map((call) => call.arguments[0]); } +function presenceReads(harness: Harness): unknown[] { + return presenceEntries(harness).map((entries) => + (entries as readonly { readonly driverDeviceId: string }[]).map( + (entry) => entry.driverDeviceId, + ), + ); +} + function claimKind(harness: Harness, device: PhysicalDevice): string | undefined { return harness.engine.core.claims.claim(device.id)?.kind; } @@ -253,7 +261,7 @@ describe("createLeasing with physical devices", () => { const result = await outcome(harness.engine.request(physicalRequest, asking("agent"))); expect(result).toMatchObject({ device: { driverDeviceId: "UDID-A" } }); - expect(presenceReads(harness)).toEqual([ + expect(presenceEntries(harness)).toEqual([ [{ driverDeviceId: "UDID-A", hardwareSerial: "SER-A" }], ]); }); diff --git a/src/leasing/test-physical-device-watcher.ts b/src/leasing/test-physical-device-watcher.ts index 475bae823..5f0370a68 100644 --- a/src/leasing/test-physical-device-watcher.ts +++ b/src/leasing/test-physical-device-watcher.ts @@ -258,12 +258,20 @@ export function eventsOf(harness: Harness, name: string) { return harness.bus.replay().filter((event) => String(event.event) === name); } -export function readsOf(driver: FakeDriver): unknown[] { +export function readEntriesOf(driver: FakeDriver): unknown[] { return driver.calls .filter((call) => call.operation === "listPresentPhysical") .map((call) => call.arguments[0]); } +export function readsOf(driver: FakeDriver): unknown[] { + return readEntriesOf(driver).map((entries) => + (entries as readonly { readonly driverDeviceId: string }[]).map( + (entry) => entry.driverDeviceId, + ), + ); +} + const heldReclaims = new WeakMap(); export function reclaimCalls(driver: FakeDriver) { From 6db716367d9a7af893dc3656d96e71a452d71c18 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:12:16 +0100 Subject: [PATCH 09/16] feat(core): a physical reclaim hands the driver the record's hardware serial (#1604) --- src/core/driver.ts | 9 ++++++++- src/core/reclaim-coordinator.test.ts | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/core/driver.ts b/src/core/driver.ts index 63ccba5a8..15e596a10 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -54,6 +54,8 @@ export type VirtualDriverDevice = DriverDevice & { readonly physical: false }; export type PhysicalDriverDevice = DriverDevice & { readonly physical: true; readonly enrolledApps: readonly string[]; + /** why: set for a network phone only, so the driver checks it still reaches that phone (ADR 0080 §2). */ + readonly hardwareSerial?: string; }; export function isPhysicalDriverDevice(device: DriverDevice): device is PhysicalDriverDevice { @@ -83,7 +85,12 @@ export function toDriverDevice(device: DeviceRecord): VirtualDriverDevice | Phys driverData: device.driverData, }; return device.physical - ? { ...base, enrolledApps: device.enrolledApps, physical: true } + ? { + ...base, + enrolledApps: device.enrolledApps, + ...(device.hardwareSerial === undefined ? {} : { hardwareSerial: device.hardwareSerial }), + physical: true, + } : { ...base, physical: false }; } diff --git a/src/core/reclaim-coordinator.test.ts b/src/core/reclaim-coordinator.test.ts index 13048635d..07ab84f7f 100644 --- a/src/core/reclaim-coordinator.test.ts +++ b/src/core/reclaim-coordinator.test.ts @@ -657,6 +657,24 @@ describe("ReclaimCoordinator for a physical device the platform no longer lists }); }); + it("a physical reclaim hands the driver the record's hardwareSerial, and none for a record without one", async () => { + const reclaimedWith = async (hardwareSerial?: string) => { + const harness = await physicalHarness( + "reclaiming", + hardwareSerial === undefined ? {} : { hardwareSerial }, + ); + harness.driver.setPhysicalPresence(PHYSICAL_ID, true); + await harness.coordinator.reclaim(releasedPhysical(harness.device())); + return harness.driver.calls.find((call) => call.operation === "reclaim")?.arguments[0]; + }; + + expect(await reclaimedWith("SER-1")).toMatchObject({ + deviceId: PHYSICAL_ID, + hardwareSerial: "SER-1", + }); + expect(await reclaimedWith()).not.toHaveProperty("hardwareSerial"); + }); + it("a failed physical reclaim reads presence with the record's driverDeviceId and hardwareSerial", async () => { const harness = await physicalHarness("reclaiming", { hardwareSerial: "SER-1" }); harness.driver.setPhysicalPresence(PHYSICAL_ID, true); From 195dafaa26028db6333dc8b09fe7877dbc3c9809 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:12:42 +0100 Subject: [PATCH 10/16] test: device add refuses a phone another live record's hardware serial or ID matches, over either transport (#1604) --- src/core/physical-enrollment.test.ts | 49 +++++++++++++++++----------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/src/core/physical-enrollment.test.ts b/src/core/physical-enrollment.test.ts index 8a00681fe..fc37caf60 100644 --- a/src/core/physical-enrollment.test.ts +++ b/src/core/physical-enrollment.test.ts @@ -597,26 +597,37 @@ describe("PhysicalEnrollment", () => { expect(physicalRecords(harness)).toHaveLength(2); }); - it("refuses a phone whose hardware serial another live record already holds, naming that record, and writes nothing", async () => { - const harness = await build([ - { ids: ["R58Y61A60HN"] }, - { hardwareSerial: "R58Y61A60HN", ids: ["192.168.1.5:5555"] }, - ]); - const control = await build([{ hardwareSerial: "R58Y61A60HN", ids: ["192.168.1.5:5555"] }]); - await control.core.enrollment.add("ios", "192.168.1.5:5555"); - expect(live(control)).toHaveLength(1); - await harness.core.enrollment.add("ios", "R58Y61A60HN"); - - const refused = harness.core.enrollment.add("ios", "192.168.1.5:5555"); + it("refuses a phone whose hardware serial another live record already holds, whatever either one's transport, naming that record, and writes nothing; a deleted holder refuses nothing", async () => { + const usb = { ids: ["R58Y61A60HN"] }; + const network = { hardwareSerial: "R58Y61A60HN", ids: ["192.168.1.5:5555"] }; + const otherAddress = { hardwareSerial: "R58Y61A60HN", ids: ["192.168.1.9:5555"] }; + const cases = [ + { candidate: network, holder: usb, holds: "R58Y61A60HN" }, + { candidate: otherAddress, holder: network, holds: "192.168.1.5:5555" }, + { candidate: usb, holder: network, holds: "192.168.1.5:5555" }, + ]; + + for (const { candidate, holder, holds } of cases) { + const control = await build([candidate]); + await control.core.enrollment.add("ios", candidate.ids[0] as string); + expect(live(control)).toHaveLength(1); + const harness = await build([holder, candidate]); + await harness.core.enrollment.add("ios", holder.ids[0] as string); + + const refused = harness.core.enrollment.add("ios", candidate.ids[0] as string); + + await expect(refused).rejects.toMatchObject({ + canonicalId: holds, + message: `this phone (hardware serial R58Y61A60HN) is enrolled as ${holds}; remove that record first`, + name: "DeviceNotEnrollableError", + reason: "enrolled-under-other-id", + }); + expect(live(harness).map((device) => device.driverDeviceId)).toEqual([holder.ids[0]]); - await expect(refused).rejects.toMatchObject({ - canonicalId: "R58Y61A60HN", - message: - "this phone (hardware serial R58Y61A60HN) is enrolled as R58Y61A60HN; remove that record first", - name: "DeviceNotEnrollableError", - reason: "enrolled-under-other-id", - }); - expect(live(harness).map((device) => device.driverDeviceId)).toEqual(["R58Y61A60HN"]); + await harness.core.enrollment.remove(holder.ids[0] as string); + await harness.core.enrollment.add("ios", candidate.ids[0] as string); + expect(live(harness).map((device) => device.driverDeviceId)).toEqual([candidate.ids[0]]); + } }); it("names the device in its error when the second read names another device or a read fails", async () => { From 5f4d9609fbf88457244401535b6c7306b6e68ddb Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:12:54 +0100 Subject: [PATCH 11/16] feat(core): device add refuses a phone another live record's hardware serial or ID matches (#1604) --- src/core/physical-enrollment.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/core/physical-enrollment.ts b/src/core/physical-enrollment.ts index 608e75513..9425fa256 100644 --- a/src/core/physical-enrollment.ts +++ b/src/core/physical-enrollment.ts @@ -212,20 +212,23 @@ export class PhysicalEnrollment { id: string, read: Omit, ): void { - const { hardwareSerial } = read; + const { driverDeviceId, hardwareSerial } = read; const holder = this.options.registry.snapshot.devices.find( (device): device is PhysicalDevice => device.physical && device.state !== "deleted" && - device.driverDeviceId !== read.driverDeviceId && - device.driverDeviceId === hardwareSerial, + device.driverDeviceId !== driverDeviceId && + (device.hardwareSerial === driverDeviceId || + (hardwareSerial !== undefined && + (device.driverDeviceId === hardwareSerial || + device.hardwareSerial === hardwareSerial))), ); - if (holder === undefined || hardwareSerial === undefined) return; + if (holder === undefined) return; throw new DeviceNotEnrollableError( platform, id, "enrolled-under-other-id", - `this phone (hardware serial ${hardwareSerial}) is enrolled as ${holder.driverDeviceId}; remove that record first`, + `this phone (hardware serial ${hardwareSerial ?? driverDeviceId}) is enrolled as ${holder.driverDeviceId}; remove that record first`, holder.driverDeviceId, ); } From 5b82860db833e6c4e746d891ef2b2747b447fcae Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:13:15 +0100 Subject: [PATCH 12/16] test: re-enrol takes the new read's hardware serial and a late clash is refused at either commit (#1604) --- src/core/physical-enrollment.test.ts | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/core/physical-enrollment.test.ts b/src/core/physical-enrollment.test.ts index fc37caf60..79bb8a544 100644 --- a/src/core/physical-enrollment.test.ts +++ b/src/core/physical-enrollment.test.ts @@ -630,6 +630,51 @@ describe("PhysicalEnrollment", () => { } }); + it("re-enrols with the hardware serial the new read carries, and refuses a clash that appears after an inspection, at the first commit or the second, leaving the record as it was", async () => { + const network = "192.168.1.5:5555"; + const taking = await build([{ hardwareSerial: "SER-1", ids: [network] }]); + await taking.core.enrollment.add("ios", network); + taking.driver.setPhysicalDevices([{ hardwareSerial: "SER-2", ids: [network] }]); + const again = await taking.core.enrollment.add("ios", network); + expect(again.reenrolled).toBe(true); + expect(live(taking).map((device) => device.hardwareSerial)).toEqual(["SER-2"]); + taking.driver.setPhysicalDevices([{ ids: [network] }]); + await taking.core.enrollment.add("ios", network); + expect(live(taking)[0]).not.toHaveProperty("hardwareSerial"); + + const first = await build([{ ids: ["SER-9"] }, { hardwareSerial: "SER-9", ids: [network] }]); + const held = holdInspection(first.driver, 1); + const racing = first.core.enrollment.add("ios", network); + const lost = expect(racing).rejects.toMatchObject({ + canonicalId: "SER-9", + reason: "enrolled-under-other-id", + }); + await vi.waitFor(() => expect(held.reached).toHaveBeenCalled()); + await first.core.enrollment.add("ios", "SER-9"); + held.release(); + await lost; + expect(live(first).map((device) => device.driverDeviceId)).toEqual(["SER-9"]); + + const second = await build([{ hardwareSerial: "SER-1", ids: [network] }, { ids: ["SER-9"] }]); + await second.core.enrollment.add("ios", network); + await second.core.enrollment.add("ios", "SER-9"); + const original = second.driver.inspectPhysical.bind(second.driver); + let calls = 0; + vi.spyOn(second.driver, "inspectPhysical").mockImplementation(async (id) => { + calls += 1; + const read = await original(id); + return calls === 2 && read.enrollable ? { ...read, hardwareSerial: "SER-9" } : read; + }); + const before = JSON.stringify(live(second)); + + await expect(second.core.enrollment.add("ios", network)).rejects.toMatchObject({ + canonicalId: "SER-9", + reason: "enrolled-under-other-id", + }); + + expect(JSON.stringify(live(second))).toBe(before); + }); + it("names the device in its error when the second read names another device or a read fails", async () => { const harness = await build(); await harness.core.enrollment.add("ios", UDID); From f0a8393a225cbd5e30bdd63f1387ab432cb603c5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:13:23 +0100 Subject: [PATCH 13/16] feat(core): re-enrol takes the new hardware serial and checks it at its commit (#1604) --- src/core/physical-enrollment.ts | 7 ++++--- src/core/registry.ts | 4 +++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/core/physical-enrollment.ts b/src/core/physical-enrollment.ts index 9425fa256..5a8c7566f 100644 --- a/src/core/physical-enrollment.ts +++ b/src/core/physical-enrollment.ts @@ -136,9 +136,10 @@ export class PhysicalEnrollment { `${existing.driverDeviceId} was read again as ${again.driverDeviceId}`, ); } - const device = await this.options.decisions.run(() => - this.options.registry.reenrollPhysical(existing.id, { ...again, platform }), - ); + const device = await this.options.decisions.run(() => { + this.#requireOneRecord(platform, id, again); + return this.options.registry.reenrollPhysical(existing.id, { ...again, platform }); + }); this.options.physicalDeviceReady?.(device.id); return { device, reenrolled: true }; } finally { diff --git a/src/core/registry.ts b/src/core/registry.ts index 2985550eb..45c121b49 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -617,9 +617,11 @@ export class Registry implements LeaseRequestStore { throw error; } } + const { hardwareSerial: _previousSerial, ...unserialed } = settled; const updated: PhysicalDevice = { - ...settled, + ...unserialed, enrolledApps: [...input.apps], + ...(input.hardwareSerial === undefined ? {} : { hardwareSerial: input.hardwareSerial }), readyAt: this.options.clock.now(), spec: { class: input.class, From ab3469c3a48133678881e70710245d0dbb5a5683 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:14:59 +0100 Subject: [PATCH 14/16] test: the worker auto-enrols a listed network ID and refuses one whose hardware serial is enrolled (#1604) --- e2e/fake-driver/fake-driver.ts | 1 + e2e/fake-driver/types.ts | 1 + e2e/physical-enrollment-auto-enroll.test.ts | 24 +++++++++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index cfa7191a4..6b9991862 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -649,6 +649,7 @@ export class OutOfProcessFakeDriver implements Driver { enrollable: true, model: device.model ?? "Fake Phone", osVersion: device.osVersion ?? "1.0", + ...(device.hardwareSerial === undefined ? {} : { hardwareSerial: device.hardwareSerial }), }; } diff --git a/e2e/fake-driver/types.ts b/e2e/fake-driver/types.ts index c1e8eae6b..a8a00d5b2 100644 --- a/e2e/fake-driver/types.ts +++ b/e2e/fake-driver/types.ts @@ -52,6 +52,7 @@ export interface ScriptedPhysicalDevice { readonly class?: "phone" | "tablet"; readonly apps?: readonly string[]; readonly installedApps?: readonly string[]; + readonly hardwareSerial?: string; readonly present?: boolean; readonly absentReason?: "locked" | "untrusted" | "not-present"; readonly refusal?: { readonly reason: FakeDriverRefusalReason; readonly message: string }; diff --git a/e2e/physical-enrollment-auto-enroll.test.ts b/e2e/physical-enrollment-auto-enroll.test.ts index c139013e3..100aac61a 100644 --- a/e2e/physical-enrollment-auto-enroll.test.ts +++ b/e2e/physical-enrollment-auto-enroll.test.ts @@ -270,6 +270,30 @@ describe("devices.autoEnroll", () => { ).toEqual(["operator"]); }); + it("enrols a listed network ID with no record as auto, and refuses one whose hardware serial is already enrolled as enrolled-under-other-id, logged once, with no event", async () => { + const network = (address: string): ScriptedPhysicalDevice => ({ + ...PIXEL, + hardwareSerial: "R58M123ABC", + ids: [address], + }); + const env = await autoDaemon({ android: { physicalDevices: [network("192.168.1.5:5555")] } }); + await waitFor(async () => (await named(env, "device.enrolled")).length === 1, { + label: "the network phone is enrolled", + }); + + await plug(env, "android", [network("192.168.1.5:5555"), network("192.168.1.9:5555")]); + await waitFor(async () => (await autoEnrollLog(env)).length === 1, { label: "the refusal" }); + await observeFor(700, async () => { + expect(await autoEnrollLog(env), "several runs at one reason write one line").toEqual([ + "auto-enroll: android 192.168.1.9:5555 not enrolled: this phone (hardware serial R58M123ABC) is enrolled as 192.168.1.5:5555; remove that record first", + ]); + }); + + expect((await named(env, "device.enrolled")).map((entry) => entry.payload)).toEqual([ + expect.objectContaining({ driverDeviceId: "192.168.1.5:5555", initiator: "auto" }), + ]); + }); + it("forgets which phones are held out when the daemon restarts, so a removed phone still plugged in is enrolled on the first run", async () => { const env = await autoDaemon({ ios: { physicalDevices: [IPHONE] } }); await waitFor(async () => (await named(env, "device.enrolled")).length === 1, { From aa3a036759fd0a95285e96f270f6c78da985cd3d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:16:07 +0100 Subject: [PATCH 15/16] docs(website): the error and reasons tables list enrolled-under-other-id; test: device add answers it over the CLI and HTTP (#1604) --- e2e/physical-enrollment.test.ts | 27 +++++++++++++++++++ src/core/driver.test.ts | 9 ++++++- .../content/docs/docs/reference/errors.mdx | 2 +- .../worker/enrolling-physical-devices.mdx | 1 + 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/e2e/physical-enrollment.test.ts b/e2e/physical-enrollment.test.ts index 2725ae9c9..40ddebb69 100644 --- a/e2e/physical-enrollment.test.ts +++ b/e2e/physical-enrollment.test.ts @@ -269,6 +269,33 @@ describe("simlock device add", () => { }); }); + it("of a phone whose hardware serial another record holds answers enrolled-under-other-id with the message and the canonicalId that record holds, over the CLI and HTTP, and writes no second record", async () => { + const network = "192.168.1.5:5555"; + const daemon = await httpDaemon({ + android: { + physicalDevices: [PIXEL, { ...PIXEL, hardwareSerial: PIXEL.ids[0], ids: [network] }], + }, + }); + const enrolled = await add(daemon.env, "android", PIXEL.ids[0] as string); + const message = `this phone (hardware serial ${PIXEL.ids[0]}) is enrolled as ${PIXEL.ids[0]}; remove that record first`; + + const result = await daemon.env.cli(["device", "add", "--platform", "android", network]); + const http = await postDevice(daemon, { id: network, platform: "android" }); + + expect(result.code, result.stderr).toBe(12); + expect(result.error).toEqual({ code: "DEVICE_NOT_ENROLLABLE", message }); + expect(http.status).toBe(422); + expect(http.body.error).toEqual({ + canonicalId: PIXEL.ids[0], + code: "DEVICE_NOT_ENROLLABLE", + id: network, + message, + platform: "android", + reason: "enrolled-under-other-id", + }); + expect((await rows(daemon.env)).map((row) => row.id)).toEqual([enrolled.id]); + }); + it("without --platform exits 2 with USAGE and the driver log has no inspectPhysical call", async () => { const env = await startDaemon({ ios: { physicalDevices: [IPHONE] } }); await env.driverLog.clear(); diff --git a/src/core/driver.test.ts b/src/core/driver.test.ts index 93307be52..3b6033677 100644 --- a/src/core/driver.test.ts +++ b/src/core/driver.test.ts @@ -215,10 +215,17 @@ describe("PhysicalInspection (ADR 0022 §5)", () => { // @ts-expect-error only the core can know a device is enrolled on the other platform reason: "enrolled-on-other-platform", }; + const otherId: PhysicalInspection = { + enrollable: false, + message: "enrolled as another ID", + // @ts-expect-error only the core can know a phone is enrolled under another ID + reason: "enrolled-under-other-id", + }; void otherPlatform; + void otherId; } - it("lets a driver refuse with every reason but enrolled-on-other-platform", () => { + it("lets a driver refuse with every reason but enrolled-on-other-platform and enrolled-under-other-id", () => { const reasons: Record = { "developer-mode-off": true, locked: true, diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index f57ae212e..abe66c914 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -77,7 +77,7 @@ In a script, check `code`, not the message: the wording of a message can change, | Code | Exit | HTTP | Meaning | What to do | | --- | --- | --- | --- | --- | -| `DEVICE_NOT_ENROLLABLE` | 12 | 422 | `device add` of a device that cannot be enrolled. The reason is one of: not connected, network only, not trusted, Developer Mode off, OS too old, unsupported kind, locked, unreadable, a simulator or emulator, or enrolled on the other platform. | Fix what the message names (connect it by USB, trust this computer, turn on Developer Mode, unlock it) and run `device add` again. | +| `DEVICE_NOT_ENROLLABLE` | 12 | 422 | `device add` of a device that cannot be enrolled. The reason is one of: not connected, network only, not trusted, Developer Mode off, OS too old, unsupported kind, locked, unreadable, a simulator or emulator, enrolled on the other platform, or enrolled under another ID. | Fix what the message names (connect it by USB, trust this computer, turn on Developer Mode, unlock it) and run `device add` again. For a phone enrolled under another ID, run `device remove` on the record the message names first. | | `DEVICE_BUSY` | 11 | 409 | `device add` or `device remove` of a device that is leased, being cleaned, or held by another operation. `baseline remove` of a baseline whose copy is being cleaned up or held by another operation (a leased copy gets `BASELINE_IN_USE`). | Try again once that ends. | | `UNKNOWN_DEVICE` | 12 | 404 | `device remove` of an ID that is not an enrolled device. | Check the ID with `simlock list --devices`. | 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 741642291..2958641df 100644 --- a/website/src/content/docs/docs/worker/enrolling-physical-devices.mdx +++ b/website/src/content/docs/docs/worker/enrolling-physical-devices.mdx @@ -178,6 +178,7 @@ Removed 00008110-001A2B3C4D5E. It is no longer enrolled; nothing on the device c | `unreadable` | Simlock could not read the device. The message names the step that failed. Reconnect it and try again. | | `virtual-device` | The ID belongs to a simulator or emulator. Only real devices can be enrolled. | | `enrolled-on-other-platform` | The device is already enrolled under the other platform. | +| `enrolled-under-other-id` | The same phone is already enrolled under another ID. The message names that ID. Run `device remove` on it first, then add the phone again. | Other errors: From f951fed82b2406f4c1a2db8611f9a4df7b714e9f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 21:24:07 +0100 Subject: [PATCH 16/16] test: re-enrolling a phone with its own hardware serial is not a clash with itself (#1604) --- src/core/physical-enrollment.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/core/physical-enrollment.test.ts b/src/core/physical-enrollment.test.ts index 79bb8a544..f5a8e73a4 100644 --- a/src/core/physical-enrollment.test.ts +++ b/src/core/physical-enrollment.test.ts @@ -634,6 +634,8 @@ describe("PhysicalEnrollment", () => { const network = "192.168.1.5:5555"; const taking = await build([{ hardwareSerial: "SER-1", ids: [network] }]); await taking.core.enrollment.add("ios", network); + const same = await taking.core.enrollment.add("ios", network); + expect(same.reenrolled, "same ID, same serial").toBe(true); taking.driver.setPhysicalDevices([{ hardwareSerial: "SER-2", ids: [network] }]); const again = await taking.core.enrollment.add("ios", network); expect(again.reenrolled).toBe(true);