diff --git a/docs/internal/agent-rules/toolchain.md b/docs/internal/agent-rules/toolchain.md index 168042b51..27051c36b 100644 --- a/docs/internal/agent-rules/toolchain.md +++ b/docs/internal/agent-rules/toolchain.md @@ -75,7 +75,7 @@ The machine can run a line only if: | iOS | `uname -s` is `Darwin`; `xcrun simctl list runtimes` lists one | | Android | `command -v emulator adb` finds both | | 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. 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` is the absolute path of `bin/agent-device.mjs` in a checkout of agent-device built with `pnpm install && pnpm build`, and `git -C "$(dirname "$SIMLOCK_E2E_AGENT_DEVICE")/.." rev-parse HEAD` prints the commit in `package.json`'s `@agent-device/proxy` dependency; 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` | +| 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` is the absolute path of `bin/agent-device.mjs` in a checkout of agent-device built with `pnpm install && pnpm build`, and `git -C "$(dirname "$SIMLOCK_E2E_AGENT_DEVICE")/.." rev-parse HEAD` prints the commit in `package.json`'s `@agent-device/proxy` dependency; room for two devices: `node -p "os.totalmem() / 2**30"` prints at least 7 for iOS or 12 for Android (simlock's 4 GiB OS reserve plus two of its default 1.5 GiB iOS or 4 GiB Android per-device budgets). Run `scripts/slow-e2e.sh e2e/slow-agent-device.test.ts` or `scripts/slow-e2e.sh e2e/slow-agent-device-gateway.test.ts` | | Physical Android | `command -v adb` finds it; `adb devices -l` lists `$SIMLOCK_PHYSICAL_ANDROID` on a USB transport (a `usb:` field) in state `device`; `SIMLOCK_PHYSICAL_ANDROID_APK` names an APK. Run `scripts/slow-e2e.sh --physical e2e/slow-android-physical.test.ts` | | Physical Android, 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/README.md b/e2e/README.md index 2acc0f0ae..3fe5e8280 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -67,5 +67,5 @@ running test body silently never fires — see the comment in `helpers/env.ts`. 60s limit on a cold boot ([#206](https://github.com/callstackincubator/simlock/issues/206)). Treat the slow lane as a manual, one-flow-at-a-time tool until both are fixed. - Android is exercised through the fake driver in the fast lane; only - `slow-android-smoke.test.ts`, `slow-warm-pool.test.ts` and `slow-agent-device.test.ts` - touch a real emulator. + `slow-android-smoke.test.ts`, `slow-warm-pool.test.ts`, `slow-agent-device.test.ts` and + `slow-agent-device-gateway.test.ts` touch a real emulator. diff --git a/e2e/helpers/agent-device-targets.ts b/e2e/helpers/agent-device-targets.ts new file mode 100644 index 000000000..233cb5909 --- /dev/null +++ b/e2e/helpers/agent-device-targets.ts @@ -0,0 +1,180 @@ +import { execFileSync } from "node:child_process"; +import { writeSync } from "node:fs"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { expect } from "vitest"; + +import type { AgentDeviceResult } from "./agent-device.js"; +import type { SharedTestEnv } from "./env.js"; +import { REPO_ROOT } from "./repo-root.js"; +import { waitFor } from "./wait.js"; + +export function succeeds(file: string, args: readonly string[]): boolean { + try { + execFileSync(file, args, { stdio: "pipe" }); + return true; + } catch { + return false; + } +} + +export function hasIosRuntime(): boolean { + if (process.platform !== "darwin" || process.arch !== "arm64") return false; + try { + return execFileSync("xcrun", ["simctl", "list", "runtimes"], { encoding: "utf8" }).includes( + "iOS", + ); + } catch { + return false; + } +} + +export interface Target { + readonly platform: "ios" | "android"; + readonly bundleId: string; + readonly app: string; + readonly deviceFlag: "--udid" | "--serial"; + readonly forbiddenFlags: (deviceId: string, dir: string) => string[][]; +} + +export const IOS: Target = { + platform: "ios", + bundleId: "com.callstack.appduct.playgroundnative", + app: join(REPO_ROOT, "e2e/fixtures/appduct/ios/AppductPlayground.app"), + deviceFlag: "--udid", + forbiddenFlags: (_id, dir) => [["--ios-simulator-device-set", dir]], +}; + +export const ANDROID: Target = { + platform: "android", + bundleId: "com.callstack.appduct.playground", + app: join(REPO_ROOT, "e2e/fixtures/appduct/android/AppductPlayground.apk"), + deviceFlag: "--serial", + forbiddenFlags: (id, dir) => [ + ["--ios-simulator-device-set", dir], + ["--android-device-allowlist", id], + ], +}; + +export interface DeviceRow { + readonly id: string; + readonly driverDeviceId: string; + // why: the address agent-device names the device by (an iOS UDID, an Android adb serial); on Android it is not the driver's device id. + readonly address: string; + readonly state: string; +} +export interface LeaseRow { + readonly id: string; + readonly deviceId: string; + readonly ownerId: string; + readonly requesterId: string; +} +export interface RequestRow { + readonly requesterId: string; +} + +// why: the first snapshot on a fresh simulator starts the XCTest runner, which agent-device gives 45 s to start (RUNNER_STARTUP_TIMEOUT_MS in packages/platform-apple/src/runner/runner-startup-transport.ts), so with the command's own 45 s it can pass the CLI's 60 s default and cut off agent-device's answer. +export const FIRST_SNAPSHOT = { timeout: 180_000 } as const; + +async function listRows(env: SharedTestEnv, flag: string): Promise { + const result = await env.cli(["list", flag], { timeout: 60_000 }); + expect(result.code, `simlock list ${flag}: ${result.stderr}`).toBe(0); + return result.json as T[]; +} + +export const listDevices = (env: SharedTestEnv) => listRows(env, "--devices"); +export const listLeases = (env: SharedTestEnv) => listRows(env, "--leases"); + +// why: `simlock list --requests` prints one text line per request (`Request : [ on ], ...`) or "No requests are waiting.", never JSON. +export async function listRequests(env: SharedTestEnv): Promise { + const result = await env.cli(["list", "--requests"], { timeout: 60_000 }); + expect(result.code, `simlock list --requests: ${result.stderr}`).toBe(0); + return result.stdout + .split("\n") + .map((line) => /^Request \S+: ([^\s,]+)/.exec(line)) + .filter((match) => match !== null) + .map((match) => ({ requesterId: match[1] as string })); +} + +export async function waitForFree(env: SharedTestEnv): Promise { + let observed = "nothing read yet"; + await waitFor( + async () => { + const [devices, leases, requests] = await Promise.all([ + listDevices(env), + listLeases(env), + listRequests(env), + ]); + observed = `devices ${devices.map((device) => device.state).join(",") || "none"}; leases ${String(leases.length)}; requests ${String(requests.length)}`; + return ( + devices.length > 0 && + devices.every((device) => device.state === "ready") && + leases.length === 0 && + requests.length === 0 + ); + }, + { + timeout: 240_000, + interval: 1_000, + label: () => `every device ready, no lease, no request; last observed: ${observed}`, + }, + ); +} + +export function ok(result: AgentDeviceResult): void { + expect(result.code, `${result.stdout}\n${result.stderr}`).toBe(0); +} + +export function failureText(result: AgentDeviceResult): string { + return result.error?.message ?? `${result.stdout}\n${result.stderr}`; +} + +// why: the device limit lives in the config of the daemon that owns devices (a worker, or a single host), so the caller passes that daemon; the caller waits for whatever it needs after the restart. +export async function setLimits( + daemon: SharedTestEnv, + target: Target, + devices: number, +): Promise { + const config = JSON.parse(await readFile(daemon.configPath, "utf8")) as { + capacity: { config: { limits: Record } }; + }; + config.capacity.config.limits[target.platform] = { maxDevices: devices, maxRunning: devices }; + await writeFile(daemon.configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8"); + await daemon.restart(); +} + +export async function warmUp(daemon: SharedTestEnv, target: Target, count: number): Promise { + const ids: string[] = []; + for (let index = 1; index <= count; index += 1) { + const lease = await daemon.cli( + ["lease", "--detach", "--platform", target.platform, "--agent-id", `warmup-${index}`], + { timeout: 330_000 }, + ); + expect(lease.code, lease.stderr).toBe(0); + ids.push((lease.json as { lease: { id: string } }).lease.id); + } + for (const id of ids) { + const released = await daemon.cli(["release", id], { timeout: 60_000 }); + expect(released.code, released.stderr).toBe(0); + } + // why: a released Android device is shut down and boots again with a wiped disk; `count` of them boot at once on a loaded host, so the wait allows a lease's whole boot window (330 s) rather than one quiet boot. + let observed = "nothing read yet"; + await waitFor( + async () => { + const devices = await listDevices(daemon); + observed = devices.map((device) => device.state).join(",") || "none"; + return devices.length >= count && devices.every((device) => device.state === "ready"); + }, + { + timeout: 330_000, + interval: 1_000, + label: () => `${String(count)} warm-up devices ready; last observed: ${observed}`, + }, + ); +} + +// why: vitest holds a test's console output until the test ends; a write to fd 2 reaches the log at once, so a stuck test shows while it runs. +export function progress(line: string): void { + writeSync(2, `${new Date().toISOString()} ${line}\n`); +} diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index d950693e3..3961cad48 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -20,3 +20,20 @@ export { events } from "./events.js"; export type { RecordedEvent } from "./events.js"; export { waitForDeviceState, waitForLeaseCount } from "./status.js"; export type { CliResult } from "./cli.js"; +export { + ANDROID, + FIRST_SNAPSHOT, + IOS, + failureText, + hasIosRuntime, + listDevices, + listLeases, + listRequests, + ok, + progress, + setLimits, + succeeds, + waitForFree, + warmUp, +} from "./agent-device-targets.js"; +export type { DeviceRow, LeaseRow, RequestRow, Target } from "./agent-device-targets.js"; diff --git a/e2e/slow-agent-device-gateway.test.ts b/e2e/slow-agent-device-gateway.test.ts new file mode 100644 index 000000000..01a6e8c8f --- /dev/null +++ b/e2e/slow-agent-device-gateway.test.ts @@ -0,0 +1,333 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + onTestFinished, +} from "vitest"; + +import { + ANDROID, + FIRST_SNAPSHOT, + IOS, + assertPinnedAgentDevice, + cleanupAgents, + failureText, + freeLoopbackPort, + hasIosRuntime, + listDevices, + listLeases, + makeAgent, + newAgentToken, + ok, + progress, + setLimits, + succeeds, + waitFor, + waitForFree, + warmUp, + withSharedDaemon, + type Agent, + type SharedTestEnv, + type Target, +} from "./helpers/index.js"; + +const AGENT_DEVICE = process.env.SIMLOCK_E2E_AGENT_DEVICE; + +const iosAvailable = hasIosRuntime(); +const androidAvailable = succeeds("sh", ["-c", "command -v emulator && command -v adb"]); + +const NO_WORKER = "no worker connected to this gateway can serve agent-device"; + +interface WorkerView { + readonly connection: string; + readonly capacity?: Readonly>; + readonly capabilities?: readonly { readonly name: string; readonly state: string }[]; +} + +const sharedEnvs = new Set(); +afterAll(async () => { + await Promise.allSettled([...sharedEnvs].map((env) => env.teardown())); + sharedEnvs.clear(); +}, 120_000); + +function defineSuite(target: Target): void { + const platform = target.platform; + let gateway: SharedTestEnv; + let worker: SharedTestEnv; + const restores: (() => Promise)[] = []; + + const agent = (name: string): Promise => makeAgent(gateway, name); + // why: an open that fails answers within seconds, so it ends the test there instead of leaving the test to wait on a lease nobody holds. + const open = async (who: Agent) => { + const result = await who.run(["open", "--platform", platform], { timeout: 330_000 }); + if (result.code !== 0) { + throw new Error(`open failed for ${who.name}: ${result.stdout}\n${result.stderr}`); + } + return result; + }; + + async function workerView(): Promise { + const listed = await gateway.cli(["worker", "list", "--json"], { timeout: 60_000 }); + expect(listed.code, `simlock worker list: ${listed.stderr}`).toBe(0); + return (listed.json as { workers: WorkerView[] }).workers[0]; + } + + async function waitForWorker( + label: string, + expected: (view: WorkerView) => boolean, + timeout: number, + ): Promise { + let observed = "no worker listed"; + await waitFor( + async () => { + const view = await workerView(); + observed = JSON.stringify(view ?? null); + return view !== undefined && expected(view); + }, + { timeout, interval: 1_000, label: () => `${label}; last observed: ${observed}` }, + ); + } + + const agentDeviceState = (view: WorkerView): string | undefined => + view.capabilities?.find((entry) => entry.name === "agent-device")?.state; + + const waitForAvailable = () => + waitForWorker( + "the gateway's worker list shows the worker connected with agent-device available", + (view) => view.connection === "connected" && agentDeviceState(view) === "available", + 120_000, + ); + + // why: the test edits one daemon's config and restarts it; afterEach puts the original text back, so a failing test cannot leave the next one on a changed config. + async function changeConfig( + daemon: SharedTestEnv, + change: (config: Record>) => void, + ): Promise { + const original = await readFile(daemon.configPath, "utf8"); + restores.push(async () => { + await writeFile(daemon.configPath, original, "utf8"); + await daemon.restart(); + }); + const config = JSON.parse(original) as Record>; + change(config); + await writeFile(daemon.configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8"); + await daemon.restart(); + } + + beforeAll(async () => { + const pinned = await assertPinnedAgentDevice(platform); + const gatewayPort = await freeLoopbackPort(); + gateway = await withSharedDaemon({ + driver: "none", + configOverrides: { + mode: "gateway", + http: { enabled: true, host: "127.0.0.1", port: gatewayPort }, + agentDevice: { enabled: true }, + }, + }); + sharedEnvs.add(gateway); + const minted = await gateway.cli(["token", "create", "--role", "worker"], { timeout: 60_000 }); + expect(minted.code, minted.stderr).toBe(0); + const { secret } = minted.json as { secret: string }; + + worker = await withSharedDaemon({ + driver: "real", + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, + gateway: { label: "worker", token: secret, url: `ws://127.0.0.1:${gatewayPort}` }, + agentDevice: { enabled: true, command: pinned }, + capacity: { + config: { limits: { [platform]: { maxDevices: 1, maxRunning: 1 } } }, + }, + }, + }); + sharedEnvs.add(worker); + await waitForAvailable(); + await warmUp(worker, target, 1); + }, 420_000); + + afterAll(async () => { + await Promise.allSettled([worker?.teardown(), gateway?.teardown()]); + sharedEnvs.delete(worker); + sharedEnvs.delete(gateway); + }, 120_000); + + beforeEach((context) => { + progress(`START ${platform} gateway: ${context.task.name.slice(0, 100)}`); + }); + + afterEach((context) => { + progress( + `END ${platform} gateway (${context.task.result?.state ?? "unknown"}): ${context.task.name.slice(0, 100)}`, + ); + }); + + afterEach(async () => { + await cleanupAgents(); + for (const restore of restores.splice(0).reverse()) await restore(); + await waitForAvailable(); + const released = await gateway.cli(["release", "--all", "--yes"], { timeout: 60_000 }); + expect(released.code, released.stderr).toBe(0); + await waitForFree(worker); + }, 420_000); + + it( + "through the gateway, an agent opens a device, installs the Appduct fixture app as an upload, opens it, takes a snapshot that shows tab-status, saves a PNG screenshot and closes; the device is free within 240 s and the lease is gone from the gateway's simlock list within 240 s", + { timeout: 600_000 }, + async () => { + const a = await agent("a"); + ok(await open(a)); + expect(await listLeases(gateway)).toHaveLength(1); + ok(await a.run(["install", "Appduct", target.app])); + ok(await a.run(["open", target.bundleId])); + const snapshot = await a.run(["snapshot"], FIRST_SNAPSHOT); + ok(snapshot); + expect(snapshot.stdout).toContain("tab-status"); + const dir = await mkdtemp(join(tmpdir(), "simlock-ad-gw-shot-")); + onTestFinished(() => rm(dir, { force: true, recursive: true })); + const png = join(dir, "shot.png"); + ok(await a.run(["screenshot", png])); + expect((await readFile(png)).subarray(0, 8).toString("hex")).toBe("89504e470d0a1a0a"); + ok(await a.run(["close"])); + await waitForFree(worker); + await waitFor(async () => (await listLeases(gateway)).length === 0, { + timeout: 240_000, + interval: 1_000, + label: "the lease is gone from the gateway's simlock list", + }); + }, + ); + + it( + "through the gateway, a screenshot saved as an artifact downloads to the agent's machine as a PNG", + { timeout: 600_000 }, + async () => { + const a = await agent("a"); + ok(await open(a)); + ok(await a.run(["install", "Appduct", target.app])); + ok(await a.run(["open", target.bundleId])); + const dir = await mkdtemp(join(tmpdir(), "simlock-ad-gw-artifact-")); + onTestFinished(() => rm(dir, { force: true, recursive: true })); + const png = join(dir, "artifact.png"); + await expect(readFile(png)).rejects.toThrow(); + ok(await a.run(["screenshot", png], FIRST_SNAPSHOT)); + const bytes = await readFile(png); + expect(bytes.length).toBeGreaterThan(8); + expect(bytes.subarray(0, 8).toString("hex")).toBe("89504e470d0a1a0a"); + }, + ); + + it( + "with agentDevice.enabled unset on the gateway, its /v1/agent-device/health answers 404 where it answered something else while enabled", + { timeout: 600_000 }, + async () => { + const probe = await newAgentToken(gateway); + const healthUrl = `http://127.0.0.1:${String(gateway.httpPort)}/v1/agent-device/health`; + const headers = { authorization: `Bearer ${probe.secret}` }; + expect((await fetch(healthUrl, { headers })).status, "health while enabled").not.toBe(404); + await changeConfig(gateway, (config) => { + delete config.agentDevice; + }); + await waitForWorker( + "the gateway's worker list shows the worker connected again", + (view) => view.connection === "connected", + 120_000, + ); + expect((await fetch(healthUrl, { headers })).status).toBe(404); + }, + ); + + it( + "with the worker's agentDevice.enabled unset (the gateway's simlock worker list shows agent-device off), open through the gateway fails within 5 s with a message containing `no worker connected to this gateway can serve agent-device`, and no lease is made", + { timeout: 600_000 }, + async () => { + await changeConfig(worker, (config) => { + delete config.agentDevice; + }); + await waitForWorker( + "the gateway's worker list shows the worker connected with agent-device off", + (view) => view.connection === "connected" && agentDeviceState(view) === "off", + 120_000, + ); + const a = await agent("a"); + const startedAt = Date.now(); + const result = await a.run(["open", "--platform", platform], { timeout: 5_000 }); + expect(Date.now() - startedAt, "open took longer than 5 s").toBeLessThan(5_000); + expect(result.code, "open was accepted").not.toBe(0); + expect(failureText(result)).toContain(NO_WORKER); + expect(await listLeases(gateway)).toEqual([]); + expect(await listLeases(worker)).toEqual([]); + }, + ); + + it( + "simlock worker list on the gateway shows the worker with agent-device available", + { timeout: 600_000 }, + async () => { + const listed = await gateway.cli(["worker", "list"], { timeout: 60_000 }); + expect(listed.code, listed.stderr).toBe(0); + expect(listed.stdout).toMatch(/^\S+ \(worker\): connected .* -- agent-device available$/m); + }, + ); + + describe("with the device limit raised to 2", () => { + const waitForCapacity = (limit: number) => + waitForWorker( + `the gateway's worker list shows the worker available with capacity ${String(limit)}`, + (view) => + view.connection === "connected" && + agentDeviceState(view) === "available" && + view.capacity?.[platform]?.limit === limit, + 420_000, + ); + + beforeAll(async () => { + await setLimits(worker, target, 2); + await warmUp(worker, target, 2); + await waitForCapacity(2); + }, 600_000); + + afterAll(async () => { + await setLimits(worker, target, 1); + await waitForCapacity(1); + }, 420_000); + + it( + "with the device limit raised to 2 and two devices ready, agent-device devices through the gateway after open lists exactly the agent's device", + { timeout: 600_000 }, + async () => { + const a = await agent("a"); + expect( + (await listDevices(worker)).filter((device) => device.state === "ready"), + ).toHaveLength(2); + ok(await open(a)); + // why: the lease runs on the worker, so the device's address comes from the worker that owns it. + const [lease] = await listLeases(worker); + const bound = (await listDevices(worker)).find((device) => device.id === lease?.deviceId); + const listed = await a.run(["devices"]); + ok(listed); + const devices = (listed.data as { devices?: { id: string }[] } | undefined)?.devices ?? []; + expect(devices.map((device) => device.id)).toEqual([bound?.address]); + }, + ); + }); +} + +describe.skipIf(AGENT_DEVICE === undefined || !iosAvailable)( + "agent-device through a gateway (iOS)", + { tags: ["slow", "ios"] }, + () => defineSuite(IOS), +); + +describe.skipIf(AGENT_DEVICE === undefined || !androidAvailable)( + "agent-device through a gateway (Android)", + { tags: ["slow", "android"] }, + () => defineSuite(ANDROID), +); diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index ee4317a6a..2611a093d 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -1,5 +1,4 @@ import { execFileSync } from "node:child_process"; -import { writeSync } from "node:fs"; import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -23,143 +22,33 @@ import { waitForAgentDevice, waitFor, withSharedDaemon, + ANDROID, + FIRST_SNAPSHOT, + IOS, + failureText, + hasIosRuntime, + listDevices, + listLeases, + listRequests, + ok, + progress, + setLimits, + succeeds, + waitForFree, + warmUp, type Agent, type AgentDeviceResult, + type RequestRow, + type Target, type RecordedEvent, type SharedTestEnv, } from "./helpers/index.js"; -import { REPO_ROOT } from "./helpers/repo-root.js"; const AGENT_DEVICE = process.env.SIMLOCK_E2E_AGENT_DEVICE; -function succeeds(file: string, args: readonly string[]): boolean { - try { - execFileSync(file, args, { stdio: "pipe" }); - return true; - } catch { - return false; - } -} - -function hasIosRuntime(): boolean { - if (process.platform !== "darwin" || process.arch !== "arm64") return false; - try { - return execFileSync("xcrun", ["simctl", "list", "runtimes"], { encoding: "utf8" }).includes( - "iOS", - ); - } catch { - return false; - } -} - const iosAvailable = hasIosRuntime(); const androidAvailable = succeeds("sh", ["-c", "command -v emulator && command -v adb"]); -interface Target { - readonly platform: "ios" | "android"; - readonly bundleId: string; - readonly app: string; - readonly deviceFlag: "--udid" | "--serial"; - readonly forbiddenFlags: (deviceId: string, dir: string) => string[][]; -} - -const IOS: Target = { - platform: "ios", - bundleId: "com.callstack.appduct.playgroundnative", - app: join(REPO_ROOT, "e2e/fixtures/appduct/ios/AppductPlayground.app"), - deviceFlag: "--udid", - forbiddenFlags: (_id, dir) => [["--ios-simulator-device-set", dir]], -}; - -const ANDROID: Target = { - platform: "android", - bundleId: "com.callstack.appduct.playground", - app: join(REPO_ROOT, "e2e/fixtures/appduct/android/AppductPlayground.apk"), - deviceFlag: "--serial", - forbiddenFlags: (id, dir) => [ - ["--ios-simulator-device-set", dir], - ["--android-device-allowlist", id], - ], -}; - -interface DeviceRow { - readonly id: string; - readonly driverDeviceId: string; - // why: the address agent-device names the device by (an iOS UDID, an Android adb serial); on Android it is not the driver's device id. - readonly address: string; - readonly state: string; -} -interface LeaseRow { - readonly id: string; - readonly deviceId: string; - readonly ownerId: string; - readonly requesterId: string; -} -interface RequestRow { - readonly requesterId: string; -} - -// why: the first snapshot on a fresh simulator starts the XCTest runner, which agent-device gives 45 s to start (RUNNER_STARTUP_TIMEOUT_MS in packages/platform-apple/src/runner/runner-startup-transport.ts), so with the command's own 45 s it can pass the CLI's 60 s default and cut off agent-device's answer. -const FIRST_SNAPSHOT = { timeout: 180_000 } as const; - -// why: vitest holds a test's console output until the test ends; a write to fd 2 reaches the log at once, so a stuck test shows while it runs. -function progress(line: string): void { - writeSync(2, `${new Date().toISOString()} ${line}\n`); -} - -async function listRows(env: SharedTestEnv, flag: string): Promise { - const result = await env.cli(["list", flag], { timeout: 60_000 }); - expect(result.code, `simlock list ${flag}: ${result.stderr}`).toBe(0); - return result.json as T[]; -} - -const listDevices = (env: SharedTestEnv) => listRows(env, "--devices"); -const listLeases = (env: SharedTestEnv) => listRows(env, "--leases"); - -// why: `simlock list --requests` prints one text line per request (`Request : [ on ], ...`) or "No requests are waiting.", never JSON. -async function listRequests(env: SharedTestEnv): Promise { - const result = await env.cli(["list", "--requests"], { timeout: 60_000 }); - expect(result.code, `simlock list --requests: ${result.stderr}`).toBe(0); - return result.stdout - .split("\n") - .map((line) => /^Request \S+: ([^\s,]+)/.exec(line)) - .filter((match) => match !== null) - .map((match) => ({ requesterId: match[1] as string })); -} - -async function waitForFree(env: SharedTestEnv): Promise { - let observed = "nothing read yet"; - await waitFor( - async () => { - const [devices, leases, requests] = await Promise.all([ - listDevices(env), - listLeases(env), - listRequests(env), - ]); - observed = `devices ${devices.map((device) => device.state).join(",") || "none"}; leases ${String(leases.length)}; requests ${String(requests.length)}`; - return ( - devices.length > 0 && - devices.every((device) => device.state === "ready") && - leases.length === 0 && - requests.length === 0 - ); - }, - { - timeout: 240_000, - interval: 1_000, - label: () => `every device ready, no lease, no request; last observed: ${observed}`, - }, - ); -} - -function ok(result: AgentDeviceResult): void { - expect(result.code, `${result.stdout}\n${result.stderr}`).toBe(0); -} - -function failureText(result: AgentDeviceResult): string { - return result.error?.message ?? `${result.stdout}\n${result.stderr}`; -} - function refused(result: AgentDeviceResult): void { expect(result.code, "the command was accepted").not.toBe(0); expect(failureText(result)).toContain("refused:"); @@ -243,39 +132,6 @@ function defineSuite(target: Target): void { await waitForAgentDevice(env, probe.secret); } - async function setLimits(devices: number): Promise { - const config = JSON.parse(await readFile(env.configPath, "utf8")) as { - capacity: { config: { limits: Record } }; - }; - config.capacity.config.limits[platform] = { maxDevices: devices, maxRunning: devices }; - await writeFile(env.configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8"); - await env.restart(); - await awaitAgentDevice(); - } - - async function warmUp(count: number): Promise { - const ids: string[] = []; - for (let index = 1; index <= count; index += 1) { - const lease = await env.cli( - ["lease", "--detach", "--platform", platform, "--agent-id", `warmup-${index}`], - { timeout: 330_000 }, - ); - expect(lease.code, lease.stderr).toBe(0); - ids.push((lease.json as { lease: { id: string } }).lease.id); - } - for (const id of ids) { - const released = await env.cli(["release", id], { timeout: 60_000 }); - expect(released.code, released.stderr).toBe(0); - } - await waitFor( - async () => { - const devices = await listDevices(env); - return devices.length >= count && devices.every((device) => device.state === "ready"); - }, - { timeout: 240_000, interval: 1_000, label: "warm-up devices ready" }, - ); - } - beforeAll(async () => { const pinned = await assertPinnedAgentDevice(platform); env = await withSharedDaemon({ @@ -290,7 +146,7 @@ function defineSuite(target: Target): void { }); sharedEnvs.add(env); await awaitAgentDevice(); - await warmUp(1); + await warmUp(env, target, 1); }, 420_000); afterAll(async () => { @@ -695,13 +551,15 @@ function defineSuite(target: Target): void { describe("with the device limit raised to 2", () => { beforeAll(async () => { - await setLimits(2); - await warmUp(2); + await setLimits(env, target, 2); + await awaitAgentDevice(); + await warmUp(env, target, 2); }, 420_000); afterAll(async () => { - await setLimits(1); - }, 420_000); + await setLimits(env, target, 1); + await awaitAgentDevice(); + }, 600_000); it( "with both devices ready, devices lists nothing before open, and after open only the device it bound, not the other ready device", diff --git a/package.json b/package.json index 84f9c8000..b7096eaa4 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,7 @@ "mutate": "node scripts/mutate.mjs" }, "dependencies": { - "@agent-device/proxy": "file:vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz", + "@agent-device/proxy": "file:vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz", "@hono/node-server": "2.0.10", "@hono/zod-validator": "^0.9.1", "@modelcontextprotocol/sdk": "1.29.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 27ca0cc80..7430ad363 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -212,8 +212,8 @@ importers: .: dependencies: '@agent-device/proxy': - specifier: file:vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz - version: file:vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz + specifier: file:vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz + version: file:vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz '@hono/node-server': specifier: 2.0.10 version: 2.0.10(hono@4.13.5) @@ -314,9 +314,9 @@ importers: packages: - '@agent-device/proxy@file:vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz': - resolution: {integrity: sha512-/Q0a2HgHF82DmisG8y5sYsguc5sBc8nEuWuylaemVUWaPmqpJTvwV6aVVsGcluJInU29361hyN27zSbl1v7FiQ==, tarball: file:vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz} - version: 0.21.27-dev + '@agent-device/proxy@file:vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz': + resolution: {integrity: sha512-8vQHEJTDvsQvJchkbX/yZe/BZ2JkF68rsnQ/Ii16kuFCRgv2vXO6IYml2NrEOum7jjGpIXuuZl/WFP8ywl5p5w==, tarball: file:vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz} + version: 0.21.28-dev engines: {node: '>=22.12'} '@axe-core/playwright@4.13.0': @@ -3101,7 +3101,7 @@ packages: snapshots: - '@agent-device/proxy@file:vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz': {} + '@agent-device/proxy@file:vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz': {} '@axe-core/playwright@4.13.0(playwright-core@1.63.0)': dependencies: diff --git a/vendor/README.md b/vendor/README.md index 5ca546bd6..0c80f1e79 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -1,8 +1,8 @@ # vendor -`agent-device-proxy-0.21.27-dev-54e4e4d.tgz` is `@agent-device/proxy`, packed +`agent-device-proxy-0.21.28-dev-253dca0.tgz` is `@agent-device/proxy`, packed from the `simlock-integration` branch of agent-device at commit -`54e4e4db971d75ba1ebeb75c0ab7bce45c7d9b28`: +`253dca023edf13410f7928c76e9e604e5e5871a0`: ```bash pnpm --filter @agent-device/proxy pack --pack-destination diff --git a/vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz b/vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz deleted file mode 100644 index a7b1c2217..000000000 Binary files a/vendor/agent-device-proxy-0.21.27-dev-54e4e4d.tgz and /dev/null differ diff --git a/vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz b/vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz new file mode 100644 index 000000000..4aa419927 Binary files /dev/null and b/vendor/agent-device-proxy-0.21.28-dev-253dca0.tgz differ