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 1e60cdcca..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; §3–4 superseded in part by [ADR 0043](0043-physical-devices-reach-agent-device-through-a-second-daemon.md) +- **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/agent-rules/toolchain.md b/docs/internal/agent-rules/toolchain.md index c47fb9621..f19a2b194 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` 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 new file mode 100644 index 000000000..beb898116 --- /dev/null +++ b/e2e/slow-agent-device-physical.test.ts @@ -0,0 +1,203 @@ +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"]; +// 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"], + ...(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 { + 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), +} as const; + +interface RpcAnswer { + readonly result?: { readonly ok?: boolean; readonly data?: Record }; + 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)` + : `agent-device with a physical ${tag} phone (skipped: ${missing[platform]} is not set)`, + { tags: ["slow", "physical", platform] }, + () => { + 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", + ...(await pins()), + }, + 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 ${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"); + 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); + + // 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 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, [addressKey]: id }; + const meta = { ...scope, 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", + flags, + meta, + positionals: [png], + }); + expect(shot.error, JSON.stringify(shot)).toBeUndefined(); + expect((await readFile(writtenPath(shot, png))).subarray(0, 8).toString("hex")).toBe( + PNG_MAGIC, + ); + + const released = await call("agent_device.lease.release", { + ...scope, + deviceKey, + leaseId, + }); + expect(released.error, JSON.stringify(released)).toBeUndefined(); + await waitForFree(env); + }, + ); + }, + ); +} + +defineSuite("android", ANDROID_SERIAL ?? ""); +defineSuite("ios", IOS_UDID ?? ""); diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index edc5595e4..d283f8730 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 @@ -38,10 +38,10 @@ 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. 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 - `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. +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`/`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. @@ -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 @@ -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 efc62b640..29e9970a0 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, @@ -254,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)); @@ -717,7 +751,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({ @@ -733,14 +767,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) { @@ -790,16 +824,281 @@ 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 = [ + { + address: { serial: "R58Y61A60HN" }, + asked: { platform: "android" }, + extra: { platform: "android" }, + id: "R58Y61A60HN", + phone: { class: "phone", model: "Pixel 8", osVersion: "15" }, + 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 { address, asked, extra, id, phone, platform } of cases) { + const rig = await setUp({ + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: ["35"], + clock, + knownModels: [phone.model], + physicalDevices: [{ ids: [id], ...phone }], + platform, + }), + ], + }); + await rig.daemon.dispatch("device.add", { id, platform }, adminSession); + rig.driver.setPhysicalPresence(id, true); - const answer = await envelopeOf(await allocate(rig, 1, { physical: true })); + const answer = await envelopeOf( + await allocate(rig, 1, { platform, ...extra, physical: true }), + ); - expect(answer.error).toMatchObject( - refusal("refused: physical devices are not available through agent-device"), + expect(answer.result).toMatchObject({ + data: { + 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), ...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([]); + } + }); + + 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(allocatesReceived(rig)).toEqual([]); + 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 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"); + 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("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("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) => { + 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("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" }); + 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 }); + 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)]); @@ -1581,27 +1880,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, a malformed one and no header are each forwarded, as today", 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, 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" }); + 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 of [other, malformed, {}]) { - 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 + 1); - } + 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, 200, 200]); + 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 () => { @@ -3260,6 +3579,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" }); @@ -3488,7 +3822,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 } })); @@ -3505,6 +3839,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 } }), @@ -3727,7 +4065,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) }]); @@ -3749,7 +4087,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) }]); @@ -3787,7 +4125,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..aac048b09 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 }), }; } @@ -274,6 +270,7 @@ function forwardedBody( deviceKey: _deviceKey, imageTag: _imageTag, osVersion: _osVersion, + physical: _physical, target: _target, ...rest } = call.params; @@ -318,7 +315,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 +404,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..c5530754e 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -1,6 +1,10 @@ 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 { frontReplyFor, notAvailable } from "../shared/replies.js"; +import { classifyCall, readRpcBody } from "../shared/rpc.js"; export type LinkStatus = | { @@ -25,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; @@ -40,16 +44,79 @@ export interface HostLink { dispose?(): void; } -export class InProcessHostLink implements HostLink { - readonly readsLeaseHeader = false; +interface RoutedHosts { + readonly simulators: AgentDeviceHost; + readonly phones: AgentDeviceHost; +} + +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; + readonly #roles = new Map(); + + constructor( + private readonly hosts: RoutedHosts, + private readonly registry: ModuleRegistryView, + ) {} + + 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(); + } - constructor(private readonly host: AgentDeviceHost) {} + 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)); + } + dropInstancePins(request); + } + 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); + } - status(): ReturnType { - return this.host.status(); + // 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; } - forward(request: Request, identity: Identity): Promise { - return this.host.forward(request, identity); + 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 false; + } + const read = await readRpcBody(request.clone()); + if (read.kind !== "request" || classifyCall(read.method, read.params) !== "allocate") { + return false; + } + const address = read.params["serial"] ?? read.params["udid"]; + return this.registry.snapshot.devices.some( + (device) => device.physical && device.driverDeviceId === address, + ); } } diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index d80449d4c..37fd826e2 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,54 @@ 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); + 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 () => { const rig = await setUp(); const tap = tapDispatch(rig.gateway); 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, 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; } 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..c815b5fb8 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, @@ -25,18 +25,32 @@ 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( upstream: AgentDeviceUpstream, + phoneUpstream: AgentDeviceUpstream, clock: Clock, platforms: readonly AgentDevicePlatform[], + registry: ModuleRegistryView, ): AgentDeviceEdgeParts { - const record = new ReleaseScopeRecord(); + const simulatorRecord = new ReleaseScopeRecord(); + const phoneRecord = new ReleaseScopeRecord(); return { - leaseEnd: new AgentDeviceLeaseEnd(upstream, record), - link: new InProcessHostLink(new AgentDeviceHost(upstream, platforms, record)), + leaseEnds: [ + new AgentDeviceLeaseEnd(upstream, simulatorRecord), + new AgentDeviceLeaseEnd(phoneUpstream, phoneRecord), + ], + link: new RoutedHostLink( + { + phones: new AgentDeviceHost(phoneUpstream, platforms, phoneRecord), + simulators: new AgentDeviceHost(upstream, platforms, simulatorRecord), + }, + registry, + ), map: new FrontMap(clock), renewals: new Renewals(clock), }; @@ -45,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, + ); }; } @@ -82,6 +100,7 @@ function agentDeviceCapabilitySource(parts: AgentDeviceEdgeParts): { export interface AgentDeviceFakes { readonly upstream?: AgentDeviceUpstream; + readonly phoneUpstream?: AgentDeviceUpstream; readonly health?: AgentDeviceHealthProbe; } @@ -114,8 +133,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), @@ -131,7 +152,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)); 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), 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, 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 e909c9c8b..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 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. 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 @@ -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