From 449b0a055dbc9f83e184e25fdd28fda0eaef0d85 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:28:09 +0200 Subject: [PATCH 01/28] test: allocate with physical: true leases an enrolled phone through the phone daemon (#874) --- src/agent-device/edge.test.ts | 55 +++++++++++++++++++++++++++++------ src/agent-device/testing.ts | 1 + src/agent-device/worker.ts | 1 + 3 files changed, 48 insertions(+), 9 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index efc62b640..b1e046568 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -75,6 +75,7 @@ interface SetUpOptions { readonly maxRunning?: number; readonly slowStart?: boolean; readonly upstream?: FakeAgentDevice; + readonly phoneUpstream?: FakeAgentDevice; } interface Rig { @@ -82,6 +83,7 @@ interface Rig { readonly daemon: DaemonServer; readonly driver: FakeDriver; readonly fake: FakeAgentDevice; + readonly phone: FakeAgentDevice; readonly filesystem: MemoryFilesystem; readonly logs: MemoryLogSink; readonly origin: string; @@ -165,6 +167,7 @@ async function setUp(options: SetUpOptions = {}): Promise { ]); const port = await freeLoopbackPort(); const fake = options.upstream ?? new FakeAgentDevice(); + const phone = options.phoneUpstream ?? new FakeAgentDevice(); const drivers = options.drivers?.(clock) ?? [iosDriver(clock)]; const stateDbPath = join(directory, "state.db"); const logs = new MemoryLogSink(); @@ -199,7 +202,7 @@ async function setUp(options: SetUpOptions = {}): Promise { drivers, filesystem, logger: new JsonLinesLogger({ clock, level: "debug", sink: logs }), - optionalModules: [agentDeviceModuleWith({ upstream: fake })], + optionalModules: [agentDeviceModuleWith({ phoneUpstream: phone, upstream: fake })], version: "1.2.3", } as StartDaemonOptions).then((daemon) => { runningDaemons.push(daemon); @@ -214,6 +217,7 @@ async function setUp(options: SetUpOptions = {}): Promise { daemon: undefined as never, driver: drivers[0] as FakeDriver, fake, + phone, filesystem, logs, origin, @@ -227,6 +231,7 @@ async function setUp(options: SetUpOptions = {}): Promise { daemon, driver: drivers[0] as FakeDriver, fake, + phone, filesystem, logs, origin, @@ -790,16 +795,48 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(installs()).toBe(1); }); - it("allocate with `physical: true` answers `refused: physical devices are not available through agent-device` and leaves no lease; `physical: false` and `physical: null` are granted", async () => { - const rig = await setUp({ maxRunning: 8 }); + it("allocate with `physical: true` leases an enrolled phone through the phone daemon, and the reply names the device with `physical: true` (`false` for a virtual one)", async () => { + const cases = [ + { + extra: { platform: "android" }, + id: "R58Y61A60HN", + platform: "android", + phone: { class: "phone", model: "Pixel 8", osVersion: "15" }, + physical: true, + }, + ] as const; + for (const { extra, id, phone, physical, platform } of cases) { + const rig = await setUp({ + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: ["35"], + clock, + knownModels: ["Pixel 8"], + physicalDevices: [{ ids: [id], ...phone }], + platform, + }), + ], + }); + await rig.daemon.dispatch("device.add", { id, platform }, adminSession); - const answer = await envelopeOf(await allocate(rig, 1, { physical: true })); + const answer = await envelopeOf(await allocate(rig, 1, { ...extra, physical })); + + expect(answer.result).toMatchObject({ + data: { + lease: { device: { model: phone.model, osVersion: phone.osVersion, physical } }, + }, + ok: true, + }); + expect(rig.phone.rpcRequests("agent_device.lease.allocate")).toMatchObject([ + { params: { leaseId: hex(1), serial: id } }, + ]); + expect(allocatesReceived(rig)).toEqual([]); + } + }); + + it("allocate with `physical: false` and `physical: null` are granted", async () => { + const rig = await setUp({ maxRunning: 8 }); - expect(answer.error).toMatchObject( - refusal("refused: physical devices are not available through agent-device"), - ); - expect(await leases(rig)).toEqual([]); - expect(allocatesReceived(rig)).toEqual([]); await granted(rig, 2, { physical: false }); await granted(rig, 3, { physical: null }); expect((await leases(rig)).map((lease) => lease.id)).toEqual([hex(2), hex(3)]); diff --git a/src/agent-device/testing.ts b/src/agent-device/testing.ts index b5efe1fbf..6390eb35e 100644 --- a/src/agent-device/testing.ts +++ b/src/agent-device/testing.ts @@ -696,6 +696,7 @@ export class FakeAgentDevice implements AgentDeviceUpstream { export function agentDeviceModuleWith(fakes: { readonly upstream?: AgentDeviceUpstream; + readonly phoneUpstream?: AgentDeviceUpstream; readonly health?: AgentDeviceHealthProbe; }): OptionalModuleDefinition { return { diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index fcb9d3b22..5472d35f8 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -82,6 +82,7 @@ function agentDeviceCapabilitySource(parts: AgentDeviceEdgeParts): { export interface AgentDeviceFakes { readonly upstream?: AgentDeviceUpstream; + readonly phoneUpstream?: AgentDeviceUpstream; readonly health?: AgentDeviceHealthProbe; } From cbc7ac00a3ef9228209b8bc81fbf585c1990afbd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:34:08 +0200 Subject: [PATCH 02/28] feat(agent-device): a physical allocate reaches the phone daemon through a routed host link (#874) --- src/agent-device/edge.test.ts | 36 +++++++++++++------- src/agent-device/front/allocate.ts | 15 ++++---- src/agent-device/front/host-link.ts | 53 +++++++++++++++++++++++++++++ src/agent-device/worker.ts | 16 +++++++-- src/modules/index.ts | 1 + 5 files changed, 97 insertions(+), 24 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index b1e046568..66d2acf5d 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -722,7 +722,7 @@ describe("the agent-device front, through the whole worker daemon", () => { } }); - it("the relayed allocate reply carries `data.lease.device` as `{ model, osVersion }` on iOS and on Android without a tag, and `{ model, osVersion, imageTag }` on Android with one, the daemon's `deviceKey` and `data.device` unchanged", async () => { + it("the relayed allocate reply carries `data.lease.device` as `{ model, osVersion, physical: false }` on iOS and on Android without a tag, and with `imageTag` on Android with one, the daemon's `deviceKey` and `data.device` unchanged", async () => { const rig = await setUp({ drivers: (clock) => [ new FakeDriver({ @@ -738,14 +738,14 @@ describe("the agent-device front, through the whole worker daemon", () => { maxRunning: 8, }); const cases = [ - [1, { osVersion: ">=18 <27" }, { model: "iPhone 16", osVersion: "26.0" }], - [2, {}, { model: "iPhone 16", osVersion: "27.0" }], + [1, { osVersion: ">=18 <27" }, { model: "iPhone 16", osVersion: "26.0", physical: false }], + [2, {}, { model: "iPhone 16", osVersion: "27.0", physical: false }], [ 3, { imageTag: "google_apis_playstore", platform: "android" }, - { imageTag: "google_apis_playstore", model: "Pixel 8", osVersion: "34" }, + { imageTag: "google_apis_playstore", model: "Pixel 8", osVersion: "34", physical: false }, ], - [4, { platform: "android" }, { model: "Pixel 8", osVersion: "35" }], + [4, { platform: "android" }, { model: "Pixel 8", osVersion: "35", physical: false }], ] as const; for (const [n, extra, device] of cases) { @@ -818,6 +818,7 @@ describe("the agent-device front, through the whole worker daemon", () => { ], }); await rig.daemon.dispatch("device.add", { id, platform }, adminSession); + rig.driver.setPhysicalPresence(id, true); const answer = await envelopeOf(await allocate(rig, 1, { ...extra, physical })); @@ -1618,7 +1619,7 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(rig.fake.uploads).toEqual(["artifact bytes"]); }); - it("on a worker, an `x-agent-device-lease-id` header naming another token's lease, a malformed one and no header are each forwarded, as today", async () => { + it("on a worker, an `x-agent-device-lease-id` header naming another token's lease or no header is forwarded, and a malformed one is refused `the x-agent-device-lease-id header is not a lease id`", async () => { const rig = await setUp(); await granted(rig, 1); const other = { "x-agent-device-lease-id": hex(1) }; @@ -1627,7 +1628,11 @@ describe("the agent-device front, through the whole worker daemon", () => { rig.fake.requests.filter((request) => request.path === "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/upload/preflight").length; const answers: Response[] = []; - for (const headers of [other, malformed, {}]) { + for (const [headers, reaches] of [ + [other, 1], + [malformed, 0], + [{}, 1], + ] as const) { const before = preflights(); const answer = await send(rig, "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/upload/preflight", { body: "{}", @@ -1635,10 +1640,13 @@ describe("the agent-device front, through the whole worker daemon", () => { token: secrets.two, }); answers.push(answer); - expect(preflights()).toBe(before + 1); + expect(preflights()).toBe(before + reaches); } - expect(answers.map((answer) => answer.status)).toEqual([200, 200, 200]); + expect(answers.map((answer) => answer.status)).toEqual([200, 400, 200]); + expect(await answers[1]?.text()).toContain( + "the x-agent-device-lease-id header is not a lease id", + ); }); it("an `/rpc` body over 1 MiB, one that is not JSON, a JSON array, and an object with no `method` are each refused with their message and `id: null`, also while agent-device is unavailable, and neither simlock nor the agent-device daemon sees them", async () => { @@ -3764,7 +3772,7 @@ describe("the agent-device front's request rules", () => { const before = commandsReceived(rig).length; expect(await listedIds(await runCommand(rig, "devices", undefined))).toEqual([]); - expect(commandsReceived(rig)).toHaveLength(before + 1); + expect(commandsReceived(rig)).toHaveLength(before); await granted(rig, 1); rig.fake.listDevices([...three, { id: idOf(rig, 2) }, { id: idOf(rig, 1) }]); @@ -3786,7 +3794,7 @@ describe("the agent-device front's request rules", () => { expect(await listedIds(await runCommand(rig, "devices", undefined))).toEqual([idOf(rig, 2)]); }); - it("a `devices` error answer from agent-device passes unchanged; a success with no list at `data.devices`, a body over 1 MiB, a non-JSON body and a list holding a non-object each answer an empty list; `devices` with `meta.requestProgress` is refused", async () => { + it("a `devices` error answer from agent-device passes unchanged; a success with no list at `data.devices`, a body over 1 MiB, a non-JSON body and a list holding a non-object each answer `could not read the device list from the worker holding lease `; `devices` with `meta.requestProgress` is refused", async () => { const rig = await setUp(); await granted(rig, 1); rig.fake.listDevices([{ id: idOf(rig, 1) }]); @@ -3824,7 +3832,11 @@ describe("the agent-device front's request rules", () => { ]; for (const body of unusable) { rig.fake.answerDevicesWith(body); - expect(await listedIds(await runCommand(rig, "devices", 1))).toEqual([]); + expect((await envelopeOf(await runCommand(rig, "devices", 1))).error).toMatchObject({ + data: { + message: `could not read the device list from the worker holding lease ${hex(1)}`, + }, + }); } await refused( rig, diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index de8433bde..f10864c1c 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -52,6 +52,7 @@ interface Plan { readonly class?: "phone" | "tv" | "desktop"; readonly imageTag?: string; readonly osVersion?: string; + readonly physical?: true; readonly ttlMs?: number; } @@ -85,13 +86,7 @@ function deviceRefusal(fields: ReturnType): FrontReply | return undefined; } -function unsupportedSelector( - params: Record, - fields: ReturnType, -): FrontReply | undefined { - if (params["physical"] === true) { - return refusal("refused: physical devices are not available through agent-device"); - } +function unsupportedSelector(fields: ReturnType): FrontReply | undefined { if (typeof fields.target === "string" && !Object.hasOwn(CLASS_OF_TARGET, fields.target)) { return refusal(`refused: unknown --target ${fields.target}; use mobile, tv or desktop`); } @@ -105,7 +100,7 @@ function refusalFor(params: Record): FrontReply | undefined { return refusal("refused: this agent-device is too old for simlock; upgrade it"); } if (notPlain(params)) return refusal("refused: simlock leases only plain devices"); - const unsupported = unsupportedSelector(params, fields); + const unsupported = unsupportedSelector(fields); if (unsupported !== undefined) return unsupported; const device = deviceRefusal(fields); if (device !== undefined) return device; @@ -138,6 +133,7 @@ function planOf(params: Record, cap: number | undefined): Plan platform: fields.platform as "ios" | "android", ...(device === undefined ? (klass === undefined ? {} : { class: klass }) : { model: device }), ...stringFields(fields), + ...(params["physical"] === true ? { physical: true as const } : {}), ...(ttlMs === undefined ? {} : { ttlMs }), }; } @@ -318,7 +314,7 @@ export async function allocate( if (outcome.kind === "gone") return undefined; if (outcome.kind === "failed") return frontReply(outcome.reply, call); const { grant } = outcome; - const address = grant.device.address; + const address = grant.device.spec.physical ? grant.device.driverDeviceId : grant.device.address; if (request.signal.aborted || address === undefined || address === "") { await releaseSimlock(context, identity, plan.leaseId); return request.signal.aborted @@ -407,6 +403,7 @@ function withGrantedDevice( lease["device"] = { model: spec.model, osVersion: spec.osVersion, + physical: spec.physical, ...(spec.imageTag === undefined ? {} : { imageTag: spec.imageTag }), }; return { ...reply, text: JSON.stringify(body) }; diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index f5ff27734..0907531d8 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -1,6 +1,9 @@ import type { Identity } from "../../auth/index.js"; +import type { ModuleRegistryView } from "../../modules/index.js"; import type { AgentDevicePlatform } from "../host/agent-device-supervisor.js"; import type { AgentDeviceHost } from "../host/host.js"; +import { FRONT_PREFIX } from "../shared/paths.js"; +import { classifyCall, readRpcBody } from "../shared/rpc.js"; export type LinkStatus = | { @@ -53,3 +56,53 @@ export class InProcessHostLink implements HostLink { return this.host.forward(request, identity); } } + +interface RoutedHosts { + readonly simulators: AgentDeviceHost; + readonly phones: AgentDeviceHost; +} + +type Role = keyof RoutedHosts; + +// why: a worker runs one agent-device daemon for simulators and one for phones; this link holds a host for each and remembers which daemon each lease was allocated on. +export class RoutedHostLink implements HostLink { + readonly readsLeaseHeader = true; + readonly #roles = new Map(); + + constructor( + private readonly hosts: RoutedHosts, + private readonly registry: ModuleRegistryView, + ) {} + + status(leaseId?: string): ReturnType { + return this.#host(leaseId === undefined ? undefined : this.#roles.get(leaseId)).status(); + } + + async forward(request: Request, identity: Identity, leaseId?: string): Promise { + const role = await this.#roleOf(request, leaseId); + return this.hosts[role].forward(request, identity); + } + + #host(role: Role | undefined): AgentDeviceHost { + return this.hosts[role ?? "simulators"]; + } + + async #roleOf(request: Request, leaseId: string | undefined): Promise { + const known = leaseId === undefined ? undefined : this.#roles.get(leaseId); + if (known !== undefined) return known; + if (request.method !== "POST" || new URL(request.url).pathname !== `${FRONT_PREFIX}/rpc`) { + return "simulators"; + } + const read = await readRpcBody(request.clone()); + if (read.kind !== "request" || classifyCall(read.method, read.params) !== "allocate") { + return "simulators"; + } + const address = read.params["serial"] ?? read.params["udid"]; + const phone = this.registry.snapshot.devices.some( + (device) => device.physical && device.driverDeviceId === address, + ); + if (!phone) return "simulators"; + if (leaseId !== undefined) this.#roles.set(leaseId, "phones"); + return "phones"; + } +} diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index 5472d35f8..a63cb21ea 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -1,10 +1,10 @@ import type { HttpDispatch } from "../http/dispatcher-session.js"; import type { Identity } from "../auth/index.js"; import type { Clock } from "../ports/index.js"; -import type { WorkerContext, WorkerModule } from "../modules/index.js"; +import type { ModuleRegistryView, WorkerContext, WorkerModule } from "../modules/index.js"; import type { AgentDeviceModuleConfig } from "./definition.js"; import { FrontMap } from "./front/front-map.js"; -import { InProcessHostLink, type LinkStatus } from "./front/host-link.js"; +import { RoutedHostLink, type LinkStatus } from "./front/host-link.js"; import { Renewals } from "./front/renewals.js"; import { AgentDeviceSupervisor, @@ -30,13 +30,21 @@ interface AgentDeviceEdgeParts extends AgentDeviceFrontParts { function createAgentDeviceEdgeParts( upstream: AgentDeviceUpstream, + phoneUpstream: AgentDeviceUpstream, clock: Clock, platforms: readonly AgentDevicePlatform[], + registry: ModuleRegistryView, ): AgentDeviceEdgeParts { const record = new ReleaseScopeRecord(); return { leaseEnd: new AgentDeviceLeaseEnd(upstream, record), - link: new InProcessHostLink(new AgentDeviceHost(upstream, platforms, record)), + link: new RoutedHostLink( + { + phones: new AgentDeviceHost(phoneUpstream, platforms), + simulators: new AgentDeviceHost(upstream, platforms, record), + }, + registry, + ), map: new FrontMap(clock), renewals: new Renewals(clock), }; @@ -115,8 +123,10 @@ export function createWorkerWith( const phoneSupervisor = supervise("phones"); const parts = createAgentDeviceEdgeParts( fakes.upstream ?? new SupervisorAgentDeviceUpstream(supervisor), + fakes.phoneUpstream ?? new SupervisorAgentDeviceUpstream(phoneSupervisor), ctx.clock, ctx.platforms, + ctx.registry, ); return { capability: agentDeviceCapabilitySource(parts), diff --git a/src/modules/index.ts b/src/modules/index.ts index ec793246d..4e3e7b5a1 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -14,6 +14,7 @@ export type { ModuleHttpResponse, ModuleLeaseEndParticipant, ModuleMount, + ModuleRegistryView, ModuleRelayTarget, OptionalModuleDefinition, WorkerContext, From 08e9ea3096b8df170e9bd94532fb4e287efc393a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:34:56 +0200 Subject: [PATCH 03/28] test: allocate with physical: true leases iOS phones by model and osVersion too (#874) --- src/agent-device/edge.test.ts | 36 ++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 66d2acf5d..ada99b1a2 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -798,20 +798,37 @@ describe("the agent-device front, through the whole worker daemon", () => { it("allocate with `physical: true` leases an enrolled phone through the phone daemon, and the reply names the device with `physical: true` (`false` for a virtual one)", async () => { const cases = [ { + address: { serial: "R58Y61A60HN" }, + asked: { platform: "android" }, extra: { platform: "android" }, id: "R58Y61A60HN", - platform: "android", phone: { class: "phone", model: "Pixel 8", osVersion: "15" }, - physical: true, + platform: "android", + }, + { + address: { udid: "00008030-000270803C28802E" }, + asked: { model: "iPhone 15 Pro", platform: "ios" }, + extra: { device: "iPhone 15 Pro" }, + id: "00008030-000270803C28802E", + phone: { class: "phone", model: "iPhone 15 Pro", osVersion: "18.4" }, + platform: "ios", + }, + { + address: { udid: "00008030-000270803C28802E" }, + asked: { osVersion: ">=18", platform: "ios" }, + extra: { osVersion: ">=18" }, + id: "00008030-000270803C28802E", + phone: { class: "phone", model: "iPhone 15 Pro", osVersion: "18.4" }, + platform: "ios", }, ] as const; - for (const { extra, id, phone, physical, platform } of cases) { + for (const { address, asked, extra, id, phone, platform } of cases) { const rig = await setUp({ drivers: (clock) => [ new FakeDriver({ availableOsVersions: ["35"], clock, - knownModels: ["Pixel 8"], + knownModels: [phone.model], physicalDevices: [{ ids: [id], ...phone }], platform, }), @@ -820,16 +837,21 @@ describe("the agent-device front, through the whole worker daemon", () => { await rig.daemon.dispatch("device.add", { id, platform }, adminSession); rig.driver.setPhysicalPresence(id, true); - const answer = await envelopeOf(await allocate(rig, 1, { ...extra, physical })); + const answer = await envelopeOf( + await allocate(rig, 1, { platform, ...extra, physical: true }), + ); expect(answer.result).toMatchObject({ data: { - lease: { device: { model: phone.model, osVersion: phone.osVersion, physical } }, + lease: { + device: { model: phone.model, osVersion: phone.osVersion, physical: true }, + }, }, ok: true, }); + expect(await requestedSpecs(rig, hex(1))).toMatchObject([{ ...asked, physical: true }]); expect(rig.phone.rpcRequests("agent_device.lease.allocate")).toMatchObject([ - { params: { leaseId: hex(1), serial: id } }, + { params: { leaseId: hex(1), ...address } }, ]); expect(allocatesReceived(rig)).toEqual([]); } From bd0af98ab3d31b5f12e3bbeaefc859a9e2729406 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:35:38 +0200 Subject: [PATCH 04/28] test: allocate with a physical that is not a boolean is refused malformed physical (#874) --- src/agent-device/edge.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index ada99b1a2..793acdc17 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -3555,7 +3555,7 @@ describe("the agent-device front's request rules", () => { ); }); - it("a `udid` that is a number is refused with `refused: malformed udid`; a `shardAll` that is a string with `refused: malformed shardAll`; on an allocate an `osVersion` that is a number is refused with `refused: malformed osVersion` and an `imageTag` that is an object with `refused: malformed imageTag`, as is an `osVersion` number on a command's flags, while `osVersion: null` is absent", async () => { + it("a `udid` that is a number is refused with `refused: malformed udid`; a `shardAll` that is a string with `refused: malformed shardAll`; on an allocate an `osVersion` that is a number is refused with `refused: malformed osVersion` an `imageTag` that is an object with `refused: malformed imageTag` and a `physical` of `yes` or `1` with `refused: malformed physical` and no lease, as is an `osVersion` number on a command's flags, while `osVersion: null` is absent", async () => { const rig = await setUp(); await granted(rig, 1); await forwarded(rig, () => runCommand(rig, "test", 1, { flags: { shardAll: 2 } })); @@ -3572,6 +3572,10 @@ describe("the agent-device front's request rules", () => { ); await refused(rig, () => allocate(rig, 2, { osVersion: 26 }), "refused: malformed osVersion"); await refused(rig, () => allocate(rig, 2, { imageTag: {} }), "refused: malformed imageTag"); + for (const physical of ["yes", 1]) { + await refused(rig, () => allocate(rig, 2, { physical }), "refused: malformed physical"); + } + expect(await listed(rig)).toEqual([hex(1)]); await refused( rig, () => runCommand(rig, "snapshot", 1, { flags: { osVersion: 26 } }), From 0c921c50cd84ce2af8dba43c3149fe0e9901dcb3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:35:49 +0200 Subject: [PATCH 05/28] feat(agent-device): the front type-checks physical on the wire (#874) --- src/agent-device/shared/selectors.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/agent-device/shared/selectors.ts b/src/agent-device/shared/selectors.ts index adb392281..2165003fe 100644 --- a/src/agent-device/shared/selectors.ts +++ b/src/agent-device/shared/selectors.ts @@ -18,12 +18,16 @@ const STRING_FIELDS = [ "osVersion", "imageTag", ] as const; +const BOOLEAN_FIELDS = ["physical"] as const; const INTEGER_FIELDS = ["shardAll", "shardSplit"] as const; export function malformedField(source: Fields): string | undefined { for (const field of STRING_FIELDS) { if (present(source[field]) && typeof source[field] !== "string") return field; } + for (const field of BOOLEAN_FIELDS) { + if (present(source[field]) && typeof source[field] !== "boolean") return field; + } for (const field of INTEGER_FIELDS) { if (present(source[field]) && !Number.isInteger(source[field])) return field; } From 1dfa012d0a47fd7b7b9452a5b83ff1bd7abaf013 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:36:41 +0200 Subject: [PATCH 06/28] test: simlock's refusal of a physical allocate reaches the agent with no lease (#874) --- src/agent-device/edge.test.ts | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 793acdc17..cc2810d9e 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -857,6 +857,46 @@ describe("the agent-device front, through the whole worker daemon", () => { } }); + it("allocate with `physical: true` that simlock refuses (an `imageTag`, a model no enrolled phone has, an OS range none fits) answers `refused by simlock: ` and leaves no lease", async () => { + const rig = await setUp({ + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: ["35"], + clock, + knownModels: ["Pixel 8"], + physicalDevices: [ + { class: "phone", ids: ["R58Y61A60HN"], model: "Pixel 8", osVersion: "15" }, + ], + platform: "android", + }), + ], + }); + await rig.daemon.dispatch( + "device.add", + { id: "R58Y61A60HN", platform: "android" }, + adminSession, + ); + rig.driver.setPhysicalPresence("R58Y61A60HN", true); + const cases = [ + [{ imageTag: "default" }, "imageTag: `imageTag` has no meaning for a physical device"], + [{ device: "Pixel 9" }, "no enrolled physical device can match android model Pixel 9"], + [ + { osVersion: ">=16" }, + "no enrolled physical device can match android class phone os in the requested range", + ], + ] as const; + + for (const [index, [extra, message]] of cases.entries()) { + const answer = await envelopeOf( + await allocate(rig, index + 1, { platform: "android", ...extra, physical: true }), + ); + + expect(answer.error).toMatchObject(refusal(`refused by simlock: ${message}`)); + } + expect(await leases(rig)).toEqual([]); + expect(rig.phone.rpcRequests("agent_device.lease.allocate")).toEqual([]); + }); + it("allocate with `physical: false` and `physical: null` are granted", async () => { const rig = await setUp({ maxRunning: 8 }); From 4bfe19239d43ef87dc7e0c1deece6c4e77c52161 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:37:42 +0200 Subject: [PATCH 07/28] test: a physical allocate while the phone daemon is not running names its reason (#874) --- src/agent-device/edge.test.ts | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index cc2810d9e..2d39506c9 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -259,6 +259,35 @@ async function waitListening(origin: string): Promise { throw new Error("the daemon never listened"); } +const phoneSerial = "R58Y61A60HN"; + +// why: one Android driver serving a virtual Pixel 8 and an enrolled, present phone, so a test can lease either through the same worker. +async function setUpWithPhone(options: SetUpOptions = {}): Promise { + const rig = await setUp({ + ...options, + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: ["35"], + clock, + defaultModels: { phone: ["Pixel 8"] }, + knownModels: ["Pixel 8"], + modelClasses: { "Pixel 8": "phone" }, + physicalDevices: [ + { class: "phone", ids: [phoneSerial], model: "Pixel 8", osVersion: "15" }, + ], + platform: "android", + }), + ], + }); + await rig.daemon.dispatch("device.add", { id: phoneSerial, platform: "android" }, adminSession); + rig.driver.setPhysicalPresence(phoneSerial, true); + return rig; +} + +function allocatePhone(rig: Rig, n: number, extra: Record = {}) { + return allocate(rig, n, { platform: "android", ...extra, physical: true }); +} + async function advance(rig: Rig, ms: number, step = 1_000): Promise { for (let elapsed = 0; elapsed < ms; elapsed += step) { rig.clock.advance(Math.min(step, ms - elapsed)); @@ -897,6 +926,40 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(rig.phone.rpcRequests("agent_device.lease.allocate")).toEqual([]); }); + it("allocate with `physical: true` while the phone daemon is not running answers `agent-device is not available on this simlock: phone daemon: ` and releases the lease; a virtual allocate is granted, a command on a live phone lease answers the same, and with the simulator daemon down a physical allocate answers the simulator daemon's reason", async () => { + const down = [ + ["starting", "phone daemon: starting"], + ["adb not found", "phone daemon: adb not found"], + ] as const; + for (const [reason, message] of down) { + const rig = await setUpWithPhone({ maxRunning: 4 }); + rig.phone.setUnavailable(reason); + + const answer = await envelopeOf(await allocatePhone(rig, 1)); + + expect(answer.error).toMatchObject(refusal(`${notAvailable}${message}`, "COMMAND_FAILED")); + await expect.poll(() => listed(rig)).toEqual([]); + await granted(rig, 2, { platform: "android" }); + expect(await listed(rig)).toEqual([hex(2)]); + } + + const live = await setUpWithPhone(); + await granted(live, 1, { platform: "android", physical: true }); + live.phone.setUnavailable("starting"); + const liveCommand = await envelopeOf(await command(live, "snapshot", 1)); + expect(liveCommand.error).toMatchObject( + refusal(`${notAvailable}phone daemon: starting`, "COMMAND_FAILED"), + ); + + const simulatorsDown = await setUpWithPhone(); + simulatorsDown.fake.setUnavailable("found 0.20.3"); + const simulatorsDownAnswer = await envelopeOf(await allocatePhone(simulatorsDown, 1)); + expect(simulatorsDownAnswer.error).toMatchObject( + refusal(`${notAvailable}found 0.20.3`, "COMMAND_FAILED"), + ); + expect(await listed(simulatorsDown)).toEqual([]); + }); + it("allocate with `physical: false` and `physical: null` are granted", async () => { const rig = await setUp({ maxRunning: 8 }); From 263f45c68adb2b3d8214ac7438e0185f53efa917 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:38:22 +0200 Subject: [PATCH 08/28] feat(agent-device): a phone lease answers with the phone daemon's reason while it is down (#874) --- src/agent-device/front/host-link.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index 0907531d8..80ae2096c 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -3,6 +3,7 @@ import type { ModuleRegistryView } from "../../modules/index.js"; import type { AgentDevicePlatform } from "../host/agent-device-supervisor.js"; import type { AgentDeviceHost } from "../host/host.js"; import { FRONT_PREFIX } from "../shared/paths.js"; +import { frontReplyFor, notAvailable } from "../shared/replies.js"; import { classifyCall, readRpcBody } from "../shared/rpc.js"; export type LinkStatus = @@ -74,17 +75,29 @@ export class RoutedHostLink implements HostLink { private readonly registry: ModuleRegistryView, ) {} - status(leaseId?: string): ReturnType { - return this.#host(leaseId === undefined ? undefined : this.#roles.get(leaseId)).status(); + async status(leaseId?: string): Promise { + const role = leaseId === undefined ? undefined : this.#roles.get(leaseId); + if (role !== "phones") return this.hosts.simulators.status(); + return this.#phoneStatus(); } async forward(request: Request, identity: Identity, leaseId?: string): Promise { const role = await this.#roleOf(request, leaseId); + if (role === "phones") { + const status = await this.#phoneStatus(); + if (status.state === "unavailable") { + return frontReplyFor(request, notAvailable(status.reason)); + } + } return this.hosts[role].forward(request, identity); } - #host(role: Role | undefined): AgentDeviceHost { - return this.hosts[role ?? "simulators"]; + // why: the phone daemon's reason is named with its role, so an agent can tell it from the simulator daemon's. + async #phoneStatus(): Promise { + const status = await this.hosts.phones.status(); + return status.state === "unavailable" + ? { reason: `phone daemon: ${status.reason}`, state: "unavailable" } + : status; } async #roleOf(request: Request, leaseId: string | undefined): Promise { From c4715ea4f75ccbafd634764d1de87b6293a65e1f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:39:47 +0200 Subject: [PATCH 09/28] test: later calls follow the lease to the daemon that allocated it (#874) --- src/agent-device/edge.test.ts | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 2d39506c9..471bb7cd2 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -960,6 +960,46 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(await listed(simulatorsDown)).toEqual([]); }); + it("a command, a heartbeat, a release and a `devices` naming a phone lease reach the phone daemon, those naming a simulator lease reach the simulator daemon, and `devices` with one lease of each answers both devices, each from its daemon", async () => { + const rig = await setUpWithPhone(); + await granted(rig, 1, { physical: true, platform: "android" }); + await granted(rig, 2, { platform: "android" }); + rig.phone.listDevices([{ id: phoneSerial }, { id: "emulator-5600" }]); + rig.fake.listDevices([{ id: idOf(rig, 2) }, { id: "emulator-5601" }]); + const reached = (fake: FakeAgentDevice, method: string) => fake.rpcRequests(method).length; + const calls = [ + ["agent_device.command", (n: number) => command(rig, "snapshot", n)], + ["agent_device.lease.heartbeat", (n: number) => heartbeat(rig, n)], + ["agent_device.lease.release", (n: number) => release(rig, n)], + ] as const; + + for (const [method, send] of calls) { + const [phoneBefore, simulatorBefore] = [ + reached(rig.phone, method), + reached(rig.fake, method), + ]; + await send(1); + expect([reached(rig.phone, method), reached(rig.fake, method)]).toEqual([ + phoneBefore + 1, + simulatorBefore, + ]); + await send(2); + expect([reached(rig.phone, method), reached(rig.fake, method)]).toEqual([ + phoneBefore + 1, + simulatorBefore + 1, + ]); + } + + await granted(rig, 3, { physical: true, platform: "android" }); + await granted(rig, 4, { platform: "android" }); + rig.fake.listDevices([{ id: idOf(rig, 4) }, { id: "emulator-5601" }]); + const answer = await envelopeOf(await runCommand(rig, "devices", undefined)); + const data = answer.result?.["data"] as { devices: { id: string }[] } | undefined; + expect(data?.devices.map((device) => device.id).sort()).toEqual( + [phoneSerial, idOf(rig, 4)].sort(), + ); + }); + it("allocate with `physical: false` and `physical: null` are granted", async () => { const rig = await setUp({ maxRunning: 8 }); From 3726701c48179f1be15a6b265cb982f4924a2355 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:40:22 +0200 Subject: [PATCH 10/28] test: non-RPC routes on a worker follow the lease header to the phone daemon (#874) --- src/agent-device/edge.test.ts | 65 +++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 26 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 471bb7cd2..ae2234c46 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -1784,34 +1784,47 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(rig.fake.uploads).toEqual(["artifact bytes"]); }); - it("on a worker, an `x-agent-device-lease-id` header naming another token's lease or no header is forwarded, and a malformed one is refused `the x-agent-device-lease-id header is not a lease id`", async () => { - const rig = await setUp(); - await granted(rig, 1); - const other = { "x-agent-device-lease-id": hex(1) }; + it("on a worker, an upload preflight and an artifact download follow the `x-agent-device-lease-id` header to the daemon of the lease it names, go to the simulator daemon with no header or another token's lease, and a malformed header is refused `the x-agent-device-lease-id header is not a lease id`", async () => { + const rig = await setUpWithPhone(); + await granted(rig, 1, { physical: true, platform: "android" }); + await granted(rig, 2, { platform: "android" }); + const named = (n: number) => ({ "x-agent-device-lease-id": hex(n) }); const malformed = { "x-agent-device-lease-id": "NOT-A-LEASE-ID".repeat(4) }; - const preflights = () => - rig.fake.requests.filter((request) => request.path === "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/upload/preflight").length; - - const answers: Response[] = []; - for (const [headers, reaches] of [ - [other, 1], - [malformed, 0], - [{}, 1], - ] as const) { - const before = preflights(); - const answer = await send(rig, "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/upload/preflight", { - body: "{}", - headers, - token: secrets.two, - }); - answers.push(answer); - expect(preflights()).toBe(before + reaches); - } + const reaching = (fake: FakeAgentDevice, path: string) => + fake.requests.filter((request) => request.path === path).length; + const routes = [ + ["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/upload/preflight", { body: "{}" }], + ["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/artifacts/a1", {}], + ] as const; + const cases = [ + [named(1), secrets.one, "phone"], + [named(2), secrets.one, "simulators"], + [{}, secrets.one, "simulators"], + [named(1), secrets.two, "phone"], + [malformed, secrets.one, "refused"], + ] as const; - expect(answers.map((answer) => answer.status)).toEqual([200, 400, 200]); - expect(await answers[1]?.text()).toContain( - "the x-agent-device-lease-id header is not a lease id", - ); + for (const [path, body] of routes) { + for (const [headers, token, reaches] of cases) { + const [phoneBefore, simulatorsBefore] = [ + reaching(rig.phone, path), + reaching(rig.fake, path), + ]; + + const answer = await send(rig, path, { ...body, headers, token }); + + expect([ + reaching(rig.phone, path) - phoneBefore, + reaching(rig.fake, path) - simulatorsBefore, + ]).toEqual([reaches === "phone" ? 1 : 0, reaches === "simulators" ? 1 : 0]); + if (reaches === "refused") { + expect(answer.status).toBe(400); + expect(await answer.text()).toContain( + "the x-agent-device-lease-id header is not a lease id", + ); + } + } + } }); it("an `/rpc` body over 1 MiB, one that is not JSON, a JSON array, and an object with no `method` are each refused with their message and `id: null`, also while agent-device is unavailable, and neither simlock nor the agent-device daemon sees them", async () => { From 890bebd436b6fca682896a67b0f9c9130d3c09c2 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:41:01 +0200 Subject: [PATCH 11/28] test: simlock ending a phone lease releases it at the phone daemon (#874) --- src/agent-device/edge.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index ae2234c46..c05ac8335 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -1000,6 +1000,29 @@ describe("the agent-device front, through the whole worker daemon", () => { ); }); + it("when simlock ends a phone lease (presence lost, an operator's release of all) the release reaches the phone daemon, not the simulator daemon, and the agent's next heartbeat answers ended by simlock", async () => { + const endings = [ + async (rig: Rig) => { + rig.driver.setPhysicalPresence(phoneSerial, false); + await advance(rig, 120_000); + }, + async (rig: Rig) => { + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + }, + ]; + for (const end of endings) { + const rig = await setUpWithPhone(); + await granted(rig, 1, { physical: true, platform: "android" }); + + await end(rig); + + await expect.poll(() => listed(rig)).toEqual([]); + await expect.poll(() => rig.phone.rpcRequests("agent_device.lease.release")).toHaveLength(1); + expect(rig.fake.rpcRequests("agent_device.lease.release")).toEqual([]); + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + } + }); + it("allocate with `physical: false` and `physical: null` are granted", async () => { const rig = await setUp({ maxRunning: 8 }); From df7eb557bdcb7978eab8d4d0f944861f55c53d07 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:41:19 +0200 Subject: [PATCH 12/28] feat(agent-device): both daemons' lease-end participants run for every ended lease (#874) --- src/agent-device/front/host-link.ts | 5 +++++ src/agent-device/worker.ts | 24 ++++++++++++++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index 80ae2096c..87d4f7a01 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -92,6 +92,11 @@ export class RoutedHostLink implements HostLink { return this.hosts[role].forward(request, identity); } + // why: a lease that ended no longer needs its daemon remembered, and the map holds only live phone leases. + forget(leaseId: string): void { + this.#roles.delete(leaseId); + } + // why: the phone daemon's reason is named with its role, so an agent can tell it from the simulator daemon's. async #phoneStatus(): Promise { const status = await this.hosts.phones.status(); diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index a63cb21ea..d558624e6 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -25,7 +25,9 @@ import { import { frontReplyFor, notAvailable } from "./shared/replies.js"; interface AgentDeviceEdgeParts extends AgentDeviceFrontParts { - readonly leaseEnd: AgentDeviceLeaseEnd; + readonly link: RoutedHostLink; + // why: one participant per daemon; for each ended lease only the one whose record holds its scope sends a release. + readonly leaseEnds: readonly AgentDeviceLeaseEnd[]; } function createAgentDeviceEdgeParts( @@ -35,13 +37,17 @@ function createAgentDeviceEdgeParts( platforms: readonly AgentDevicePlatform[], registry: ModuleRegistryView, ): AgentDeviceEdgeParts { - const record = new ReleaseScopeRecord(); + const simulatorRecord = new ReleaseScopeRecord(); + const phoneRecord = new ReleaseScopeRecord(); return { - leaseEnd: new AgentDeviceLeaseEnd(upstream, record), + leaseEnds: [ + new AgentDeviceLeaseEnd(upstream, simulatorRecord), + new AgentDeviceLeaseEnd(phoneUpstream, phoneRecord), + ], link: new RoutedHostLink( { - phones: new AgentDeviceHost(phoneUpstream, platforms), - simulators: new AgentDeviceHost(upstream, platforms, record), + phones: new AgentDeviceHost(phoneUpstream, platforms, phoneRecord), + simulators: new AgentDeviceHost(upstream, platforms, simulatorRecord), }, registry, ), @@ -142,7 +148,13 @@ export function createWorkerWith( void supervisor.start().then(() => phoneSupervisor.start()); } }, - beforeDeviceReclaim: (ended, signal) => parts.leaseEnd.leaseEnded(ended, signal), + beforeDeviceReclaim: async (ended, signal) => { + try { + await Promise.all(parts.leaseEnds.map((end) => end.leaseEnded(ended, signal))); + } finally { + parts.link.forget(ended.leaseId); + } + }, beforeDrain: async () => { disposeAgentDeviceEdge(parts); await cancelWaitingAllocates(parts, (id) => ctx.cancelPending(id)); From c4d9c8640bd2e9ad973f462f10beb431b8a7f9ca Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:41:51 +0200 Subject: [PATCH 13/28] test: a command on a phone lease naming another serial or udid is refused (#874) --- src/agent-device/edge.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index c05ac8335..162bdc876 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -3506,6 +3506,21 @@ describe("the agent-device front's request rules", () => { } }); + it("on a phone lease the phone's own serial is forwarded to the phone daemon; another `serial` or `udid` is refused with `refused: simlock picks the device`", async () => { + const rig = await setUpWithPhone(); + await granted(rig, 1, { physical: true, platform: "android" }); + const reached = () => rig.phone.rpcRequests("agent_device.command").length; + await runCommand(rig, "snapshot", 1, { flags: { serial: phoneSerial } }); + expect(reached()).toBe(1); + + for (const flags of [{ serial: "emulator-5554" }, { udid: "00008030-000270803C28802E" }]) { + const answer = await envelopeOf(await runCommand(rig, "snapshot", 1, { flags })); + + expect(answer.error).toMatchObject(refusal(simlockPicks)); + } + expect(reached()).toBe(1); + }); + it("`--device` with the leased device's id, and its name with `_` for a space, extra spaces and other letter case, are forwarded unchanged", async () => { const rig = await setUp(); rig.fake.nameDeviceInNextReply({ name: "Sim Lock Phone" }); From 1688771b844253d2b602cfeec2645bf1d9563690 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:42:07 +0200 Subject: [PATCH 14/28] test: an ended phone lease is forgotten by the routed link (#874) --- src/agent-device/edge.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 162bdc876..962492071 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -1023,6 +1023,18 @@ describe("the agent-device front, through the whole worker daemon", () => { } }); + it("after a phone lease ends, an allocate that reuses its lease id for a virtual device reaches the simulator daemon", async () => { + const rig = await setUpWithPhone(); + await granted(rig, 1, { physical: true, platform: "android" }); + await release(rig, 1); + await expect.poll(() => listed(rig)).toEqual([]); + + await granted(rig, 1, { platform: "android" }); + + expect(allocatesReceived(rig, 1)).toHaveLength(1); + expect(rig.phone.rpcRequests("agent_device.lease.allocate")).toHaveLength(1); + }); + it("allocate with `physical: false` and `physical: null` are granted", async () => { const rig = await setUp({ maxRunning: 8 }); From f7d3533103a41c15b0c44e9d5cf3093e75cb2d3d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:43:33 +0200 Subject: [PATCH 15/28] test: through a gateway a physical allocate, a later command and devices reach the worker's phone daemon (#874) --- src/agent-device/gateway-front.test.ts | 55 +++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index d80449d4c..725d635a4 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -47,6 +47,7 @@ const missingMessage = const tooOld = "refused: this agent-device is too old to use through a gateway; update it"; // why: shorter than the gateway's 10 s call timeout, so the read can finish once the fake clock moves past it. const slowCatalogMs = 8_000; +const phoneSerial = "R58Y61A60HN"; const defaultTtlMs = 600_000; const gatewayMaxTtlMs = 1_800_000; const workerMaxTtlMs = 50_000_000; @@ -89,6 +90,8 @@ interface WorkerSpec { readonly label: string; readonly platform?: "ios" | "android"; readonly model?: string; + // why: an Android worker with one enrolled, present phone, leased with `physical: true` through its phone daemon. + readonly phone?: boolean; readonly capability?: "available" | "off" | "unavailable"; readonly maxRunning?: number; // why: a standalone worker -- no gateway membership, its own HTTP port -- the way a worker without a gateway is; a joined worker may not enable HTTP. @@ -106,6 +109,7 @@ interface Member { readonly label: string; readonly daemon: Promise; readonly fake: FakeAgentDevice; + readonly phone: FakeAgentDevice; readonly driver: FakeDriver; readonly directory: string; readonly filesystem: Filesystem; @@ -165,6 +169,9 @@ function driverFor( latencyMs: latency, knownModels: [model], modelClasses: { [model]: "phone" }, + ...(spec.phone === true + ? { physicalDevices: [{ class: "phone", ids: [phoneSerial], model, osVersion: "15" }] } + : {}), platform: "android", }); } @@ -242,6 +249,7 @@ async function setUp(options: SetUpOptions = {}): Promise { if (existing === undefined) temporaryDirectories.push(workerDirectory); const workerFilesystem = existing?.filesystem ?? new MemoryFilesystem(); const fake = existing?.fake ?? new FakeAgentDevice(); + const phone = existing?.phone ?? new FakeAgentDevice(); if (spec.capability === "unavailable") fake.setUnavailable("down"); const latency: Record = spec.slowCatalog === true ? { listCatalog: slowCatalogMs } : {}; @@ -272,7 +280,7 @@ async function setUp(options: SetUpOptions = {}): Promise { level: "debug", sink: new MemoryLogSink(), }), - optionalModules: [agentDeviceModuleWith({ upstream: fake })], + optionalModules: [agentDeviceModuleWith({ phoneUpstream: phone, upstream: fake })], version: "1.2.3", } as StartDaemonOptions).then((daemon) => { runningDaemons.push(daemon); @@ -287,6 +295,7 @@ async function setUp(options: SetUpOptions = {}): Promise { filesystem: workerFilesystem, label: spec.label, latency, + phone, origin: directPort === undefined ? "" : `http://127.0.0.1:${String(directPort)}`, secret, spec, @@ -320,7 +329,11 @@ async function setUp(options: SetUpOptions = {}): Promise { }; for (const spec of options.workers ?? [{ label: "w1" }]) { const member = await addWorker(spec); - await member.daemon; + const worker = await member.daemon; + if (spec.phone === true) { + await worker.dispatch("device.add", { id: phoneSerial, platform: "android" }, adminSession); + member.driver.setPhysicalPresence(phoneSerial, true); + } } for (const member of members) if (member.spec.direct !== true) await untilRead(rig, member); return rig; @@ -816,6 +829,44 @@ describe("the agent-device front, through a gateway", { timeout: 60_000 }, () => expect(request?.input).toMatchObject({ requesterId: hex(1), requires: ["agent-device"] }); }); + it('through a gateway a physical allocate reaches the worker\'s phone daemon with `requires: ["agent-device"]`, a later command and `devices` follow, the reply carries `device.physical: true`, a phone daemon that is down answers `agent-device is not available on this simlock: phone daemon: ` with no lease, and after a gateway restart the live phone lease is adopted', async () => { + const down = await setUp({ workers: [{ label: "w1", phone: true, platform: "android" }] }); + first(down).phone.setUnavailable("down"); + + const refused = await envelopeOf( + await allocate(down, 1, { physical: true, platform: "android" }), + ); + + expect(refused.error?.message).toBe(`${notAvailable}phone daemon: down`); + expect(await fleetLeases(down)).toEqual([]); + + const rig = await setUp({ workers: [{ label: "w1", phone: true, platform: "android" }] }); + const member = first(rig); + const tap = tapDispatch(rig.gateway); + const answer = await envelopeOf( + await allocate(rig, 1, { physical: true, platform: "android" }), + ); + + expect(answer.result).toMatchObject({ + data: { lease: { device: { model: "Pixel 8", osVersion: "15", physical: true } } }, + }); + const request = tap.inputs.find((entry) => entry.operation === "lease.request"); + expect(request?.input).toMatchObject({ physical: true, requires: ["agent-device"] }); + expect(member.phone.rpcRequests("agent_device.lease.allocate")).toHaveLength(1); + expect(member.fake.rpcRequests("agent_device.lease.allocate")).toEqual([]); + await listedByGateway(rig, 1); + const reached = () => member.phone.rpcRequests("agent_device.command").length; + expect((await envelopeOf(await command(rig, "snapshot", 1))).error).toBeUndefined(); + expect(reached()).toBe(1); + member.phone.listDevices([{ id: phoneSerial, name: "the phone" }]); + expect(await listedNames(await command(rig, "devices", undefined))).toEqual(["the phone"]); + + await restarted(rig, member, 1); + expect((await envelopeOf(await command(rig, "snapshot", 1))).error).toBeUndefined(); + expect(member.fake.rpcRequests("agent_device.command")).toEqual([]); + expect(reached()).toBe(3); + }); + it('allocate through the gateway with `osVersion` ">=18" reaches the lease request with it and `requires: ["agent-device"]`, and the reply carries `data.lease.device`', async () => { const rig = await setUp(); const tap = tapDispatch(rig.gateway); From 28cf16e23da6a308c75dfcaa282e8920cb8855ed Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:45:14 +0200 Subject: [PATCH 16/28] feat(agent-device): a relayed request reaches the daemon of the lease it names (#874) --- src/agent-device/worker.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index d558624e6..c815b5fb8 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -59,19 +59,23 @@ function createAgentDeviceEdgeParts( // why: a relayed request's tenant is the gateway's prefixed principal, which the host treats as the requester, so the worker's own tokens never share a session with it. function agentDeviceRelayTarget( parts: AgentDeviceEdgeParts, -): (request: Request, tenant: string) => Promise { - return async (request, tenant) => { - const status = await parts.link.status(); +): (request: Request, tenant: string, leaseId: string | undefined) => Promise { + return async (request, tenant, leaseId) => { + const status = await parts.link.status(leaseId); if (status.state === "unavailable") { return frontReplyFor(request, notAvailable(status.reason)); } - return parts.link.forward(request, { - principal: tenant, - name: tenant, - role: "agent", - via: "relay", - ambient: false, - }); + return parts.link.forward( + request, + { + principal: tenant, + name: tenant, + role: "agent", + via: "relay", + ambient: false, + }, + leaseId, + ); }; } From 3dfe05a029fafeab3a250ddbee9e36b73f351719 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:45:19 +0200 Subject: [PATCH 17/28] test: a gateway adopts a live phone lease with the phone's address after a restart (#874) --- src/agent-device/gateway-front.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index 725d635a4..37fd826e2 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -865,6 +865,16 @@ describe("the agent-device front, through a gateway", { timeout: 60_000 }, () => expect((await envelopeOf(await command(rig, "snapshot", 1))).error).toBeUndefined(); expect(member.fake.rpcRequests("agent_device.command")).toEqual([]); expect(reached()).toBe(3); + const own = await envelopeOf( + await command(rig, "snapshot", 1, {}, { flags: { serial: phoneSerial } }), + ); + expect(own.error).toBeUndefined(); + expect(reached()).toBe(4); + const other = await envelopeOf( + await command(rig, "snapshot", 1, {}, { flags: { serial: "emulator-5554" } }), + ); + expect(other.error?.message).toBe(picksTheDevice); + expect(reached()).toBe(4); }); it('allocate through the gateway with `osVersion` ">=18" reaches the lease request with it and `requires: ["agent-device"]`, and the reply carries `data.lease.device`', async () => { From 65630749c921071a9ed5a3b56ecad7a99c14065e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:45:32 +0200 Subject: [PATCH 18/28] feat(agent-device): the gateway adopts a phone lease at the phone's enrolled id (#874) --- src/agent-device/gateway.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/agent-device/gateway.ts b/src/agent-device/gateway.ts index 5a8db08c2..7485b639b 100644 --- a/src/agent-device/gateway.ts +++ b/src/agent-device/gateway.ts @@ -96,14 +96,16 @@ function describeDevice( device: ReturnType[number], ): FleetLeaseFacts["listed"] { const { platform, model } = device.spec; - if (device.address === undefined || (platform !== "ios" && platform !== "android")) { + // why: a phone is reached by the id it was enrolled with, since it has no address of its own. + const address = device.spec.physical ? device.driverDeviceId : device.address; + if (address === undefined || (platform !== "ios" && platform !== "android")) { return undefined; } const deviceClass = view.catalog?.find((catalog) => catalog.platform === platform)?.modelClasses[ model ]; return { - address: device.address, + address, model, platform, ttlDeadline: record.ttlDeadline, From cdb5dfb5fdeb8e818fd0f4a27e16a901908fb6b2 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:48:46 +0200 Subject: [PATCH 19/28] test(e2e): agent-device leases a physical phone on the slow lane (#874) --- e2e/slow-agent-device-physical.test.ts | 149 +++++++++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 e2e/slow-agent-device-physical.test.ts diff --git a/e2e/slow-agent-device-physical.test.ts b/e2e/slow-agent-device-physical.test.ts new file mode 100644 index 000000000..40db4d21f --- /dev/null +++ b/e2e/slow-agent-device-physical.test.ts @@ -0,0 +1,149 @@ +import { randomBytes } from "node:crypto"; +import { existsSync } from "node:fs"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it, onTestFinished } from "vitest"; + +import { + assertPinnedAgentDevice, + freeLoopbackPort, + listLeases, + newAgentToken, + waitForAgentDevice, + waitForFree, + withSharedDaemon, + type SharedTestEnv, +} from "./helpers/index.js"; + +const MINUTE = 60_000; +const PNG_MAGIC = "89504e470d0a1a0a"; + +type Platform = "android" | "ios"; + +const ANDROID_SERIAL = process.env["SIMLOCK_PHYSICAL_ANDROID"]; +const IOS_UDID = process.env["SIMLOCK_PHYSICAL_IOS"]; +const IOS_SIGNING = { + bundleId: process.env["SIMLOCK_E2E_IOS_BUNDLE_ID"], + provisioningProfile: process.env["SIMLOCK_E2E_IOS_PROVISIONING_PROFILE"], + signingIdentity: process.env["SIMLOCK_E2E_IOS_SIGNING_IDENTITY"], + teamId: process.env["SIMLOCK_E2E_IOS_TEAM_ID"], +} as const; + +function unset(name: string, value: string | undefined): string | undefined { + return value === undefined || value === "" ? name : undefined; +} + +const missing = { + android: unset("SIMLOCK_PHYSICAL_ANDROID", ANDROID_SERIAL), + ios: + unset("SIMLOCK_PHYSICAL_IOS", IOS_UDID) ?? + unset("SIMLOCK_E2E_IOS_TEAM_ID", IOS_SIGNING.teamId) ?? + unset("SIMLOCK_E2E_IOS_BUNDLE_ID", IOS_SIGNING.bundleId) ?? + unset("SIMLOCK_E2E_IOS_PROVISIONING_PROFILE", IOS_SIGNING.provisioningProfile) ?? + unset("SIMLOCK_E2E_IOS_SIGNING_IDENTITY", IOS_SIGNING.signingIdentity), +} as const; + +interface RpcAnswer { + readonly result?: { readonly ok?: boolean; readonly data?: Record }; + readonly error?: { readonly message: string }; +} + +function defineSuite(platform: Platform, id: string): void { + const tag = platform === "android" ? "Android" : "iOS"; + describe.skipIf(missing[platform] !== undefined)( + missing[platform] === undefined + ? `agent-device with a physical ${tag} phone (real agent-device)` + : `agent-device with a physical ${tag} phone (skipped: ${missing[platform]} is not set)`, + { tags: ["slow", "physical", platform] }, + () => { + let env: SharedTestEnv; + let secret: string; + + const call = async (method: string, params: Record): Promise => { + const response = await fetch(`http://127.0.0.1:${env.httpPort}/v1/agent-device/rpc`, { + body: JSON.stringify({ id: 1, jsonrpc: "2.0", method, params }), + headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" }, + method: "POST", + signal: AbortSignal.timeout(6 * MINUTE), + }); + return (await response.json()) as RpcAnswer; + }; + + beforeAll(async () => { + const pinned = await assertPinnedAgentDevice(platform); + env = await withSharedDaemon({ + configOverrides: { + capabilities: { + "agent-device": { + command: pinned, + enabled: true, + ...(platform === "ios" ? { ios: IOS_SIGNING } : {}), + }, + }, + http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, + }, + driver: "real", + }); + const token = await newAgentToken(env); + secret = token.secret; + await waitForAgentDevice(env, secret); + const added = await env.cli(["device", "add", "--platform", platform, id, "--json"], { + timeout: 2 * MINUTE, + }); + expect(added.code, `device add failed: ${added.stderr}`).toBe(0); + }, 10 * MINUTE); + + afterAll(async () => { + await env?.teardown(); + }, 2 * MINUTE); + + it( + `a raw agent_device.lease.allocate with physical: true and platform: "${platform}" is granted that ${platform === "android" ? "serial" : "udid"}, a screenshot on the lease answers a PNG, and agent_device.lease.release releases the Simlock lease`, + { timeout: 15 * MINUTE }, + async () => { + const leaseId = randomBytes(16).toString("hex"); + const scope = { clientId: "slow-lane", leaseProvider: "proxy", runId: "slow-lane" }; + + const allocated = await call("agent_device.lease.allocate", { + ...scope, + leaseId, + physical: true, + platform, + ttlMs: 10 * MINUTE, + }); + + expect(allocated.error, JSON.stringify(allocated)).toBeUndefined(); + expect(allocated.result?.ok).toBe(true); + const [lease] = await listLeases(env); + expect(lease?.id).toBe(leaseId); + const devices = (await env.cli(["list", "--devices"])).json as { + readonly id: string; + readonly driverDeviceId: string; + }[]; + expect(devices.find((device) => device.id === lease?.deviceId)?.driverDeviceId).toBe(id); + + const dir = await mkdtemp(join(tmpdir(), "simlock-ad-phone-")); + onTestFinished(() => rm(dir, { force: true, recursive: true })); + const png = join(dir, "shot.png"); + const shot = await call("agent_device.command", { + command: "screenshot", + meta: { leaseId }, + positionals: [png], + }); + expect(shot.error, JSON.stringify(shot)).toBeUndefined(); + const named = shot.result?.data?.["path"]; + const written = existsSync(png) ? png : typeof named === "string" ? named : png; + expect((await readFile(written)).subarray(0, 8).toString("hex")).toBe(PNG_MAGIC); + + const released = await call("agent_device.lease.release", { ...scope, leaseId }); + expect(released.error, JSON.stringify(released)).toBeUndefined(); + await waitForFree(env); + }, + ); + }, + ); +} + +defineSuite("android", ANDROID_SERIAL ?? ""); +defineSuite("ios", IOS_UDID ?? ""); From be0a2b63bd6f6a1075828d5bd9fdc8fd6c4c2d4f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:48:51 +0200 Subject: [PATCH 20/28] docs(agent-device): phones are leased with --physical through the phone daemon (#874) --- ...ce-is-served-by-an-optional-edge-module.md | 2 +- docs/internal/adr/README.md | 2 +- docs/internal/agent-rules/toolchain.md | 1 + src/agent-device/AGENTS.md | 58 +++++++++---------- src/agent-device/front/host-link.ts | 18 +----- .../docs/docs/using-devices/agent-device.mdx | 9 ++- .../docs/using-devices/physical-devices.mdx | 2 +- 7 files changed, 41 insertions(+), 51 deletions(-) diff --git a/docs/internal/adr/0023-agent-device-is-served-by-an-optional-edge-module.md b/docs/internal/adr/0023-agent-device-is-served-by-an-optional-edge-module.md index 821072e8a..268e2a6e4 100644 --- a/docs/internal/adr/0023-agent-device-is-served-by-an-optional-edge-module.md +++ b/docs/internal/adr/0023-agent-device-is-served-by-an-optional-edge-module.md @@ -1,6 +1,6 @@ # 0023. agent-device is served by an optional edge module, and the simlock lease is the only clock -- **Status:** Accepted +- **Status:** Accepted; §1 narrowed by 0026 for gateway mode; §3 narrowed by 0030 (no reap while turned off); §3–4 superseded in part by [ADR 0043](0043-physical-devices-reach-agent-device-through-a-second-daemon.md) - **Date:** 2026-10-12 - **Issue:** [#466](https://github.com/callstackincubator/simlock/issues/466) - **Supersedes:** nothing. Builds on [ADR 0020](0020-a-requester-may-choose-its-lease-id.md) diff --git a/docs/internal/adr/README.md b/docs/internal/adr/README.md index a5e77b962..f9036462f 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -61,7 +61,7 @@ the status is stale. | [0020](0020-a-requester-may-choose-its-lease-id.md) | A requester may choose its lease id, and the gateway passes it through bare | Accepted | | [0021](0021-a-gateway-dispatch-is-a-probe-and-names-its-fleet-request.md) | A gateway dispatch is a probe, and the gateway records every fleet request's outcome | Accepted — partly implemented: §5 (usage figures) is not built | | [0022](0022-a-physical-device-is-a-second-device-type-the-core-knows.md) | A physical device is a second device type the core knows | Proposed; amends 0001 §3 and §5, 0015 §3 and 0019 §1–2 for physical devices | -| [0023](0023-agent-device-is-served-by-an-optional-edge-module.md) | agent-device is served by an optional edge module, and the simlock lease is the only clock | Accepted; §1 narrowed by 0026 for gateway mode; §3 narrowed by 0030 (no reap while turned off) | +| [0023](0023-agent-device-is-served-by-an-optional-edge-module.md) | agent-device is served by an optional edge module, and the simlock lease is the only clock | Accepted; §1 narrowed by 0026 for gateway mode; §3 narrowed by 0030 (no reap while turned off); §3–4 superseded in part by 0043 | | [0024](0024-leasing-calls-lease-end-participants-before-reclaim.md) | Leasing calls lease-end participants before it reclaims a device | Accepted | | [0025](0025-simlock-ships-android-profiles-and-a-model-pairs-only-with-images-that-fit.md) | Simlock ships Android device profiles, and a model pairs only with images that fit it | Accepted | | [0026](0026-agent-device-through-a-gateway-relays-over-the-uplink.md) | agent-device through a gateway: workers advertise capabilities, and the host link relays over the uplink | Accepted; §2 narrowed by 0028 for relayed bodies | diff --git a/docs/internal/agent-rules/toolchain.md b/docs/internal/agent-rules/toolchain.md index c47fb9621..774dfac0e 100644 --- a/docs/internal/agent-rules/toolchain.md +++ b/docs/internal/agent-rules/toolchain.md @@ -150,6 +150,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 `642.` followed by a number (streaming a phone needs Xcode 27's CoreDevice; 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` | | 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` | +| 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`, `SIMLOCK_E2E_IOS_BUNDLE_ID`, `SIMLOCK_E2E_IOS_PROVISIONING_PROFILE` and `SIMLOCK_E2E_IOS_SIGNING_IDENTITY` (in `.slow-lane.env`). 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/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index edc5595e4..2b300ddd1 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -8,29 +8,29 @@ Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no ## Files -| File | Role | -| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| `definition.ts` | `agentDeviceModule`: config, defaults, cap check; loads `worker.ts` only when on | -| `worker.ts` | `createWorker`: both supervisors, edge parts, capability, relay target, mount, hooks | -| `host/agent-device-supervisor.ts` | Reap, start, watch, stop one role's daemon (`simulators` or `phones`); availability state | -| `host/install.ts` | `findAgentDevice`: command → install root → daemon entry | -| `host/health.ts` | `NodeAgentDeviceHealthProbe`: `GET /health`, 5 s | -| `host/availability-findings.ts` | `agentDeviceFindings` for `simlock doctor`; a phone daemon's message starts `phone daemon: ` | -| `host/upstream.ts` | `AgentDeviceUpstream` port; `SupervisorAgentDeviceUpstream` | -| `host/host.ts` | `AgentDeviceHost`: `@agent-device/proxy`, tenant, 2 GiB download cap | -| `host/lease-end.ts` | `ReleaseScopeRecord`, `AgentDeviceLeaseEnd` (lease-end participant) | -| `front/front.ts` | The mount: role check, routes, `/rpc` dispatch by call class | -| `front/request-rules.ts` | Refusals and rewrites before anything is forwarded | -| `front/allocate.ts`, `front/heartbeat.ts`, `front/release.ts` | Lease calls ↔ simlock `lease.*` | -| `front/renewals.ts` | Renews the simlock lease while a command runs | -| `front/front-map.ts` | In-memory leases this front made, and who ended each | -| `front/devices-filter.ts`, `front/token-devices.ts` | `devices` cut to the token's leases | -| `front/host-link.ts` | `HostLink` port (`stillHeld`: gateway only, a lease its `lease.list` omits is ended only when the index lost it); `InProcessHostLink` (worker) | -| `front/relay-host-link.ts` | `RelayHostLink` (gateway); `FleetPort` | -| `front/edge-parts.ts` | Front parts, dispose and cancel steps, `createAgentDeviceFront` | -| `gateway.ts` | Gateway side: `FleetPort` from the gateway context, the mount, `beforeDrain` | -| `shared/` | Paths, routes, RPC reader, replies, compatibility, daemon env, release scope | -| `testing.ts` | `FakeAgentDevice` (in-memory daemon), `FakeAgentDeviceHealth` | +| File | Role | +| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `definition.ts` | `agentDeviceModule`: config, defaults, cap check; loads `worker.ts` only when on | +| `worker.ts` | `createWorker`: both supervisors, edge parts, capability, relay target, mount, hooks | +| `host/agent-device-supervisor.ts` | Reap, start, watch, stop one role's daemon (`simulators` or `phones`); availability state | +| `host/install.ts` | `findAgentDevice`: command → install root → daemon entry | +| `host/health.ts` | `NodeAgentDeviceHealthProbe`: `GET /health`, 5 s | +| `host/availability-findings.ts` | `agentDeviceFindings` for `simlock doctor`; a phone daemon's message starts `phone daemon: ` | +| `host/upstream.ts` | `AgentDeviceUpstream` port; `SupervisorAgentDeviceUpstream` | +| `host/host.ts` | `AgentDeviceHost`: `@agent-device/proxy`, tenant, 2 GiB download cap | +| `host/lease-end.ts` | `ReleaseScopeRecord`, `AgentDeviceLeaseEnd` (lease-end participant, one per daemon) | +| `front/front.ts` | The mount: role check, routes, `/rpc` dispatch by call class | +| `front/request-rules.ts` | Refusals and rewrites before anything is forwarded | +| `front/allocate.ts`, `front/heartbeat.ts`, `front/release.ts` | Lease calls ↔ simlock `lease.*` | +| `front/renewals.ts` | Renews the simlock lease while a command runs | +| `front/front-map.ts` | In-memory leases this front made, and who ended each | +| `front/devices-filter.ts`, `front/token-devices.ts` | `devices` cut to the token's leases | +| `front/host-link.ts` | `HostLink` port (`stillHeld`: gateway only, a lease its `lease.list` omits is ended only when the index lost it); `RoutedHostLink` (worker: one host per daemon, a lease → daemon map) | +| `front/relay-host-link.ts` | `RelayHostLink` (gateway); `FleetPort` | +| `front/edge-parts.ts` | Front parts, dispose and cancel steps, `createAgentDeviceFront` | +| `gateway.ts` | Gateway side: `FleetPort` from the gateway context, the mount, `beforeDrain` | +| `shared/` | Paths, routes, RPC reader, replies, compatibility, daemon env, release scope | +| `testing.ts` | `FakeAgentDevice` (in-memory daemon), `FakeAgentDeviceHealth` | ## How it works @@ -41,7 +41,7 @@ its env has no simulator set or driver lease key, `ANDROID_ADB_SERVER_PORT=5037` `AGENT_DEVICE_IOS_*` signing keys (`capabilities.agent-device.ios.*`), and the no-iOS and no-Android sentinels when a platform is off. It starts once the simulator daemon's start has settled, never awaited. The capability follows the simulator daemon; doctor lists a finding per -daemon. Nothing is routed to the phone daemon yet. +daemon. `RoutedHostLink` sends a physical allocate (its `serial`/`udid` is an enrolled phone's id) and every later call for that lease to the phone daemon, everything else to the simulator daemon; a phone daemon that is not running answers `phone daemon: `. Each daemon has its own `ReleaseScopeRecord` and `AgentDeviceLeaseEnd`; the link forgets a lease when it ends. Supervisor start (`AgentDeviceSupervisor.start`, at daemon start), per role: @@ -91,13 +91,13 @@ under leasing's signal (`lease.endWaitMs`). ## Flow: agent on a worker 1. CLI `open` → `POST /v1/agent-device/rpc` `agent_device.lease.allocate` with its lease id. -2. Front refuses a non-plain lease, no `--platform`, a bad `ttlMs`, no lease id, `physical: true`, or a `--target` it does not map. +2. Front refuses a non-plain lease, no `--platform`, a bad `ttlMs`, no lease id, a `physical` that is not a boolean, or a `--target` it does not map. 3. `lease.request`: `leaseId` = `requesterId` = the CLI's lease id; `--device` → model, - `--target` → class, `--os` → `osVersion`, `--image-tag` → `imageTag`; TTL = sent, capped by `capabilities.agent-device.leaseTtlCapMs`, at least 5 s; + `--target` → class, `--os` → `osVersion`, `--image-tag` → `imageTag`, `physical: true` → `physical: true` (Simlock picks an enrolled phone); TTL = sent, capped by `capabilities.agent-device.leaseTtlCapMs`, at least 5 s; queue wait 330 s. CLI hangs up → `lease.cancel`, retried every 1 s. -4. Grant → allocate forwarded with the device address (`udid`/`serial`), no +4. Grant → allocate forwarded with the device address (`udid`/`serial`; a phone's is its enrolled id), to the phone daemon for a phone and the simulator daemon otherwise (`RoutedHostLink`, which remembers each lease's daemon until the lease ends), no `device`/`deviceKey`/`target`/`osVersion`/`imageTag` (commands lose both keys too), `ttlMs` = max(24 h, 2 × `lease.maxTtlMs`). -5. agent-device error → simlock lease released. Success → front map entry; reply relayed with `data.lease.device` `{ model, osVersion, imageTag? }` added from the grant. +5. agent-device error → simlock lease released. Success → front map entry; reply relayed with `data.lease.device` `{ model, osVersion, physical, imageTag? }` added from the grant. 6. Commands carry the lease id; rules check, renewals run, `devices` filtered. 7. Release → agent-device first, then `lease.release` → reclaim; lease-end finds no scope left. @@ -109,7 +109,7 @@ under leasing's signal (`lease.endWaitMs`). 3. Every later call is relayed to the lease's worker (`FleetPort.relay` → `GatewayRelay`, target `agent-device`) with tenant `gw..`, cut to 128 chars with a hash. A lease not the token's → 403. No lease: only `GET /health`. -4. Worker: `agentDeviceRelayTarget` → `InProcessHostLink` → host, requester = tenant. +4. Worker: `agentDeviceRelayTarget` → `RoutedHostLink` (the lease id picks the phone daemon or the simulator daemon) → host, requester = tenant. No front rules run on the worker. 5. Worker unreachable → "try again" reply; a command so answered ends its renewal reference without releasing the lease or ending worker work. Other live commands diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index 87d4f7a01..fd8a0a77b 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -29,13 +29,13 @@ export interface AdoptableLease { } export interface HostLink { - // why: only a link that serves many hosts routes non-RPC requests by the lease header and fans out `devices`; a worker never reads the header. + // why: only a link that serves many hosts routes non-RPC requests by the lease header and fans out `devices`; the gateway's link and a worker's routed link do. readonly readsLeaseHeader: boolean; // why: capabilities a lease request must require so it lands on a host that can serve agent-device; none means any worker. readonly leaseRequires?: readonly string[]; status(leaseId?: string, identity?: Identity): Promise; forward(request: Request, identity: Identity, leaseId?: string): Promise; - // why: only a link that serves many hosts adopts leases made before the front's map was empty; a worker's map is in memory and has no entry for a lease it made before a restart, but that lease is ended, not adopted. + // why: only the gateway's link adopts leases made before the front's map was empty; a worker's map is in memory and has no entry for a lease it made before a restart, but that lease is ended, not adopted. adoptable?(identity: Identity): readonly AdoptableLease[]; // why: a lease the front asked for in this process is its allocate's to keep or release, never to adopt. asked?(leaseId: string): void; @@ -44,20 +44,6 @@ export interface HostLink { dispose?(): void; } -export class InProcessHostLink implements HostLink { - readonly readsLeaseHeader = false; - - constructor(private readonly host: AgentDeviceHost) {} - - status(): ReturnType { - return this.host.status(); - } - - forward(request: Request, identity: Identity): Promise { - return this.host.forward(request, identity); - } -} - interface RoutedHosts { readonly simulators: AgentDeviceHost; readonly phones: AgentDeviceHost; diff --git a/website/src/content/docs/docs/using-devices/agent-device.mdx b/website/src/content/docs/docs/using-devices/agent-device.mdx index e909c9c8b..e0de382d8 100644 --- a/website/src/content/docs/docs/using-devices/agent-device.mdx +++ b/website/src/content/docs/docs/using-devices/agent-device.mdx @@ -7,7 +7,7 @@ import { Steps, Aside } from '@astrojs/starlight/components'; [agent-device](https://github.com/callstack/agent-device) is Callstack's command-line tool for driving mobile apps: it opens an app, reads the screen as a tree of elements, taps, types and takes screenshots. With Simlock, `agent-device open` leases a simulator or emulator from Simlock, and every later command goes to that device. Each agent gets its own device, and a device is wiped when the agent closes it. -Simlock runs two agent-device daemons on each worker and watches both: one over the simulators and emulators Simlock leases, and a phone daemon beside it that sees the phones plugged into the host. The phone daemon needs the iOS signing values agent-device uses for an iPhone, set with `simlock config set capabilities.agent-device.ios.teamId ` (also `bundleId`, `provisioningProfile` and `signingIdentity`), and takes effect on daemon restart. If it cannot start, `simlock doctor` prints a line starting `phone daemon:`; the simulator daemon and the worker's agent-device status are not affected. Agents cannot use the phone daemon yet. Agents reach it over HTTP, on the worker or through a gateway, with a Simlock agent token. +Simlock runs two agent-device daemons on each worker and watches both: one over the simulators and emulators Simlock leases, and a phone daemon beside it that sees the phones plugged into the host. The phone daemon needs the iOS signing values agent-device uses for an iPhone, set with `simlock config set capabilities.agent-device.ios.teamId ` (also `bundleId`, `provisioningProfile` and `signingIdentity`), and takes effect on daemon restart. If it cannot start, `simlock doctor` prints a line starting `phone daemon:`; the simulator daemon and the worker's agent-device status are not affected. Agents lease a phone through it with `--physical`. Agents reach agent-device over HTTP, on the worker or through a gateway, with a Simlock agent token. ## Before you start @@ -21,7 +21,9 @@ On each agent's machine: - agent-device 0.21.28 or later. An older CLI is refused with `refused: this agent-device is too old for simlock; upgrade it`. - Its own Simlock agent token. Simlock tells agents apart by token: two agents that share a token share one agent-device session and see each other's devices. -agent-device through Simlock drives simulators and emulators. It does not lease physical devices. +agent-device through Simlock drives simulators, emulators and, with `--physical`, phones enrolled in Simlock (see [Physical devices](/simlock/docs/using-devices/physical-devices)). `open --physical` leases an enrolled phone: the command goes to the phone daemon and the reply names the device with `physical: true`. Simlock picks the phone, so name no `--udid` or `--serial`. + +The phone daemon runs `adb` without Simlock's version check, so its `adb` must come from the same Android SDK (platform-tools) as Simlock's. ## Turn it on @@ -124,12 +126,13 @@ Restarting a worker's daemon ends every agent-device lease on that worker, even | `refused: name --platform ios or android` | `open` needs `--platform`. | | `refused: simlock picks the device` | A `--udid`, `--serial` or `--device` names a device that is not the one Simlock leased to you. | | `refused: simlock chooses the device set; run disconnect, then connect proxy without --ios-simulator-device-set` | Simlock decides which devices agent-device sees. | -| `refused: physical devices are not available through agent-device` | `open` asked for a physical device; agent-device leases only simulators and emulators through Simlock. | +| `refused: malformed physical` | `physical` was not true or false. | | `refused: unknown --target ; use mobile, tv or desktop` | `--target` named a device class Simlock does not map. | | `refused: malformed osVersion`, `refused: malformed imageTag` | `--os` or `--image-tag` was not a string. | | `refused by simlock: ` | Simlock refused the lease, for example a model it does not know, an OS range it cannot read, or an image tag on iOS. | | `refused: this agent-device is too old to use through a gateway; update it` | Upgrade the agent's agent-device. | | `agent-device is not available on this simlock: ` | agent-device is missing, too old, starting or crashed on the worker. | +| `agent-device is not available on this simlock: phone daemon: ` | `open --physical`, or a command on a phone lease, found the phone daemon starting or down. Simulator leases keep working; `simlock doctor` prints the phone daemon's finding. | ## Related 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 487d2b5ff..adac9c513 100644 --- a/website/src/content/docs/docs/using-devices/physical-devices.mdx +++ b/website/src/content/docs/docs/using-devices/physical-devices.mdx @@ -106,7 +106,7 @@ When the device is back, Simlock cleans it and it can be leased again. A request ## Screen and UI automation - To watch a physical device's screen in the console, see [Watching the screen](/simlock/docs/using-devices/watching-the-screen). A physical iPhone needs iOS 27 or later. -- agent-device drives simulators and emulators only. See [agent-device](/simlock/docs/using-devices/agent-device). +- agent-device can drive an enrolled phone: `open --physical` leases one through Simlock. See [agent-device](/simlock/docs/using-devices/agent-device). ## Related From baed6e7bd070bf02ec07c7914fa16de2a8504975 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:49:36 +0200 Subject: [PATCH 21/28] refactor(agent-device): split the routed link's role lookup (#874) --- src/agent-device/front/host-link.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index fd8a0a77b..0a7fd78a2 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -94,19 +94,22 @@ export class RoutedHostLink implements HostLink { async #roleOf(request: Request, leaseId: string | undefined): Promise { const known = leaseId === undefined ? undefined : this.#roles.get(leaseId); if (known !== undefined) return known; + if (!(await this.#allocatesPhone(request))) return "simulators"; + if (leaseId !== undefined) this.#roles.set(leaseId, "phones"); + return "phones"; + } + + async #allocatesPhone(request: Request): Promise { if (request.method !== "POST" || new URL(request.url).pathname !== `${FRONT_PREFIX}/rpc`) { - return "simulators"; + return false; } const read = await readRpcBody(request.clone()); if (read.kind !== "request" || classifyCall(read.method, read.params) !== "allocate") { - return "simulators"; + return false; } const address = read.params["serial"] ?? read.params["udid"]; - const phone = this.registry.snapshot.devices.some( + return this.registry.snapshot.devices.some( (device) => device.physical && device.driverDeviceId === address, ); - if (!phone) return "simulators"; - if (leaseId !== undefined) this.#roles.set(leaseId, "phones"); - return "phones"; } } From 239675f8cf1e9e455724b0ff55d404193d8e200a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:51:35 +0200 Subject: [PATCH 22/28] docs(adr): list ADR 0041 before 0043 in the index (#874) --- docs/internal/adr/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/internal/adr/README.md b/docs/internal/adr/README.md index f9036462f..3c36c29be 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -79,5 +79,5 @@ the status is stale. | [0038](0038-the-warm-pool-learns-its-kinds-from-leases-and-boots-for-every-queued-request.md) | The warm pool learns its kinds from leases, and boots for every queued request | Accepted — not yet implemented | | [0039](0039-joined-workers-refuse-their-own-http-listener.md) | Joined workers refuse their own HTTP listener | Accepted — not yet implemented | | [0040](0040-every-http-route-is-declared-once-and-the-openapi-document-is-built-from-the-declarations.md) | Every HTTP route is declared once, and the OpenAPI document is built from the declarations | Accepted — not yet implemented | -| [0043](0043-physical-devices-reach-agent-device-through-a-second-daemon.md) | Physical devices reach agent-device through a second daemon on the worker | Accepted — not yet implemented; supersedes 0023 §3–4 in part | | [0041](0041-the-daemon-can-run-under-the-users-service-manager.md) | The daemon can run under the user's service manager | Accepted — not yet implemented | +| [0043](0043-physical-devices-reach-agent-device-through-a-second-daemon.md) | Physical devices reach agent-device through a second daemon on the worker | Accepted — not yet implemented; supersedes 0023 §3–4 in part | From 6ca2d20a02ce8d29df61a522bc7f6297fb9dee39 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:58:24 +0200 Subject: [PATCH 23/28] test(agent-device): a virtual allocate whose address is its driver id stays on the simulator daemon; a phone lease's down daemon answers before the rules (#874) --- src/agent-device/edge.test.ts | 34 ++++++++++++++++++++++++++++++++++ src/core/fake-driver.ts | 21 ++++++++++++++++++--- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 962492071..bad745069 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -950,6 +950,12 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(liveCommand.error).toMatchObject( refusal(`${notAvailable}phone daemon: starting`, "COMMAND_FAILED"), ); + const beforeRules = await envelopeOf( + await runCommand(live, "snapshot", 1, { flags: { serial: "emulator-9999" } }), + ); + expect(beforeRules.error).toMatchObject( + refusal(`${notAvailable}phone daemon: starting`, "COMMAND_FAILED"), + ); const simulatorsDown = await setUpWithPhone(); simulatorsDown.fake.setUnavailable("found 0.20.3"); @@ -1023,6 +1029,34 @@ describe("the agent-device front, through the whole worker daemon", () => { } }); + it("a virtual allocate whose address is also its driver id reaches the simulator daemon, not the phone daemon", async () => { + const rig = await setUp({ + drivers: (clock) => [ + new FakeDriver({ + addressIsDeviceId: true, + availableOsVersions: ["35"], + clock, + defaultModels: { phone: ["Pixel 8"] }, + knownModels: ["Pixel 8"], + modelClasses: { "Pixel 8": "phone" }, + physicalDevices: [ + { class: "phone", ids: [phoneSerial], model: "Pixel 8", osVersion: "15" }, + ], + platform: "android", + }), + ], + }); + await rig.daemon.dispatch("device.add", { id: phoneSerial, platform: "android" }, adminSession); + rig.driver.setPhysicalPresence(phoneSerial, true); + + await granted(rig, 1, { platform: "android" }); + + expect(rig.fake.rpcRequests("agent_device.lease.allocate")).toMatchObject([ + { params: { leaseId: hex(1), serial: expect.stringMatching(/^fake-android-/) } }, + ]); + expect(rig.phone.rpcRequests("agent_device.lease.allocate")).toEqual([]); + }); + it("after a phone lease ends, an allocate that reuses its lease id for a virtual device reaches the simulator daemon", async () => { const rig = await setUpWithPhone(); await granted(rig, 1, { physical: true, platform: "android" }); diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 4cee1743d..3abd9fccb 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -145,6 +145,11 @@ export interface FakeDriverOptions { readonly reclaimResult?: "ready" | "shutdown"; readonly reclaimStrategy?: "erase" | "snapshot" | "wipe"; readonly physicalDevices?: readonly FakePhysicalDevice[]; + /** + * why: a real iOS simulator is addressed by its device id; set it to give a virtual device that + * address, so a test can tell a virtual device from a phone by more than the id. + */ + readonly addressIsDeviceId?: boolean; } export class FakeDriverUnknownDeviceError extends Error { @@ -201,6 +206,7 @@ export class FakeDriver implements Driver { readonly #legacyDevices: Map; /** Bumped on every `makeReady` boot -- mirrors a real driver reassigning a port per boot. */ readonly #bootCounts = new Map(); + readonly #addressIsDeviceId: boolean; #managedReality: DriverReality | undefined; #physicalDevices: readonly FakePhysicalDevice[] | undefined; readonly #presentPhysical = new Set(); @@ -211,6 +217,7 @@ export class FakeDriver implements Driver { readonly #scriptedPhysicalDevices: FakeDriverOptions["physicalDevices"]; constructor(options: FakeDriverOptions) { + this.#addressIsDeviceId = options.addressIsDeviceId === true; this.#availableOsVersions = new Set(options.availableOsVersions ?? ["latest"]); this.#clock = options.clock; this.#estimateMs = options.estimateMs; @@ -444,6 +451,10 @@ export class FakeDriver implements Driver { }); } + #addressOf(deviceId: string, bootCount: number): string { + return this.#addressIsDeviceId ? deviceId : addressFor(deviceId, bootCount); + } + async provision(spec: VirtualSpec): Promise { await this.#beforeCall("provision", spec); this.#assertMatchingPlatform(spec.platform); @@ -452,7 +463,11 @@ export class FakeDriver implements Driver { this.#nextDeviceNumber += 1; this.#devices.set(deviceId, "provisioned"); - return { address: addressFor(deviceId, 0), deviceId, driverData: { fakeDeviceId: deviceId } }; + return { + address: this.#addressOf(deviceId, 0), + deviceId, + driverData: { fakeDeviceId: deviceId }, + }; } /** @@ -478,7 +493,7 @@ export class FakeDriver implements Driver { const bootCount = (this.#bootCounts.get(device.deviceId) ?? 0) + 1; this.#bootCounts.set(device.deviceId, bootCount); return { - address: addressFor(device.deviceId, bootCount), + address: this.#addressOf(device.deviceId, bootCount), deviceId: device.deviceId, driverData: device.driverData, ...this.#reportedMode(options), @@ -540,7 +555,7 @@ export class FakeDriver implements Driver { } return { devices: [...this.#devices.entries()].map(([deviceId, status]) => ({ - address: addressFor(deviceId, this.#bootCounts.get(deviceId) ?? 0), + address: this.#addressOf(deviceId, this.#bootCounts.get(deviceId) ?? 0), deviceId, driverData: { fakeDeviceId: deviceId }, runState: runStateFor(status), From 3b9e6667ac32e3d7e80ec0aef27936f96cd45a43 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 11:30:32 +0200 Subject: [PATCH 24/28] test(agent-device): the header-routing title says the lease id picks the daemon whichever token sends it (#874) --- src/agent-device/edge.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index bad745069..81bcfbe26 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -1853,7 +1853,7 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(rig.fake.uploads).toEqual(["artifact bytes"]); }); - it("on a worker, an upload preflight and an artifact download follow the `x-agent-device-lease-id` header to the daemon of the lease it names, go to the simulator daemon with no header or another token's lease, and a malformed header is refused `the x-agent-device-lease-id header is not a lease id`", async () => { + it("on a worker, an upload preflight and an artifact download follow the `x-agent-device-lease-id` header to the daemon of the lease it names, go to the simulator daemon with no header, and a header naming a lease routes by the lease id whichever token sends it, and a malformed header is refused `the x-agent-device-lease-id header is not a lease id`", async () => { const rig = await setUpWithPhone(); await granted(rig, 1, { physical: true, platform: "android" }); await granted(rig, 2, { platform: "android" }); From 19ab1ffe9056db0f6b16d4cf7504c9cfc795a92b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:08:51 +0200 Subject: [PATCH 25/28] fix(agent-device): a phone call drops the simulator daemon's instance pins and the phone daemon no longer receives physical (#874) --- e2e/slow-agent-device-physical.test.ts | 25 +++++++++++++++++++++++- src/agent-device/AGENTS.md | 4 ++-- src/agent-device/edge.test.ts | 27 ++++++++++++++++++++++++++ src/agent-device/front/allocate.ts | 1 + src/agent-device/front/host-link.ts | 7 +++++++ 5 files changed, 61 insertions(+), 3 deletions(-) diff --git a/e2e/slow-agent-device-physical.test.ts b/e2e/slow-agent-device-physical.test.ts index 40db4d21f..80e945446 100644 --- a/e2e/slow-agent-device-physical.test.ts +++ b/e2e/slow-agent-device-physical.test.ts @@ -60,10 +60,33 @@ function defineSuite(platform: Platform, id: string): void { let env: SharedTestEnv; let secret: string; + // why: the agent-device CLI reads `/health` before any lease and sends its two instance ids on every RPC; a lease on the phone daemon must accept them. + const pins = async (): Promise> => { + const response = await fetch(`http://127.0.0.1:${env.httpPort}/v1/agent-device/health`, { + headers: { authorization: `Bearer ${secret}` }, + }); + const health = (await response.json()) as { + readonly instanceId?: string; + readonly upstream?: { readonly instanceId?: string }; + }; + return { + ...(health.instanceId === undefined + ? {} + : { "x-agent-device-instance": health.instanceId }), + ...(health.upstream?.instanceId === undefined + ? {} + : { "x-agent-device-upstream-instance": health.upstream.instanceId }), + }; + }; + const call = async (method: string, params: Record): Promise => { const response = await fetch(`http://127.0.0.1:${env.httpPort}/v1/agent-device/rpc`, { body: JSON.stringify({ id: 1, jsonrpc: "2.0", method, params }), - headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" }, + headers: { + authorization: `Bearer ${secret}`, + "content-type": "application/json", + ...(await pins()), + }, method: "POST", signal: AbortSignal.timeout(6 * MINUTE), }); diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 2b300ddd1..26ef40099 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -96,7 +96,7 @@ under leasing's signal (`lease.endWaitMs`). `--target` → class, `--os` → `osVersion`, `--image-tag` → `imageTag`, `physical: true` → `physical: true` (Simlock picks an enrolled phone); TTL = sent, capped by `capabilities.agent-device.leaseTtlCapMs`, at least 5 s; queue wait 330 s. CLI hangs up → `lease.cancel`, retried every 1 s. 4. Grant → allocate forwarded with the device address (`udid`/`serial`; a phone's is its enrolled id), to the phone daemon for a phone and the simulator daemon otherwise (`RoutedHostLink`, which remembers each lease's daemon until the lease ends), no - `device`/`deviceKey`/`target`/`osVersion`/`imageTag` (commands lose both keys too), `ttlMs` = max(24 h, 2 × `lease.maxTtlMs`). + `device`/`deviceKey`/`target`/`osVersion`/`imageTag`/`physical` (commands lose both keys too), `ttlMs` = max(24 h, 2 × `lease.maxTtlMs`). 5. agent-device error → simlock lease released. Success → front map entry; reply relayed with `data.lease.device` `{ model, osVersion, physical, imageTag? }` added from the grant. 6. Commands carry the lease id; rules check, renewals run, `devices` filtered. 7. Release → agent-device first, then `lease.release` → reclaim; lease-end finds no scope left. @@ -144,5 +144,5 @@ renewals and release scopes: memory only. ## Known gaps - **A daemon restart loses agent-device leases.** The next heartbeat answers ended by - simlock and the simlock lease is released. + simlock and the simlock lease is released. A call on a phone lease drops the client's `x-agent-device-instance` and `x-agent-device-upstream-instance` pins (`front/host-link.ts`), which name the simulator daemon the client read `/health` from; so this holds for the phone daemon too. - **Agents sharing a token share a tenant**, and see each other's sessions. diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 81bcfbe26..29e9970a0 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -882,6 +882,10 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(rig.phone.rpcRequests("agent_device.lease.allocate")).toMatchObject([ { params: { leaseId: hex(1), ...address } }, ]); + // why: agent-device's daemon refuses any spec key it receives, so `physical` stays with simlock. + expect(rig.phone.rpcRequests("agent_device.lease.allocate")[0]?.params).not.toHaveProperty( + "physical", + ); expect(allocatesReceived(rig)).toEqual([]); } }); @@ -1006,6 +1010,29 @@ describe("the agent-device front, through the whole worker daemon", () => { ); }); + it("a client that sends the instance headers of the health it read, as the agent-device CLI does, is granted a phone and its later calls on that phone lease reach the phone daemon", async () => { + const rig = await setUpWithPhone(); + const health = (await (await send(rig, "/health")).json()) as { instanceId: string }; + const pinned = { + headers: { + "x-agent-device-instance": health.instanceId, + "x-agent-device-upstream-instance": "upstream-from-health", + }, + }; + + const allocated = await envelopeOf( + await allocate(rig, 1, { physical: true, platform: "android" }, pinned), + ); + const later = await envelopeOf(await command(rig, "snapshot", 1, pinned)); + const beat = await envelopeOf(await heartbeat(rig, 1, {}, pinned)); + + expect(allocated.result).toMatchObject({ ok: true }); + expect(later.error).toBeUndefined(); + expect(beat.error).toBeUndefined(); + expect(rig.phone.rpcRequests("agent_device.command")).toHaveLength(1); + expect(rig.phone.rpcRequests("agent_device.lease.heartbeat")).toHaveLength(1); + }); + it("when simlock ends a phone lease (presence lost, an operator's release of all) the release reaches the phone daemon, not the simulator daemon, and the agent's next heartbeat answers ended by simlock", async () => { const endings = [ async (rig: Rig) => { diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index f10864c1c..aac048b09 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -270,6 +270,7 @@ function forwardedBody( deviceKey: _deviceKey, imageTag: _imageTag, osVersion: _osVersion, + physical: _physical, target: _target, ...rest } = call.params; diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index 0a7fd78a2..c5530754e 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -51,6 +51,12 @@ interface RoutedHosts { type Role = keyof RoutedHosts; +// why: a client reads `/health` before it names a lease, so it pins the simulator daemon's proxy and daemon ids; the phone daemon's differ and would refuse every phone call, so a phone call carries no pin and a phone-daemon restart ends the lease at its next heartbeat, as a simulator-daemon restart does. +function dropInstancePins(request: Request): void { + request.headers.delete("x-agent-device-instance"); + request.headers.delete("x-agent-device-upstream-instance"); +} + // why: a worker runs one agent-device daemon for simulators and one for phones; this link holds a host for each and remembers which daemon each lease was allocated on. export class RoutedHostLink implements HostLink { readonly readsLeaseHeader = true; @@ -74,6 +80,7 @@ export class RoutedHostLink implements HostLink { if (status.state === "unavailable") { return frontReplyFor(request, notAvailable(status.reason)); } + dropInstancePins(request); } return this.hosts[role].forward(request, identity); } From 11de40afd50cdd289873db2517e1f58cf11fe8d8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:20:35 +0200 Subject: [PATCH 26/28] fix(e2e): an iPhone signs automatically with team and bundle ids; profile and identity are for manual signing (#874) --- docs/internal/agent-rules/toolchain.md | 2 +- e2e/slow-agent-device-physical.test.ts | 15 +++++++++------ src/agent-device/AGENTS.md | 2 +- .../content/docs/docs/reference/configuration.mdx | 4 ++-- .../docs/docs/using-devices/agent-device.mdx | 2 +- 5 files changed, 14 insertions(+), 11 deletions(-) diff --git a/docs/internal/agent-rules/toolchain.md b/docs/internal/agent-rules/toolchain.md index 774dfac0e..f19a2b194 100644 --- a/docs/internal/agent-rules/toolchain.md +++ b/docs/internal/agent-rules/toolchain.md @@ -150,7 +150,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 `642.` followed by a number (streaming a phone needs Xcode 27's CoreDevice; 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` | | 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` | -| 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`, `SIMLOCK_E2E_IOS_BUNDLE_ID`, `SIMLOCK_E2E_IOS_PROVISIONING_PROFILE` and `SIMLOCK_E2E_IOS_SIGNING_IDENTITY` (in `.slow-lane.env`). Run `scripts/slow-e2e.sh --physical e2e/slow-agent-device-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-agent-device-physical.test.ts b/e2e/slow-agent-device-physical.test.ts index 80e945446..3797feb7f 100644 --- a/e2e/slow-agent-device-physical.test.ts +++ b/e2e/slow-agent-device-physical.test.ts @@ -23,11 +23,16 @@ type Platform = "android" | "ios"; const ANDROID_SERIAL = process.env["SIMLOCK_PHYSICAL_ANDROID"]; const IOS_UDID = process.env["SIMLOCK_PHYSICAL_IOS"]; +// why: teamId and bundleId let Xcode sign the runner automatically; a provisioning profile or signing identity switches agent-device to manual signing, so each goes in only when set. const IOS_SIGNING = { - bundleId: process.env["SIMLOCK_E2E_IOS_BUNDLE_ID"], - provisioningProfile: process.env["SIMLOCK_E2E_IOS_PROVISIONING_PROFILE"], - signingIdentity: process.env["SIMLOCK_E2E_IOS_SIGNING_IDENTITY"], teamId: process.env["SIMLOCK_E2E_IOS_TEAM_ID"], + bundleId: process.env["SIMLOCK_E2E_IOS_BUNDLE_ID"], + ...(process.env["SIMLOCK_E2E_IOS_PROVISIONING_PROFILE"] + ? { provisioningProfile: process.env["SIMLOCK_E2E_IOS_PROVISIONING_PROFILE"] } + : {}), + ...(process.env["SIMLOCK_E2E_IOS_SIGNING_IDENTITY"] + ? { signingIdentity: process.env["SIMLOCK_E2E_IOS_SIGNING_IDENTITY"] } + : {}), } as const; function unset(name: string, value: string | undefined): string | undefined { @@ -39,9 +44,7 @@ const missing = { ios: unset("SIMLOCK_PHYSICAL_IOS", IOS_UDID) ?? unset("SIMLOCK_E2E_IOS_TEAM_ID", IOS_SIGNING.teamId) ?? - unset("SIMLOCK_E2E_IOS_BUNDLE_ID", IOS_SIGNING.bundleId) ?? - unset("SIMLOCK_E2E_IOS_PROVISIONING_PROFILE", IOS_SIGNING.provisioningProfile) ?? - unset("SIMLOCK_E2E_IOS_SIGNING_IDENTITY", IOS_SIGNING.signingIdentity), + unset("SIMLOCK_E2E_IOS_BUNDLE_ID", IOS_SIGNING.bundleId), } as const; interface RpcAnswer { diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 26ef40099..d283f8730 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -38,7 +38,7 @@ A worker runs two supervisors, one per role. `simulators`: state dir ` record `agent-device-daemon.json`, marker `--simlock-home=`. `phones`: state dir `agent-device-phones`, record `agent-device-phones-daemon.json`, marker adds `--simlock-role=phones`; its env has no simulator set or driver lease key, `ANDROID_ADB_SERVER_PORT=5037`, the -`AGENT_DEVICE_IOS_*` signing keys (`capabilities.agent-device.ios.*`), and the no-iOS and +`AGENT_DEVICE_IOS_*` signing keys (`capabilities.agent-device.ios.*`; `teamId` and `bundleId` suffice, `provisioningProfile` and `signingIdentity` are for manual signing only), and the no-iOS and no-Android sentinels when a platform is off. It starts once the simulator daemon's start has settled, never awaited. The capability follows the simulator daemon; doctor lists a finding per daemon. `RoutedHostLink` sends a physical allocate (its `serial`/`udid` is an enrolled phone's id) and every later call for that lease to the phone daemon, everything else to the simulator daemon; a phone daemon that is not running answers `phone daemon: `. Each daemon has its own `ReleaseScopeRecord` and `AgentDeviceLeaseEnd`; the link forgets a lease when it ends. diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index ed2c5e314..2d64555af 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -303,8 +303,8 @@ A name Simlock does not know is warned about and ignored. | `capabilities.agent-device.leaseTtlCapMs` | integer from `5000` to `lease.maxTtlMs` | not set (no cap) | Longest TTL for leases agent-device takes through Simlock. A longer TTL is lowered to it; a lease with none gets it. | Both | | `capabilities.agent-device.ios.teamId` | non-empty string | not set | Apple developer team ID agent-device signs its iPhone runner with. Passed to the phone daemon. | Worker | | `capabilities.agent-device.ios.bundleId` | non-empty string | not set | Bundle ID of agent-device's iPhone runner. Passed to the phone daemon. | Worker | -| `capabilities.agent-device.ios.provisioningProfile` | non-empty string | not set | Provisioning profile for the iPhone runner. Passed to the phone daemon. | Worker | -| `capabilities.agent-device.ios.signingIdentity` | non-empty string | not set | Code-signing identity for the iPhone runner. Passed to the phone daemon. | Worker | +| `capabilities.agent-device.ios.provisioningProfile` | non-empty string | not set | Provisioning profile for manual signing of the iPhone runner. Setting it switches agent-device to manual signing. Passed to the phone daemon. | Worker | +| `capabilities.agent-device.ios.signingIdentity` | non-empty string | not set | Code-signing identity for manual signing of the iPhone runner. Passed to the phone daemon. | Worker | | `capabilities.stream.enabled` | boolean | `false` | Let people watch a leased device's screen. On a gateway: pass each stream through from the worker. | Both | | `capabilities.stream.fps` | integer `1`–`60` | `30` | Highest frame rate. A still screen sends far fewer frames. | Worker | | `capabilities.stream.maxDimension` | integer `96`–`4096` | `720` | Longest side of the picture, in pixels. The setting that changes bandwidth most. | Worker | diff --git a/website/src/content/docs/docs/using-devices/agent-device.mdx b/website/src/content/docs/docs/using-devices/agent-device.mdx index e0de382d8..fc114786a 100644 --- a/website/src/content/docs/docs/using-devices/agent-device.mdx +++ b/website/src/content/docs/docs/using-devices/agent-device.mdx @@ -7,7 +7,7 @@ import { Steps, Aside } from '@astrojs/starlight/components'; [agent-device](https://github.com/callstack/agent-device) is Callstack's command-line tool for driving mobile apps: it opens an app, reads the screen as a tree of elements, taps, types and takes screenshots. With Simlock, `agent-device open` leases a simulator or emulator from Simlock, and every later command goes to that device. Each agent gets its own device, and a device is wiped when the agent closes it. -Simlock runs two agent-device daemons on each worker and watches both: one over the simulators and emulators Simlock leases, and a phone daemon beside it that sees the phones plugged into the host. The phone daemon needs the iOS signing values agent-device uses for an iPhone, set with `simlock config set capabilities.agent-device.ios.teamId ` (also `bundleId`, `provisioningProfile` and `signingIdentity`), and takes effect on daemon restart. If it cannot start, `simlock doctor` prints a line starting `phone daemon:`; the simulator daemon and the worker's agent-device status are not affected. Agents lease a phone through it with `--physical`. Agents reach agent-device over HTTP, on the worker or through a gateway, with a Simlock agent token. +Simlock runs two agent-device daemons on each worker and watches both: one over the simulators and emulators Simlock leases, and a phone daemon beside it that sees the phones plugged into the host. For an iPhone the phone daemon needs `teamId` and `bundleId`, set with `simlock config set capabilities.agent-device.ios.teamId ` (and `bundleId`). `provisioningProfile` and `signingIdentity` are for manual signing only: setting a provisioning profile switches agent-device to manual signing, which an Xcode-managed profile fails. The setting takes effect on daemon restart. If it cannot start, `simlock doctor` prints a line starting `phone daemon:`; the simulator daemon and the worker's agent-device status are not affected. Agents lease a phone through it with `--physical`. Agents reach agent-device over HTTP, on the worker or through a gateway, with a Simlock agent token. ## Before you start From ede0889c1f32785f4489544d2570df0e0c686574 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:33:48 +0200 Subject: [PATCH 27/28] fix(e2e): the physical-phone test sends a command the way the CLI does: lease scope and device key in meta, the phone's address in flags, an open first (#874) The raw screenshot carried only the lease id, so agent-device refused it (tenant isolation requires run id, then lease owner scope, no session, ambiguous device). The test was wrong, not Simlock. Also: only a provisioning profile switches agent-device to manual signing. --- e2e/slow-agent-device-physical.test.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/e2e/slow-agent-device-physical.test.ts b/e2e/slow-agent-device-physical.test.ts index 3797feb7f..e1c99b4d2 100644 --- a/e2e/slow-agent-device-physical.test.ts +++ b/e2e/slow-agent-device-physical.test.ts @@ -23,7 +23,7 @@ type Platform = "android" | "ios"; const ANDROID_SERIAL = process.env["SIMLOCK_PHYSICAL_ANDROID"]; const IOS_UDID = process.env["SIMLOCK_PHYSICAL_IOS"]; -// why: teamId and bundleId let Xcode sign the runner automatically; a provisioning profile or signing identity switches agent-device to manual signing, so each goes in only when set. +// why: teamId and bundleId let Xcode sign the runner automatically; only a provisioning profile switches agent-device to manual signing (a signing identity alone does not), so each goes in only when set. const IOS_SIGNING = { teamId: process.env["SIMLOCK_E2E_IOS_TEAM_ID"], bundleId: process.env["SIMLOCK_E2E_IOS_BUNDLE_ID"], @@ -149,12 +149,25 @@ function defineSuite(platform: Platform, id: string): void { }[]; expect(devices.find((device) => device.id === lease?.deviceId)?.driverDeviceId).toBe(id); + // why: like the CLI, a command carries the scope the lease was allocated under plus the device key agent-device's reply named; without all of them agent-device refuses the lease's owner. + const granted = allocated.result?.data?.["lease"] as { deviceKey?: string } | undefined; const dir = await mkdtemp(join(tmpdir(), "simlock-ad-phone-")); onTestFinished(() => rm(dir, { force: true, recursive: true })); const png = join(dir, "shot.png"); + // why: the CLI addresses the leased phone by its serial or udid on each command; with 26 devices known to agent-device none is picked for it. + const flags = { platform, [platform === "android" ? "serial" : "udid"]: id }; + const meta = { ...scope, deviceKey: granted?.deviceKey, leaseId }; + const opened = await call("agent_device.command", { + command: "open", + flags, + meta, + positionals: [], + }); + expect(opened.error, JSON.stringify(opened)).toBeUndefined(); const shot = await call("agent_device.command", { command: "screenshot", - meta: { leaseId }, + flags, + meta, positionals: [png], }); expect(shot.error, JSON.stringify(shot)).toBeUndefined(); @@ -162,7 +175,11 @@ function defineSuite(platform: Platform, id: string): void { const written = existsSync(png) ? png : typeof named === "string" ? named : png; expect((await readFile(written)).subarray(0, 8).toString("hex")).toBe(PNG_MAGIC); - const released = await call("agent_device.lease.release", { ...scope, leaseId }); + const released = await call("agent_device.lease.release", { + ...scope, + deviceKey: granted?.deviceKey, + leaseId, + }); expect(released.error, JSON.stringify(released)).toBeUndefined(); await waitForFree(env); }, From 90ae8a95e3fc0322d1fe844fce8f8b5730bdb20a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:34:38 +0200 Subject: [PATCH 28/28] refactor(e2e): split the physical-phone test's helpers out so Fallow's complexity gate passes (#874) --- e2e/slow-agent-device-physical.test.ts | 27 ++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/e2e/slow-agent-device-physical.test.ts b/e2e/slow-agent-device-physical.test.ts index e1c99b4d2..beb898116 100644 --- a/e2e/slow-agent-device-physical.test.ts +++ b/e2e/slow-agent-device-physical.test.ts @@ -52,8 +52,19 @@ interface RpcAnswer { readonly error?: { readonly message: string }; } +function deviceKeyOf(allocated: RpcAnswer): string | undefined { + const lease = allocated.result?.data?.["lease"] as { deviceKey?: string } | undefined; + return lease?.deviceKey; +} + +function writtenPath(shot: RpcAnswer, requested: string): string { + const named = shot.result?.data?.["path"]; + return existsSync(requested) || typeof named !== "string" ? requested : named; +} + function defineSuite(platform: Platform, id: string): void { const tag = platform === "android" ? "Android" : "iOS"; + const addressKey = platform === "android" ? "serial" : "udid"; describe.skipIf(missing[platform] !== undefined)( missing[platform] === undefined ? `agent-device with a physical ${tag} phone (real agent-device)` @@ -125,7 +136,7 @@ function defineSuite(platform: Platform, id: string): void { }, 2 * MINUTE); it( - `a raw agent_device.lease.allocate with physical: true and platform: "${platform}" is granted that ${platform === "android" ? "serial" : "udid"}, a screenshot on the lease answers a PNG, and agent_device.lease.release releases the Simlock lease`, + `a raw agent_device.lease.allocate with physical: true and platform: "${platform}" is granted that ${addressKey}, a screenshot on the lease answers a PNG, and agent_device.lease.release releases the Simlock lease`, { timeout: 15 * MINUTE }, async () => { const leaseId = randomBytes(16).toString("hex"); @@ -150,13 +161,13 @@ function defineSuite(platform: Platform, id: string): void { expect(devices.find((device) => device.id === lease?.deviceId)?.driverDeviceId).toBe(id); // why: like the CLI, a command carries the scope the lease was allocated under plus the device key agent-device's reply named; without all of them agent-device refuses the lease's owner. - const granted = allocated.result?.data?.["lease"] as { deviceKey?: string } | undefined; + const deviceKey = deviceKeyOf(allocated); const dir = await mkdtemp(join(tmpdir(), "simlock-ad-phone-")); onTestFinished(() => rm(dir, { force: true, recursive: true })); const png = join(dir, "shot.png"); // why: the CLI addresses the leased phone by its serial or udid on each command; with 26 devices known to agent-device none is picked for it. - const flags = { platform, [platform === "android" ? "serial" : "udid"]: id }; - const meta = { ...scope, deviceKey: granted?.deviceKey, leaseId }; + const flags = { platform, [addressKey]: id }; + const meta = { ...scope, deviceKey, leaseId }; const opened = await call("agent_device.command", { command: "open", flags, @@ -171,13 +182,13 @@ function defineSuite(platform: Platform, id: string): void { positionals: [png], }); expect(shot.error, JSON.stringify(shot)).toBeUndefined(); - const named = shot.result?.data?.["path"]; - const written = existsSync(png) ? png : typeof named === "string" ? named : png; - expect((await readFile(written)).subarray(0, 8).toString("hex")).toBe(PNG_MAGIC); + expect((await readFile(writtenPath(shot, png))).subarray(0, 8).toString("hex")).toBe( + PNG_MAGIC, + ); const released = await call("agent_device.lease.release", { ...scope, - deviceKey: granted?.deviceKey, + deviceKey, leaseId, }); expect(released.error, JSON.stringify(released)).toBeUndefined();