From 0dd04d8fd4ffaa54a19cf80030485a2fb84db668 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 13:26:19 +0200 Subject: [PATCH 01/18] test: end-to-end tests for agent-device through a simlock worker on real devices (#477) --- docs/internal/agent-rules/toolchain.md | 1 + e2e/README.md | 3 +- e2e/helpers/agent-device.ts | 40 ++ e2e/helpers/env.ts | 10 + e2e/helpers/index.ts | 6 +- e2e/slow-agent-device.test.ts | 728 +++++++++++++++++++++++++ 6 files changed, 785 insertions(+), 3 deletions(-) create mode 100644 e2e/helpers/agent-device.ts create mode 100644 e2e/slow-agent-device.test.ts diff --git a/docs/internal/agent-rules/toolchain.md b/docs/internal/agent-rules/toolchain.md index d9ba2019f..168042b51 100644 --- a/docs/internal/agent-rules/toolchain.md +++ b/docs/internal/agent-rules/toolchain.md @@ -75,6 +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` | | 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 466d39abb..2acc0f0ae 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -67,4 +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` and `slow-warm-pool.test.ts` touch a real emulator. + `slow-android-smoke.test.ts`, `slow-warm-pool.test.ts` and `slow-agent-device.test.ts` + touch a real emulator. diff --git a/e2e/helpers/agent-device.ts b/e2e/helpers/agent-device.ts new file mode 100644 index 000000000..2a99c9aeb --- /dev/null +++ b/e2e/helpers/agent-device.ts @@ -0,0 +1,40 @@ +import type { CliBackgroundHandle } from "./cli.js"; +import type { SharedTestEnv } from "./env.js"; + +export interface AgentDeviceResult { + readonly code: number | null; + readonly stdout: string; + readonly stderr: string; + readonly json: unknown; + readonly data: unknown; + readonly error: { code: string; message: string; details?: Record } | undefined; +} + +export interface AgentDeviceRunOptions { + readonly timeout?: number; +} + +export interface Agent { + readonly name: string; + readonly home: string; + readonly token: string; + readonly tokenId: string; + run(args: readonly string[], options?: AgentDeviceRunOptions): Promise; + start(args: readonly string[]): CliBackgroundHandle; +} + +export function newAgentToken(_env: SharedTestEnv): Promise<{ secret: string; id: string }> { + return Promise.reject(new Error("newAgentToken is not implemented")); +} + +export function makeAgent(_env: SharedTestEnv, _name: string): Promise { + return Promise.reject(new Error("makeAgent is not implemented")); +} + +export function cleanupAgents(): Promise { + return Promise.reject(new Error("cleanupAgents is not implemented")); +} + +export function waitForAgentDevice(_env: SharedTestEnv, _token: string): Promise { + return Promise.reject(new Error("waitForAgentDevice is not implemented")); +} diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index cd950efda..309f07970 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -326,6 +326,16 @@ export async function withDaemon(options: WithDaemonOptions = {}): Promise; + restart(): Promise; +} + +export function withSharedDaemon(_options: WithDaemonOptions = {}): Promise { + return Promise.reject(new Error("withSharedDaemon is not implemented")); +} + interface TeardownState { readonly backgroundProcesses: ReadonlySet; readonly env: NodeJS.ProcessEnv; diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index d4f367a3f..2e96cdf05 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -2,11 +2,13 @@ // through this barrel -- add an export here (from its owning helper module) the // moment a flow needs it, rather than pre-declaring the full internal surface, so an // unused re-export is always a real signal. -export { withDaemon } from "./env.js"; +export { withDaemon, withSharedDaemon } from "./env.js"; +export { cleanupAgents, makeAgent, newAgentToken, waitForAgentDevice } from "./agent-device.js"; +export type { Agent, AgentDeviceResult } from "./agent-device.js"; export { freeLoopbackPort } from "./port.js"; // A flow that factors its own setup out of a test body needs to name what `withDaemon` hands // back; every other flow keeps it inferred. -export type { TestEnv } from "./env.js"; +export type { SharedTestEnv, TestEnv } from "./env.js"; export { waitFor } from "./wait.js"; export { events } from "./events.js"; export type { RecordedEvent } from "./events.js"; diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts new file mode 100644 index 000000000..f6f4a2cef --- /dev/null +++ b/e2e/slow-agent-device.test.ts @@ -0,0 +1,728 @@ +import { execFileSync } from "node:child_process"; +import { existsSync } 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"; +import { afterAll, afterEach, beforeAll, describe, expect, it, onTestFinished } from "vitest"; + +import { + cleanupAgents, + freeLoopbackPort, + makeAgent, + newAgentToken, + waitForAgentDevice, + waitFor, + withSharedDaemon, + type Agent, + type AgentDeviceResult, + 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; + readonly state: string; +} +interface LeaseRow { + readonly id: string; + readonly deviceId: string; + readonly requesterId: string; +} +interface RequestRow { + readonly requesterId: string; +} + +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"); +const listRequests = (env: SharedTestEnv) => listRows(env, "--requests"); + +async function waitForFree(env: SharedTestEnv): Promise { + await waitFor( + async () => { + const [devices, leases, requests] = await Promise.all([ + listDevices(env), + listLeases(env), + listRequests(env), + ]); + 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" }, + ); +} + +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:"); +} + +function listField(result: AgentDeviceResult, key: string): unknown[] { + const data = result.data as Record | undefined; + const value = data?.[key]; + return Array.isArray(value) ? value : []; +} + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error: unknown) { + return (error as NodeJS.ErrnoException).code !== "ESRCH"; + } +} + +interface PidRecord { + readonly pid: number; + readonly entry: string; +} + +async function readPidRecord(env: SharedTestEnv): Promise { + return JSON.parse( + await readFile(join(env.home, "agent-device-daemon.json"), "utf8"), + ) as PidRecord; +} + +function killIfStillAgentDevice(record: PidRecord): void { + if (!isAlive(record.pid)) return; + const args = execFileSync("ps", ["-ww", "-o", "args=", "-p", String(record.pid)], { + encoding: "utf8", + }); + if (args.includes(record.entry)) process.kill(record.pid, "SIGKILL"); +} + +async function eventAfter( + env: SharedTestEnv, + name: string, + since: number, + match: (event: RecordedEvent) => boolean = () => true, +): Promise { + const all = await env.events(); + return all.find((event) => event.event === name && event.timestamp >= since && match(event)); +} + +function forLease(leaseId: string | undefined): (event: RecordedEvent) => boolean { + return (event) => (event.payload as { leaseId?: string }).leaseId === leaseId; +} + +function wipeStartOf(reclaimed: RecordedEvent): number { + return reclaimed.timestamp - (reclaimed.payload as { duration: number }).duration; +} + +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 env: SharedTestEnv; + + const agent = (name: string): Promise => makeAgent(env, name); + const open = (who: Agent) => who.run(["open", "--platform", platform], { timeout: 330_000 }); + + async function awaitAgentDevice(): Promise { + const probe = await newAgentToken(env); + 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 () => { + if (AGENT_DEVICE === undefined || !existsSync(AGENT_DEVICE)) { + throw new Error(`SIMLOCK_E2E_AGENT_DEVICE ${String(AGENT_DEVICE)} does not exist`); + } + env = await withSharedDaemon({ + driver: "real", + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, + agentDevice: { enabled: true, command: AGENT_DEVICE }, + capacity: { + config: { limits: { [platform]: { maxDevices: 1, maxRunning: 1 } } }, + }, + }, + }); + sharedEnvs.add(env); + await awaitAgentDevice(); + await warmUp(1); + }, 420_000); + + afterAll(async () => { + await env?.teardown(); + sharedEnvs.delete(env); + }, 120_000); + + afterEach(async () => { + await cleanupAgents(); + const released = await env.cli(["release", "--all", "--yes"], { timeout: 60_000 }); + expect(released.code, released.stderr).toBe(0); + await waitForFree(env); + }, 300_000); + + it( + "an agent opens a device, installs the Appduct fixture app as an upload, opens it by its bundle id, takes a snapshot that shows tab-status, clicks tab-status, saves a PNG screenshot and closes; within 240 s the device is free", + { 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 snapshot = await a.run(["snapshot"]); + ok(snapshot); + expect(snapshot.stdout).toContain("tab-status"); + ok(await a.run(["click", 'id="tab-status"'])); + const dir = await mkdtemp(join(tmpdir(), "simlock-ad-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(env); + }, + ); + + it( + "with this working agent-device, simlock doctor --json reports no agent-device-unavailable finding and no finding whose message names agent-device", + { timeout: 600_000 }, + async () => { + const doctor = await env.cli(["doctor", "--json"], { timeout: 60_000 }); + const findings = (doctor.json as { findings: { kind: string; message?: string }[] }).findings; + expect(findings.map((finding) => finding.kind)).not.toContain("agent-device-unavailable"); + expect(findings.filter((finding) => /agent-device/i.test(finding.message ?? ""))).toEqual([]); + }, + ); + + it( + "close releases the simlock lease before the CLI exits, and a following open works", + { timeout: 900_000 }, + async () => { + const a = await agent("a"); + ok(await open(a)); + expect(await listLeases(env)).toHaveLength(1); + ok(await a.run(["close"])); + expect(await listLeases(env)).toEqual([]); + ok(await open(a)); + expect(await listLeases(env)).toHaveLength(1); + }, + ); + + it( + "after an accepted upload install and snapshot, install from a remote: path, boot, shutdown and snapshot --ios-simulator-device-set (on Android also --android-device-allowlist ) are refused, and the device is still leased and answers snapshot", + { 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(["snapshot"])); + const [lease] = await listLeases(env); + const driverId = (await listDevices(env)).find((device) => device.id === lease?.deviceId) + ?.driverDeviceId as string; + const dir = await mkdtemp(join(tmpdir(), "simlock-ad-set-")); + onTestFinished(() => rm(dir, { force: true, recursive: true })); + + refused(await a.run(["install", "Appduct", "remote:/data/local/tmp/Appduct"])); + for (const command of ["boot", "shutdown"]) { + const denied = await a.run([command]); + expect(denied.code, `${command} was accepted`).not.toBe(0); + expect(denied.error?.code).toBe("UNAUTHORIZED"); + expect(denied.error?.details?.reason).toBe("DAEMON_POLICY_DENIED"); + } + for (const flags of target.forbiddenFlags(driverId, dir)) { + refused(await a.run(["snapshot", ...flags])); + } + + expect(await listLeases(env)).toHaveLength(1); + ok(await a.run(["snapshot"])); + }, + ); + + it( + "simlock release --all ends the agent's agent-device session before the device is wiped: no session sample starts after the wipe began, the last sample finds no session, another agent's open gets that same device where opening the fixture app fails, and the first agent's next command fails with lease ended by simlock", + { timeout: 900_000 }, + async () => { + const a = await agent("a"); + const b = await agent("b"); + ok(await open(a)); + ok(await a.run(["install", "Appduct", target.app])); + ok(await a.run(["open", target.bundleId])); + expect(listField(await a.run(["session", "list"]), "sessions").length).toBeGreaterThan(0); + const [lease] = await listLeases(env); + const startedAt = Date.now(); + + const samples: { at: number; hasSession: boolean }[] = []; + const sampling = waitFor( + async () => { + const at = Date.now(); + const sessions = listField(await a.run(["session", "list"]), "sessions"); + samples.push({ at, hasSession: sessions.length > 0 }); + const devices = await listDevices(env); + return Date.now() - startedAt > 2_000 && devices.every((d) => d.state === "ready"); + }, + { timeout: 240_000, interval: 250, label: "device ready after release --all" }, + ); + const released = await env.cli(["release", "--all", "--yes"], { timeout: 60_000 }); + expect(released.code, released.stderr).toBe(0); + await sampling; + + const reclaimed = await eventAfter(env, "device.reclaimed", startedAt); + expect(reclaimed, "no device.reclaimed after release --all").toBeDefined(); + const wipeStart = wipeStartOf(reclaimed as RecordedEvent); + expect(samples.some((sample) => !sample.hasSession)).toBe(true); + expect(samples.at(-1)?.hasSession).toBe(false); + expect( + samples.filter((sample) => sample.hasSession && sample.at >= wipeStart), + "a sample saw the session after the wipe began", + ).toEqual([]); + + ok(await open(b)); + expect((await listLeases(env))[0]?.deviceId).toBe(lease?.deviceId); + const reopened = await b.run(["open", target.bundleId]); + expect(reopened.code, "the fixture app survived the wipe").not.toBe(0); + const next = await a.run(["snapshot"]); + expect(next.code).not.toBe(0); + expect(failureText(next)).toContain("lease ended by simlock"); + }, + ); + + it( + "a wait 20000 running when simlock release --all is called exits 0 after at least 20 s, and the wipe starts after it exits", + { timeout: 600_000 }, + async () => { + const a = await agent("a"); + ok(await open(a)); + const [lease] = await listLeases(env); + const startedAt = Date.now(); + const running = a.start(["wait", "20000"]); + await waitFor( + async () => + (await eventAfter(env, "lease.renewed", startedAt, forLease(lease?.id))) !== undefined, + { timeout: 60_000, interval: 500, label: "the wait's heartbeat renewed the lease" }, + ); + const releaseAt = Date.now(); + const released = await env.cli(["release", "--all", "--yes"], { timeout: 60_000 }); + expect(released.code, released.stderr).toBe(0); + + const result = await running.waitForExit(60_000); + const exitedAt = Date.now(); + expect(result.code).toBe(0); + expect(releaseAt, "the wait ended before release --all was called").toBeLessThan( + exitedAt - 2_000, + ); + expect(exitedAt - startedAt).toBeGreaterThanOrEqual(20_000); + + await waitFor( + async () => (await eventAfter(env, "device.reclaimed", startedAt)) !== undefined, + { timeout: 240_000, interval: 1_000, label: "device.reclaimed" }, + ); + const reclaimed = (await eventAfter(env, "device.reclaimed", startedAt)) as RecordedEvent; + expect(wipeStartOf(reclaimed)).toBeGreaterThanOrEqual(exitedAt - 1_000); + }, + ); + + it( + "with the only device leased, a second agent's open waits in simlock list --requests; killing its CLI empties the queue, and once the device is free no lease.granted names that request's requester while a third agent's open gets the device", + { timeout: 900_000 }, + async () => { + const a = await agent("a"); + const b = await agent("b"); + const c = await agent("c"); + ok(await open(a)); + const startedAt = Date.now(); + const waiting = b.start(["open", "--platform", platform]); + let requests: RequestRow[] = []; + await waitFor( + async () => { + requests = await listRequests(env); + return requests.length === 1; + }, + { timeout: 60_000, interval: 500, label: "b's open queued" }, + ); + const requester = requests[0]?.requesterId as string; + waiting.kill("SIGKILL"); + await waitFor(async () => (await listRequests(env)).length === 0, { + timeout: 60_000, + interval: 500, + label: "queue empty after killing b's CLI", + }); + + ok(await a.run(["close"])); + await waitForFree(env); + ok(await open(c)); + expect(await listLeases(env)).toHaveLength(1); + const granted = (await env.events()).filter( + (event) => + event.event === "lease.granted" && + event.timestamp >= startedAt && + (event.payload as { requesterId?: string }).requesterId === requester, + ); + expect(granted).toEqual([]); + }, + ); + + it( + "when the agent-device daemon is killed, a new one with a new pid runs; the agent's next command fails with lease ended by simlock, and its simlock lease is released", + { timeout: 900_000 }, + async () => { + const a = await agent("a"); + ok(await open(a)); + const old = await readPidRecord(env); + process.kill(old.pid, "SIGKILL"); + await waitFor( + async () => { + const now = await readPidRecord(env); + return now.pid !== old.pid && isAlive(now.pid); + }, + { timeout: 60_000, interval: 500, label: "a new agent-device daemon runs" }, + ); + await awaitAgentDevice(); + + const next = await a.run(["snapshot"]); + expect(next.code).not.toBe(0); + expect(failureText(next)).toContain("lease ended by simlock"); + await waitFor(async () => (await listLeases(env)).length === 0, { + timeout: 60_000, + interval: 500, + label: "a's simlock lease released", + }); + }, + ); + + it( + "after the simlock daemon is killed and started again, the old agent-device daemon's pid is gone within 60 s; the agent's next command fails with lease ended by simlock, and its old simlock lease is released", + { timeout: 900_000 }, + async () => { + const a = await agent("a"); + ok(await open(a)); + const [lease] = await listLeases(env); + const old = await readPidRecord(env); + onTestFinished(() => killIfStillAgentDevice(old)); + + await env.killDaemon(); + await env.startDaemon(); + await awaitAgentDevice(); + + await waitFor(() => !isAlive(old.pid), { + timeout: 60_000, + interval: 500, + label: "the old agent-device daemon is gone", + }); + const next = await a.run(["snapshot"]); + expect(next.code).not.toBe(0); + expect(failureText(next)).toContain("lease ended by simlock"); + await waitFor(async () => !(await listLeases(env)).some((row) => row.id === lease?.id), { + timeout: 60_000, + interval: 500, + label: "the old lease released", + }); + }, + ); + + it( + "with agentDevice.leaseTtlCapMs 20000, an agent that sends no more commands gets lease.expired at most 25 s after its last command, and another agent's open then gets the device", + { timeout: 900_000 }, + async () => { + await env.withConfig({ agentDevice: { leaseTtlCapMs: 20_000 } }, async () => { + await awaitAgentDevice(); + const a = await agent("a"); + const b = await agent("b"); + ok(await open(a)); + const [lease] = await listLeases(env); + const lastCommandAt = Date.now(); + + let expired: RecordedEvent | undefined; + await waitFor( + async () => { + expired = await eventAfter( + env, + "lease.expired", + lastCommandAt - 5_000, + forLease(lease?.id), + ); + return expired !== undefined; + }, + { timeout: 60_000, interval: 1_000, label: "lease.expired for a's lease" }, + ); + expect((expired as RecordedEvent).timestamp - lastCommandAt).toBeLessThanOrEqual(25_000); + + ok(await open(b)); + expect(await listLeases(env)).toHaveLength(1); + }); + }, + ); + + it( + "with agentDevice.leaseTtlCapMs 20000, after a graceful simlock daemon restart an old simlock lease whose agent sends nothing gets lease.expired at most 5 s after the later of its last renewal + 20 s and the moment the restarted daemon answers simlock status", + { timeout: 900_000 }, + async () => { + await env.withConfig({ agentDevice: { leaseTtlCapMs: 20_000 } }, async () => { + await awaitAgentDevice(); + const a = await agent("a"); + ok(await open(a)); + const [lease] = await listLeases(env); + + await env.restart(); + const answeredAt = Date.now(); + + let expired: RecordedEvent | undefined; + await waitFor( + async () => { + expired = await eventAfter(env, "lease.expired", 0, forLease(lease?.id)); + return expired !== undefined; + }, + { timeout: 60_000, interval: 1_000, label: "lease.expired for the old lease" }, + ); + const lastRenewal = Math.max( + ...(await env.events()) + .filter( + (event) => + (event.event === "lease.granted" || event.event === "lease.renewed") && + forLease(lease?.id)(event), + ) + .map((event) => event.timestamp), + ); + expect((expired as RecordedEvent).timestamp).toBeLessThanOrEqual( + Math.max(lastRenewal + 20_000, answeredAt) + 5_000, + ); + }); + }, + ); + + it( + "with agentDevice.command pointing at an agent-device that reports 0.9.2, the daemon starts and grants a plain simlock lease --detach; an agent's open fails with agent-device is not available on this simlock: found 0.9.2, need 0.21.25 or later; simlock doctor reports agent-device-unavailable with found 0.9.2, need 0.21.25 or later", + { timeout: 900_000 }, + async () => { + const root = await mkdtemp(join(tmpdir(), "simlock-ad-old-")); + onTestFinished(() => rm(root, { force: true, recursive: true })); + const entry = join(root, "bin/agent-device.mjs"); + await mkdir(dirname(entry), { recursive: true }); + await mkdir(join(root, "dist/src"), { recursive: true }); + await writeFile(join(root, "package.json"), JSON.stringify({ name: "agent-device" })); + await writeFile(join(root, "dist/src/daemon.js"), ""); + await writeFile(entry, '#!/usr/bin/env node\nconsole.log("0.9.2");\n'); + await chmod(entry, 0o755); + const message = "found 0.9.2, need 0.21.25 or later"; + + await env.withConfig({ agentDevice: { command: entry } }, async () => { + const a = await agent("a"); + let finding: { kind: string; message: string } | undefined; + await waitFor( + async () => { + const doctor = await env.cli(["doctor", "--json"], { timeout: 60_000 }); + finding = ( + doctor.json as { findings: { kind: string; message: string }[] } + ).findings.find((row) => row.kind === "agent-device-unavailable"); + return finding !== undefined; + }, + { timeout: 60_000, interval: 500, label: "doctor reports agent-device-unavailable" }, + ); + expect(finding?.message).toContain(message); + + const plain = await env.cli( + ["lease", "--detach", "--platform", platform, "--agent-id", "plain"], + { timeout: 330_000 }, + ); + expect(plain.code, plain.stderr).toBe(0); + const released = await env.cli(["release", "--all", "--yes"], { timeout: 60_000 }); + expect(released.code, released.stderr).toBe(0); + await waitForFree(env); + + const opened = await open(a); + expect(opened.code).not.toBe(0); + expect(failureText(opened)).toContain( + `agent-device is not available on this simlock: ${message}`, + ); + }); + }, + ); + + describe("with the device limit raised to 2", () => { + beforeAll(async () => { + await setLimits(2); + await warmUp(2); + }, 420_000); + + afterAll(async () => { + await setLimits(1); + }, 420_000); + + it( + "with both devices ready, devices lists nothing before open, and after open only the device it bound, not the other ready device", + { timeout: 600_000 }, + async () => { + const a = await agent("a"); + expect((await listDevices(env)).filter((device) => device.state === "ready")).toHaveLength( + 2, + ); + const before = await a.run(["devices"]); + ok(before); + expect(listField(before, "devices")).toEqual([]); + + ok(await open(a)); + const [lease] = await listLeases(env); + const bound = (await listDevices(env)).find((device) => device.id === lease?.deviceId); + const after = await a.run(["devices"]); + ok(after); + expect(listField(after, "devices").map((device) => (device as { id: string }).id)).toEqual([ + bound?.driverDeviceId, + ]); + }, + ); + + it( + "two agents on two tokens get two different devices; B's snapshot naming its own device is accepted and naming A's is refused; after B's close, A's snapshot still works", + { timeout: 900_000 }, + async () => { + const a = await agent("a"); + const b = await agent("b"); + ok(await open(a)); + ok(await open(b)); + const leases = await listLeases(env); + expect(new Set(leases.map((lease) => lease.deviceId)).size).toBe(2); + const devices = await listDevices(env); + const driverIdOf = (who: Agent): string => { + const lease = leases.find((row) => row.requesterId === who.tokenId); + return devices.find((device) => device.id === lease?.deviceId)?.driverDeviceId as string; + }; + + ok(await b.run(["snapshot", target.deviceFlag, driverIdOf(b)])); + refused(await b.run(["snapshot", target.deviceFlag, driverIdOf(a)])); + ok(await b.run(["close"])); + ok(await a.run(["snapshot"])); + }, + ); + + it( + "with both devices booted, agent A holding one and agent B the other: A's test --shard-all 1 with no --device passes, and A's test --shard-all 2 with no --device fails with test sharding requires 2 devices, but only 1 matched", + { timeout: 900_000 }, + async () => { + const a = await agent("a"); + const b = await agent("b"); + ok(await open(a)); + ok(await open(b)); + const suite = await mkdtemp(join(tmpdir(), "simlock-ad-suite-")); + onTestFinished(() => rm(suite, { force: true, recursive: true })); + await writeFile(join(suite, "smoke.ad"), "snapshot\n"); + + ok(await a.run(["test", suite, "--shard-all", "1"])); + const two = await a.run(["test", suite, "--shard-all", "2"]); + expect(two.code).not.toBe(0); + expect(failureText(two)).toContain("test sharding requires 2 devices, but only 1 matched"); + }, + ); + }); +} + +describe.skipIf(AGENT_DEVICE === undefined || !iosAvailable)( + "agent-device through simlock (iOS)", + { tags: ["slow", "ios"] }, + () => defineSuite(IOS), +); + +describe.skipIf(AGENT_DEVICE === undefined || !androidAvailable)( + "agent-device through simlock (Android)", + { tags: ["slow", "android"] }, + () => defineSuite(ANDROID), +); From 8a4a57ce47bb7e77ddc7e6da318cf6dbe84d315d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 13:29:38 +0200 Subject: [PATCH 02/18] test(e2e): agent-device helpers and a shared simlock daemon for the slow lane (#477) Implements withSharedDaemon, makeAgent, newAgentToken, cleanupAgents and waitForAgentDevice. 15 failing -> 15 unproven: no agent-device build here, so the hardware run is left to the slow lane. --- e2e/helpers/agent-device.ts | 113 +++++++++++++++++++++++++++++++++--- e2e/helpers/cli.ts | 5 +- e2e/helpers/env.ts | 69 ++++++++++++++++++---- 3 files changed, 165 insertions(+), 22 deletions(-) diff --git a/e2e/helpers/agent-device.ts b/e2e/helpers/agent-device.ts index 2a99c9aeb..62d4b932e 100644 --- a/e2e/helpers/agent-device.ts +++ b/e2e/helpers/agent-device.ts @@ -1,5 +1,10 @@ -import type { CliBackgroundHandle } from "./cli.js"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { cli, cliBackground, type CliBackgroundHandle } from "./cli.js"; import type { SharedTestEnv } from "./env.js"; +import { waitFor } from "./wait.js"; export interface AgentDeviceResult { readonly code: number | null; @@ -23,18 +28,108 @@ export interface Agent { start(args: readonly string[]): CliBackgroundHandle; } -export function newAgentToken(_env: SharedTestEnv): Promise<{ secret: string; id: string }> { - return Promise.reject(new Error("newAgentToken is not implemented")); +interface MadeAgent { + readonly env: SharedTestEnv; + readonly agent: Agent; + readonly background: Set; +} + +const made: MadeAgent[] = []; + +function agentDeviceEntry(): string { + const entry = process.env.SIMLOCK_E2E_AGENT_DEVICE; + if (entry === undefined || entry === "") throw new Error("SIMLOCK_E2E_AGENT_DEVICE is not set"); + return entry; +} + +function proxyUrl(env: SharedTestEnv): string { + return `http://127.0.0.1:${env.httpPort}/v1/agent-device`; +} + +export async function newAgentToken(env: SharedTestEnv): Promise<{ secret: string; id: string }> { + const created = await env.cli(["token", "create", "--role", "agent"], { timeout: 60_000 }); + if (created.code !== 0) throw new Error(`simlock token create failed: ${created.stderr}`); + const body = created.json as { token: { id: string }; secret: string }; + return { secret: body.secret, id: body.token.id }; +} + +function parseResult(code: number | null, stdout: string, stderr: string): AgentDeviceResult { + let json: unknown; + try { + json = JSON.parse(stdout.trim()); + } catch { + json = undefined; + } + const envelope = json as + | { data?: unknown; error?: AgentDeviceResult["error"] } + | null + | undefined; + const record = typeof envelope === "object" && envelope !== null ? envelope : undefined; + return { code, stdout, stderr, json, data: record?.data, error: record?.error }; } -export function makeAgent(_env: SharedTestEnv, _name: string): Promise { - return Promise.reject(new Error("makeAgent is not implemented")); +export async function makeAgent(env: SharedTestEnv, name: string): Promise { + const token = await newAgentToken(env); + const home = await mkdtemp(join(tmpdir(), `simlock-ad-${name}-`)); + const entry = agentDeviceEntry(); + const childEnv: NodeJS.ProcessEnv = { + ...process.env, + AGENT_DEVICE_STATE_DIR: home, + AGENT_DEVICE_DAEMON_AUTH_TOKEN: token.secret, + AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1", + }; + const background = new Set(); + const agent: Agent = { + name, + home, + token: token.secret, + tokenId: token.id, + async run(args, options = {}) { + const result = await cli(["--json", ...args], childEnv, { + entry, + timeout: options.timeout ?? 120_000, + }); + return parseResult(result.code, result.stdout, result.stderr); + }, + start(args) { + const handle = cliBackground(["--json", ...args], childEnv, { entry }); + background.add(handle); + return handle; + }, + }; + made.push({ env, agent, background }); + const connected = await agent.run(["connect", "proxy", "--daemon-base-url", proxyUrl(env)]); + if (connected.code !== 0) { + throw new Error(`agent-device connect proxy failed: ${connected.stdout}\n${connected.stderr}`); + } + return agent; } -export function cleanupAgents(): Promise { - return Promise.reject(new Error("cleanupAgents is not implemented")); +export async function cleanupAgents(): Promise { + const agents = made.splice(0); + await Promise.allSettled( + agents.map(async ({ env, agent, background }) => { + for (const handle of background) handle.kill("SIGKILL"); + await Promise.all( + [...background].map((handle) => handle.waitForExit(10_000).catch(() => undefined)), + ); + await agent.run(["disconnect"], { timeout: 60_000 }).catch(() => undefined); + await env.cli(["token", "revoke", agent.tokenId], { timeout: 30_000 }).catch(() => undefined); + await rm(agent.home, { force: true, recursive: true }); + }), + ); } -export function waitForAgentDevice(_env: SharedTestEnv, _token: string): Promise { - return Promise.reject(new Error("waitForAgentDevice is not implemented")); +export async function waitForAgentDevice(env: SharedTestEnv, token: string): Promise { + await waitFor( + async () => { + const response = await fetch(`${proxyUrl(env)}/rpc`, { + body: JSON.stringify({ id: 1, jsonrpc: "2.0", method: "agent_device.probe" }), + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + method: "POST", + }); + return response.status !== 503; + }, + { timeout: 90_000, interval: 500, label: "the agent-device route answers" }, + ); } diff --git a/e2e/helpers/cli.ts b/e2e/helpers/cli.ts index d197a623b..e460792a3 100644 --- a/e2e/helpers/cli.ts +++ b/e2e/helpers/cli.ts @@ -9,6 +9,7 @@ export interface CliOptions { readonly env?: NodeJS.ProcessEnv; readonly input?: string; readonly timeout?: number; + readonly entry?: string; } export interface CliError { @@ -36,7 +37,7 @@ export function cli( options: CliOptions = {}, ): Promise { return new Promise((resolve, reject) => { - const child = spawn(process.execPath, [CLI_ENTRY, ...args], { + const child = spawn(process.execPath, [options.entry ?? CLI_ENTRY, ...args], { env: { ...env, ...options.env }, }); let stdout = ""; @@ -87,7 +88,7 @@ export function cliBackground( env: NodeJS.ProcessEnv, options: CliOptions = {}, ): CliBackgroundHandle { - const child = spawn(process.execPath, [CLI_ENTRY, ...args], { + const child = spawn(process.execPath, [options.entry ?? CLI_ENTRY, ...args], { env: { ...env, ...options.env }, }); let stdout = ""; diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 309f07970..354a6f472 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -178,6 +178,14 @@ export interface TestEnv { * it itself (e.g. `waitForLeaseCount(env, 0)`). */ export async function withDaemon(options: WithDaemonOptions = {}): Promise { + const { testEnv, state } = await buildEnv(options); + activeEnvs.add(state); + return testEnv; +} + +async function buildEnv( + options: WithDaemonOptions, +): Promise<{ testEnv: TestEnv; state: TeardownState }> { const home = await mkdtemp(join(tmpdir(), "simlock-e2e-")); const socketPath = join(home, "daemon.sock"); const logPath = join(home, "daemon.log"); @@ -315,15 +323,17 @@ export async function withDaemon(options: WithDaemonOptions = {}): Promise; } -export function withSharedDaemon(_options: WithDaemonOptions = {}): Promise { - return Promise.reject(new Error("withSharedDaemon is not implemented")); +export async function withSharedDaemon(options: WithDaemonOptions = {}): Promise { + const port = (options.configOverrides?.http as { port?: unknown } | undefined)?.port; + if (typeof port !== "number") { + throw new Error("withSharedDaemon needs configOverrides.http.port"); + } + const { testEnv, state } = await buildEnv(options); + return { + ...testEnv, + httpPort: port, + restart: () => testEnv.restartDaemon(), + teardown: () => teardown(state), + }; } interface TeardownState { @@ -404,6 +424,7 @@ async function teardown(state: TeardownState): Promise { // simulator keeps writing into its device directory while `rm` below walks it (`ENOTEMPTY`), // then outlives the home. The daemon is stopped by now, so nothing boots another one. if (realDrivers) await emptyDeviceSet(iosDeviceSet(home)); + await killLeftoverAgentDevice(home); await rm(home, { force: true, recursive: true }); if (strayPids.length > 0) { @@ -413,6 +434,32 @@ async function teardown(state: TeardownState): Promise { } } +async function killLeftoverAgentDevice(home: string): Promise { + const text = await readFileIfExists(join(home, "agent-device-daemon.json")); + if (text === undefined) return; + let record: { pid?: unknown; entry?: unknown }; + try { + record = JSON.parse(text) as { pid?: unknown; entry?: unknown }; + } catch { + return; + } + if (typeof record.pid !== "number" || typeof record.entry !== "string") return; + if (!(await isProcessAlive(record.pid))) return; + const { stdout } = await execFileAsync("ps", [ + "-ww", + "-o", + "args=", + "-p", + String(record.pid), + ]).catch(() => ({ stdout: "" })); + if (!stdout.includes(record.entry)) return; + try { + process.kill(record.pid, "SIGKILL"); + } catch { + // why: the record may name a process that exited since the check. + } +} + /** * Signal-0 liveness probe: sends no actual signal, just asks the kernel whether * `pid` exists and is ours to signal. Throws ESRCH (gone) or EPERM (exists, not From e0f64894fd8846676df0d25093019b6b27152ac8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 13:30:07 +0200 Subject: [PATCH 03/18] test(e2e): split env building to keep complexity down (#477) --- e2e/helpers/env.ts | 48 +++++++++++++++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 354a6f472..fea502deb 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -183,18 +183,14 @@ export async function withDaemon(options: WithDaemonOptions = {}): Promise { - const home = await mkdtemp(join(tmpdir(), "simlock-e2e-")); - const socketPath = join(home, "daemon.sock"); - const logPath = join(home, "daemon.log"); - const configPath = join(home, "config.json"); - const scriptPath = join(home, "fake-driver-script.json"); - const logCallPath = join(home, "fake-driver-calls.jsonl"); - + home: string, + scriptPath: string, + logCallPath: string, +): NodeJS.ProcessEnv { const useFakeDriver = options.driver === undefined || options.driver === "fake"; - const env: NodeJS.ProcessEnv = { + return { ...process.env, SIMLOCK_HOME: home, ...(useFakeDriver @@ -209,13 +205,35 @@ async function buildEnv( : {}), ...(options.agentId === undefined ? {} : { SIMLOCK_AGENT_ID: options.agentId }), }; +} + +function seedConfig( + options: WithDaemonOptions, + adbServerPort: number | undefined, +): Record | undefined { + if (options.driver === undefined || options.driver === "fake") { + return mergeDeep(FAKE_LANE_BASE_CONFIG, options.configOverrides ?? {}); + } + if (options.driver === "real") { + return mergeDeep({ drivers: { android: { adbServerPort } } }, options.configOverrides ?? {}); + } + return options.configOverrides; +} + +async function buildEnv( + options: WithDaemonOptions, +): Promise<{ testEnv: TestEnv; state: TeardownState }> { + const home = await mkdtemp(join(tmpdir(), "simlock-e2e-")); + const socketPath = join(home, "daemon.sock"); + const logPath = join(home, "daemon.log"); + const configPath = join(home, "config.json"); + const scriptPath = join(home, "fake-driver-script.json"); + const logCallPath = join(home, "fake-driver-calls.jsonl"); + + const env = processEnv(options, home, scriptPath, logCallPath); const adbServerPort = options.driver === "real" ? await freeLoopbackPort() : undefined; - const seededConfig = useFakeDriver - ? mergeDeep(FAKE_LANE_BASE_CONFIG, options.configOverrides ?? {}) - : options.driver === "real" - ? mergeDeep({ drivers: { android: { adbServerPort } } }, options.configOverrides ?? {}) - : (options.configOverrides ?? {}); + const seededConfig = seedConfig(options, adbServerPort); if (seededConfig !== undefined) { await writeFile(configPath, `${JSON.stringify(seededConfig, null, 2)}\n`, "utf8"); } From 86383d14fe933d171afaba800102161219521a33 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 13:32:07 +0200 Subject: [PATCH 04/18] test(e2e): agent env drops AGENT_DEVICE_* and sets HOME; shared daemon restart waits for exit; teardown kills leftover by marker; health wait (#477) --- e2e/helpers/agent-device.ts | 25 +++++++++---- e2e/helpers/env.ts | 75 ++++++++++++++++++++++++++----------- 2 files changed, 71 insertions(+), 29 deletions(-) diff --git a/e2e/helpers/agent-device.ts b/e2e/helpers/agent-device.ts index 62d4b932e..e399edf8e 100644 --- a/e2e/helpers/agent-device.ts +++ b/e2e/helpers/agent-device.ts @@ -72,8 +72,13 @@ export async function makeAgent(env: SharedTestEnv, name: string): Promise !key.startsWith("AGENT_DEVICE_")), + ); const childEnv: NodeJS.ProcessEnv = { - ...process.env, + ...inherited, + HOME: home, AGENT_DEVICE_STATE_DIR: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: token.secret, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1", @@ -123,13 +128,17 @@ export async function cleanupAgents(): Promise { export async function waitForAgentDevice(env: SharedTestEnv, token: string): Promise { await waitFor( async () => { - const response = await fetch(`${proxyUrl(env)}/rpc`, { - body: JSON.stringify({ id: 1, jsonrpc: "2.0", method: "agent_device.probe" }), - headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, - method: "POST", - }); - return response.status !== 503; + try { + const response = await fetch(`${proxyUrl(env)}/health`, { + headers: { authorization: `Bearer ${token}` }, + }); + if (response.status !== 200) return false; + const body = (await response.json()) as { ok?: unknown }; + return body.ok === true; + } catch { + return false; + } }, - { timeout: 90_000, interval: 500, label: "the agent-device route answers" }, + { timeout: 60_000, interval: 500, label: "the agent-device daemon answers /health" }, ); } diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index fea502deb..a1e44554b 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -1,6 +1,6 @@ import { execFile } from "node:child_process"; import { existsSync } from "node:fs"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; @@ -366,11 +366,45 @@ export async function withSharedDaemon(options: WithDaemonOptions = {}): Promise throw new Error("withSharedDaemon needs configOverrides.http.port"); } const { testEnv, state } = await buildEnv(options); + const restart = async (): Promise => { + const pids = await pidsHoldingSocket(state.socketPath); + await cli(["daemon", "stop"], state.env); + await waitFor( + async () => !(await Promise.all(pids.map((pid) => isProcessAlive(pid)))).some(Boolean), + { timeout: 30_000, label: "previous daemon process exited" }, + ); + await testEnv.startDaemon(); + }; return { ...testEnv, httpPort: port, - restart: () => testEnv.restartDaemon(), - teardown: () => teardown(state), + restart, + async withConfig(overrides, fn) { + const previous = await readFileIfExists(testEnv.configPath); + const merged = mergeDeep( + previous === undefined ? {} : (JSON.parse(previous) as Record), + overrides, + ); + await writeFile(testEnv.configPath, `${JSON.stringify(merged, null, 2)}\n`, "utf8"); + await restart(); + try { + return await fn(); + } finally { + if (previous === undefined) await rm(testEnv.configPath, { force: true }); + else await writeFile(testEnv.configPath, previous, "utf8"); + await restart(); + } + }, + async teardown() { + // why: read before teardown deletes the home. + const pid = await readAgentDevicePid(state.home); + const resolved = await realpath(state.home).catch(() => state.home); + try { + await teardown(state); + } finally { + await killLeftoverAgentDevice(resolved, pid); + } + }, }; } @@ -442,7 +476,6 @@ async function teardown(state: TeardownState): Promise { // simulator keeps writing into its device directory while `rm` below walks it (`ENOTEMPTY`), // then outlives the home. The daemon is stopped by now, so nothing boots another one. if (realDrivers) await emptyDeviceSet(iosDeviceSet(home)); - await killLeftoverAgentDevice(home); await rm(home, { force: true, recursive: true }); if (strayPids.length > 0) { @@ -452,29 +485,29 @@ async function teardown(state: TeardownState): Promise { } } -async function killLeftoverAgentDevice(home: string): Promise { +async function readAgentDevicePid(home: string): Promise { const text = await readFileIfExists(join(home, "agent-device-daemon.json")); - if (text === undefined) return; - let record: { pid?: unknown; entry?: unknown }; + if (text === undefined) return undefined; try { - record = JSON.parse(text) as { pid?: unknown; entry?: unknown }; + const record = JSON.parse(text) as { pid?: unknown }; + return typeof record.pid === "number" ? record.pid : undefined; } catch { - return; + return undefined; } - if (typeof record.pid !== "number" || typeof record.entry !== "string") return; - if (!(await isProcessAlive(record.pid))) return; - const { stdout } = await execFileAsync("ps", [ - "-ww", - "-o", - "args=", - "-p", - String(record.pid), - ]).catch(() => ({ stdout: "" })); - if (!stdout.includes(record.entry)) return; +} + +async function killLeftoverAgentDevice(home: string, pid: number | undefined): Promise { + if (pid === undefined || !(await isProcessAlive(pid))) return; + const { stdout } = await execFileAsync("ps", ["-ww", "-o", "args=", "-p", String(pid)]).catch( + () => ({ stdout: "" }), + ); + // why: the supervisor puts the resolved home in the marker; the caller resolved it before the home was removed. + const marker = `--simlock-home=${home}`; + if (!stdout.trim().endsWith(marker)) return; try { - process.kill(record.pid, "SIGKILL"); + process.kill(pid, "SIGKILL"); } catch { - // why: the record may name a process that exited since the check. + // why: the process may have exited since the check. } } From aba056dda2fa258871ba0b145086f17dbdfe5e39 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 13:40:24 +0200 Subject: [PATCH 05/18] test(e2e): never-granted filter reads requester; module-level cleanup backstop; 60 s agent CLI default; 90 s restart limit (#477) --- e2e/helpers/agent-device.ts | 10 +++++++++- e2e/helpers/env.ts | 15 +++++++++++++-- e2e/slow-agent-device.test.ts | 2 +- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/e2e/helpers/agent-device.ts b/e2e/helpers/agent-device.ts index e399edf8e..59fc9d5ea 100644 --- a/e2e/helpers/agent-device.ts +++ b/e2e/helpers/agent-device.ts @@ -2,6 +2,8 @@ import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { afterEach } from "vitest"; + import { cli, cliBackground, type CliBackgroundHandle } from "./cli.js"; import type { SharedTestEnv } from "./env.js"; import { waitFor } from "./wait.js"; @@ -92,7 +94,7 @@ export async function makeAgent(env: SharedTestEnv, name: string): Promise { ); } +// why: vitest resolves hooks from the call stack active during collection, so this is registered +// once at module scope; a test that times out never reaches its own cleanup. +afterEach(async () => { + await cleanupAgents(); +}, 120_000); + export async function waitForAgentDevice(env: SharedTestEnv, token: string): Promise { await waitFor( async () => { diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index a1e44554b..6c03bc2d1 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -366,15 +366,26 @@ export async function withSharedDaemon(options: WithDaemonOptions = {}): Promise throw new Error("withSharedDaemon needs configOverrides.http.port"); } const { testEnv, state } = await buildEnv(options); - const restart = async (): Promise => { + const restartSteps = async (): Promise => { const pids = await pidsHoldingSocket(state.socketPath); - await cli(["daemon", "stop"], state.env); + await cli(["daemon", "stop"], state.env, { timeout: 30_000 }); await waitFor( async () => !(await Promise.all(pids.map((pid) => isProcessAlive(pid)))).some(Boolean), { timeout: 30_000, label: "previous daemon process exited" }, ); await testEnv.startDaemon(); }; + const restart = async (): Promise => { + let timer: NodeJS.Timeout | undefined; + const limit = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error("shared daemon restart exceeded 90 s")), 90_000); + }); + try { + await Promise.race([restartSteps(), limit]); + } finally { + clearTimeout(timer); + } + }; return { ...testEnv, httpPort: port, diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index f6f4a2cef..b10ff7cfc 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -456,7 +456,7 @@ function defineSuite(target: Target): void { (event) => event.event === "lease.granted" && event.timestamp >= startedAt && - (event.payload as { requesterId?: string }).requesterId === requester, + (event.payload as { requester?: string }).requester === requester, ); expect(granted).toEqual([]); }, From 6e5757f34ec88ba737c32bbe5b5c096ebe631807 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 14:03:59 +0200 Subject: [PATCH 06/18] fix(agent-device): accept the backend connect proxy sends on allocate; e2e: pinned build check, fail fast on open, show health reply (#477) --- docs/HTTP-API.md | 5 +-- e2e/helpers/agent-device.ts | 50 ++++++++++++++++++++++++++---- e2e/helpers/index.ts | 8 ++++- e2e/slow-agent-device.test.ts | 17 ++++++---- src/agent-device/edge.test.ts | 24 ++++++++++++++ src/agent-device/front/allocate.ts | 15 ++++++++- 6 files changed, 103 insertions(+), 16 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 0353edd7b..41743fee9 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1550,8 +1550,9 @@ the status. a heartbeat. - `lease ended by simlock; run disconnect, then open`: a heartbeat for a lease Simlock ended. -- `refused: simlock leases only plain devices`: `backend`, - `retainOnClose: true`, a `provider*` or `aws*` key, or a `leaseProvider` +- `refused: simlock leases only plain devices`: a `backend` other than + `ios-instance` on iOS or `android-instance` on Android (the one + `connect proxy` sends), `retainOnClose: true`, a `provider*` or `aws*` key, or a `leaseProvider` other than `proxy`. - `refused: agent-device through simlock needs an agent token`. - `refused: request body over 1 MiB` and `refused: send one JSON-RPC request` diff --git a/e2e/helpers/agent-device.ts b/e2e/helpers/agent-device.ts index 59fc9d5ea..04dc32dc8 100644 --- a/e2e/helpers/agent-device.ts +++ b/e2e/helpers/agent-device.ts @@ -1,11 +1,14 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { execFileSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { isAbsolute, join } from "node:path"; import { afterEach } from "vitest"; import { cli, cliBackground, type CliBackgroundHandle } from "./cli.js"; import type { SharedTestEnv } from "./env.js"; +import { REPO_ROOT } from "./repo-root.js"; import { waitFor } from "./wait.js"; export interface AgentDeviceResult { @@ -44,6 +47,33 @@ function agentDeviceEntry(): string { return entry; } +// why: the slow lane must run the integration build the repo pins, never an agent-device installed on the machine; the pinned version is in the vendored tarball's name. +export async function assertPinnedAgentDevice(): Promise { + const entry = agentDeviceEntry(); + if (!isAbsolute(entry) || !existsSync(entry)) { + throw new Error( + `SIMLOCK_E2E_AGENT_DEVICE ${entry} is not an absolute path to an existing file`, + ); + } + const manifest = JSON.parse(await readFile(join(REPO_ROOT, "package.json"), "utf8")) as { + dependencies?: Record; + }; + const pinned = /agent-device-proxy-(.+)-[0-9a-f]{7,}\.tgz$/.exec( + manifest.dependencies?.["@agent-device/proxy"] ?? "", + )?.[1]; + if (pinned === undefined) throw new Error("package.json does not pin @agent-device/proxy"); + const actual = execFileSync(process.execPath, [entry, "--version"], { + encoding: "utf8", + timeout: 60_000, + }).trim(); + if (actual !== pinned) { + throw new Error( + `SIMLOCK_E2E_AGENT_DEVICE ${entry} is version ${actual}, the pinned build is ${pinned}`, + ); + } + return entry; +} + function proxyUrl(env: SharedTestEnv): string { return `http://127.0.0.1:${env.httpPort}/v1/agent-device`; } @@ -134,19 +164,27 @@ afterEach(async () => { }, 120_000); export async function waitForAgentDevice(env: SharedTestEnv, token: string): Promise { + let last = "no answer"; await waitFor( async () => { try { const response = await fetch(`${proxyUrl(env)}/health`, { headers: { authorization: `Bearer ${token}` }, }); - if (response.status !== 200) return false; - const body = (await response.json()) as { ok?: unknown }; - return body.ok === true; + const text = await response.text(); + if (response.status < 200 || response.status > 299) { + last = `HTTP ${response.status}: ${text}`; + return false; + } + return (JSON.parse(text) as { ok?: unknown }).ok === true; } catch { return false; } }, - { timeout: 60_000, interval: 500, label: "the agent-device daemon answers /health" }, + { + timeout: 60_000, + interval: 500, + label: () => `the agent-device daemon answers /health (last reply: ${last})`, + }, ); } diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index 2e96cdf05..d950693e3 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -3,7 +3,13 @@ // moment a flow needs it, rather than pre-declaring the full internal surface, so an // unused re-export is always a real signal. export { withDaemon, withSharedDaemon } from "./env.js"; -export { cleanupAgents, makeAgent, newAgentToken, waitForAgentDevice } from "./agent-device.js"; +export { + assertPinnedAgentDevice, + cleanupAgents, + makeAgent, + newAgentToken, + waitForAgentDevice, +} from "./agent-device.js"; export type { Agent, AgentDeviceResult } from "./agent-device.js"; export { freeLoopbackPort } from "./port.js"; // A flow that factors its own setup out of a test body needs to name what `withDaemon` hands diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index b10ff7cfc..6f321b23c 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -1,11 +1,11 @@ import { execFileSync } from "node:child_process"; -import { existsSync } 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"; import { afterAll, afterEach, beforeAll, describe, expect, it, onTestFinished } from "vitest"; import { + assertPinnedAgentDevice, cleanupAgents, freeLoopbackPort, makeAgent, @@ -191,7 +191,14 @@ function defineSuite(target: Target): void { let env: SharedTestEnv; const agent = (name: string): Promise => makeAgent(env, name); - const open = (who: Agent) => who.run(["open", "--platform", platform], { timeout: 330_000 }); + // 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 && !expectingOpenFailure) { + throw new Error(`open failed for ${who.name}: ${result.stdout}\n${result.stderr}`); + } + return result; + }; async function awaitAgentDevice(): Promise { const probe = await newAgentToken(env); @@ -232,14 +239,12 @@ function defineSuite(target: Target): void { } beforeAll(async () => { - if (AGENT_DEVICE === undefined || !existsSync(AGENT_DEVICE)) { - throw new Error(`SIMLOCK_E2E_AGENT_DEVICE ${String(AGENT_DEVICE)} does not exist`); - } + const pinned = await assertPinnedAgentDevice(); env = await withSharedDaemon({ driver: "real", configOverrides: { http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, - agentDevice: { enabled: true, command: AGENT_DEVICE }, + agentDevice: { enabled: true, command: pinned }, capacity: { config: { limits: { [platform]: { maxDevices: 1, maxRunning: 1 } } }, }, diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 8a2ab9d2f..58f949918 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -761,6 +761,11 @@ describe("the agent-device front, through the whole worker daemon", () => { params: (n) => allocateParams(n, { backend: "cloud" }), title: "backend", }, + { + message: plainOnly, + params: (n) => allocateParams(n, { backend: "android-instance" }), + title: "the Android backend on an iOS allocate", + }, { message: plainOnly, params: (n) => allocateParams(n, { retainOnClose: true }), @@ -806,6 +811,25 @@ describe("the agent-device front, through the whole worker daemon", () => { ); }); + it("an allocate in the shape connect proxy sends, with backend ios-instance, is granted and keeps the backend toward the agent-device daemon", async () => { + const rig = await setUp(); + + const answer = await envelopeOf( + await allocate(rig, 1, { + backend: "ios-instance", + runId: "proxy-1", + session: "adc-1", + tenantId: "proxy", + }), + ); + + expect(answer.result).toMatchObject({ ok: true }); + expect((await leases(rig)).map((lease) => lease.id)).toEqual([hex(1)]); + expect(allocatesReceived(rig, 1).map((received) => received.params?.["backend"])).toEqual([ + "ios-instance", + ]); + }); + it("allocate and release sent as `agent-device.lease.allocate` and `agent-device.lease.release` act exactly as the `agent_device.lease.*` spelling", async () => { const rig = await setUp(); diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index 4046cd32d..f7b54d4ef 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -44,10 +44,23 @@ interface Plan { readonly ttlMs?: number; } +// why: connect proxy names the backend that rents the platform (ios-instance, android-instance) on every allocate; any other backend is a different kind of device. +const BACKEND_OF_PLATFORM: Record = { + android: "android-instance", + ios: "ios-instance", +}; + +function foreignBackend(params: Record): boolean { + const backend = params["backend"]; + if (!present(backend)) return false; + const platform = params["platform"]; + return typeof platform !== "string" || BACKEND_OF_PLATFORM[platform] !== backend; +} + function notPlain(params: Record): boolean { const provider = params["leaseProvider"]; return ( - present(params["backend"]) || + foreignBackend(params) || params["retainOnClose"] === true || (present(provider) && provider !== "proxy") || Object.entries(params).some( From 56aa45bde9327096ae6bd46c44736ca74d2952c5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 14:04:31 +0200 Subject: [PATCH 07/18] test(e2e): tryOpen for the open that is expected to fail (#477) --- e2e/slow-agent-device.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index 6f321b23c..6e96cd07c 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -192,9 +192,10 @@ function defineSuite(target: Target): void { const agent = (name: string): Promise => makeAgent(env, 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 tryOpen = (who: Agent) => who.run(["open", "--platform", platform], { timeout: 330_000 }); const open = async (who: Agent) => { - const result = await who.run(["open", "--platform", platform], { timeout: 330_000 }); - if (result.code !== 0 && !expectingOpenFailure) { + const result = await tryOpen(who); + if (result.code !== 0) { throw new Error(`open failed for ${who.name}: ${result.stdout}\n${result.stderr}`); } return result; From d096577ae956e4d0ef31af1d5b6a0088c762d07f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 14:04:57 +0200 Subject: [PATCH 08/18] test(e2e): the unavailable-daemon open is expected to fail (#477) --- e2e/slow-agent-device.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index 6e96cd07c..d074fc9bb 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -635,7 +635,7 @@ function defineSuite(target: Target): void { expect(released.code, released.stderr).toBe(0); await waitForFree(env); - const opened = await open(a); + const opened = await tryOpen(a); expect(opened.code).not.toBe(0); expect(failureText(opened)).toContain( `agent-device is not available on this simlock: ${message}`, From 0e0b3d6c9261a0f1e9b79ee678b23a78841f8a1f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 14:26:08 +0200 Subject: [PATCH 09/18] fix(agent-device): read the allocate reply's lease and device under result.data, as agent-device sends them; log an unusable or failed upstream reply (#477) --- src/agent-device/edge.test.ts | 6 ++-- src/agent-device/front/allocate.ts | 9 +++--- src/agent-device/front/context.test.ts | 45 ++++++++++++++++++++++++++ src/agent-device/front/context.ts | 12 ++++++- src/agent-device/host/lease-end.ts | 6 ++-- src/agent-device/shared/rpc.test.ts | 33 ++++++++++++++++++- src/agent-device/shared/rpc.ts | 7 +++- src/agent-device/testing.ts | 12 ++++--- 8 files changed, 113 insertions(+), 17 deletions(-) create mode 100644 src/agent-device/front/context.test.ts diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 58f949918..29c16847e 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -854,7 +854,7 @@ describe("the agent-device front, through the whole worker daemon", () => { const iosDevice = await grantedDevice(ios); const iosParams = receivedAllocate(ios, 1); - expect(iosAnswer.result).toMatchObject({ lease: { leaseId: hex(1) }, ok: true }); + expect(iosAnswer.result).toMatchObject({ data: { lease: { leaseId: hex(1) } }, ok: true }); expect(iosParams["udid"]).toBe(iosDevice.address); expect(iosParams).not.toHaveProperty("serial"); for (const dropped of ["device", "deviceKey", "target"]) { @@ -868,7 +868,7 @@ describe("the agent-device front, through the whole worker daemon", () => { const androidDevice = await grantedDevice(android); const androidParams = receivedAllocate(android, 2); - expect(androidAnswer.result).toMatchObject({ lease: { leaseId: hex(2) }, ok: true }); + expect(androidAnswer.result).toMatchObject({ data: { lease: { leaseId: hex(2) } }, ok: true }); expect(androidParams["serial"]).toBe(androidDevice.address); expect(androidParams["serial"]).not.toBe(androidDevice.driverDeviceId); expect(androidParams).not.toHaveProperty("udid"); @@ -887,7 +887,7 @@ describe("the agent-device front, through the whole worker daemon", () => { await release(rig, 1); const answer = await envelopeOf(await second.promise); - expect(answer.result).toMatchObject({ lease: { leaseId: hex(2) }, ok: true }); + expect(answer.result).toMatchObject({ data: { lease: { leaseId: hex(2) } }, ok: true }); expect((await leases(rig)).map((lease) => lease.id)).toEqual([hex(2)]); }); diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index f7b54d4ef..b3543ea55 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -7,7 +7,7 @@ import type { TokenIdentity } from "../../http/token-store.js"; import type { Clock } from "../../ports/index.js"; import { frontReply, failure, refusal, type FrontReply } from "../shared/replies.js"; import { validDeviceKey } from "../shared/release-scope.js"; -import { leaseCallFields, leaseIdOf, type RpcRead } from "../shared/rpc.js"; +import { leaseCallFields, leaseIdOf, replyData, type RpcRead } from "../shared/rpc.js"; import { addressField, asRecord } from "../shared/selectors.js"; import { ALLOCATE_SCOPE_KEYS, @@ -301,7 +301,7 @@ async function keepOrRelease( }); return relay(reply); } - const lease = reading.result["lease"]; + const lease = replyData(reading.result)?.["lease"]; const named = typeof lease === "object" && lease !== null ? (lease as Record) : {}; const ended = await releaseAgentDevice( @@ -333,8 +333,9 @@ async function settleNoReply( } function replyFacts(result: Record) { - const device = asRecord(result["device"]); - const deviceKey = asRecord(result["lease"])?.["deviceKey"]; + const data = replyData(result); + const device = asRecord(data?.["device"]); + const deviceKey = asRecord(data?.["lease"])?.["deviceKey"]; return { ...(device === undefined ? {} : { target: stringOr(device["target"], "mobile") }), ...(typeof device?.["name"] === "string" ? { name: device["name"] } : {}), diff --git a/src/agent-device/front/context.test.ts b/src/agent-device/front/context.test.ts new file mode 100644 index 000000000..225a32e96 --- /dev/null +++ b/src/agent-device/front/context.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "vitest"; + +import type { Logger } from "../../ports/index.js"; +import type { TokenIdentity } from "../../http/token-store.js"; +import { exchange, type FrontContext } from "./context.js"; + +function rig(reply: () => Promise) { + const warnings: { message: string; fields: unknown }[] = []; + const logger = { + warn: (message: string, fields: unknown) => warnings.push({ message, fields }), + } as unknown as Logger; + const context = { link: { forward: reply }, logger } as unknown as FrontContext; + return { context, warnings }; +} + +const request = new Request("http://127.0.0.1/rpc", { method: "POST" }); +const identity = {} as TokenIdentity; + +describe("exchange", () => { + it("a reply that is not JSON-RPC is logged with its status and the start of its body", async () => { + const { context, warnings } = rig(() => + Promise.resolve(new Response(`bad gateway ${"x".repeat(900)}`, { status: 502 })), + ); + + const result = await exchange(context, request, identity, "allocate"); + + expect(result.reading.kind).toBe("unusable"); + expect(warnings).toHaveLength(1); + const fields = warnings[0]?.fields as { body: string; status: number }; + expect(fields.status).toBe(502); + expect(fields.body.startsWith("bad gateway xxx")).toBe(true); + expect(fields.body.length).toBe(500); + }); + + it("a usable success reply is not logged", async () => { + const { context, warnings } = rig(() => + Promise.resolve(Response.json({ id: 1, jsonrpc: "2.0", result: { ok: true } })), + ); + + const result = await exchange(context, request, identity); + + expect(result.reading.kind).toBe("success"); + expect(warnings).toEqual([]); + }); +}); diff --git a/src/agent-device/front/context.ts b/src/agent-device/front/context.ts index b3c575590..14ab7b788 100644 --- a/src/agent-device/front/context.ts +++ b/src/agent-device/front/context.ts @@ -20,6 +20,8 @@ export interface FrontContext { readonly logger: Logger; } +const BODY_LOG_CHARS = 500; + export interface Exchange { readonly response: Response | undefined; readonly text: string | undefined; @@ -35,7 +37,15 @@ export async function exchange( try { const response = await context.link.forward(request, identity); const text = await response.text(); - return { reading: readReply(text, call), response, text }; + const reading = readReply(text, call); + // why: a 5xx or a body that is not a JSON-RPC reply ends the call as a 502, and its reason is only in what agent-device sent. + if (reading.kind === "unusable" || response.status >= 500) { + context.logger.warn("agent-device lease call got an unusable or failed reply", { + body: text.slice(0, BODY_LOG_CHARS), + status: response.status, + }); + } + return { reading, response, text }; } catch (error) { context.logger.warn("agent-device lease call got no usable reply", { message: error instanceof Error ? error.message : String(error), diff --git a/src/agent-device/host/lease-end.ts b/src/agent-device/host/lease-end.ts index 84f1a3aec..4ccd2106b 100644 --- a/src/agent-device/host/lease-end.ts +++ b/src/agent-device/host/lease-end.ts @@ -1,6 +1,6 @@ import type { EndedLease, LeaseEndParticipant } from "../../leasing/index.js"; import { readReleaseScope, type ReleaseScope } from "../shared/release-scope.js"; -import { classifyCall, leaseIdOf, readReply, readRpcBody } from "../shared/rpc.js"; +import { classifyCall, leaseIdOf, readReply, readRpcBody, replyData } from "../shared/rpc.js"; import type { AgentDeviceUpstream } from "./upstream.js"; // why: the ids of ended leases are remembered so a late reply writes nothing; the cap keeps that memory bounded. @@ -32,7 +32,9 @@ export class ReleaseScopeRecord { const text = await response.clone().text(); const reading = readReply(text, "allocate"); const read = - reading.kind === "success" ? readReleaseScope(reading.result["lease"]) : undefined; + reading.kind === "success" + ? readReleaseScope(replyData(reading.result)?.["lease"]) + : undefined; if (read !== undefined && !this.#ended.has(leaseId)) this.#scopes.set(leaseId, read); return read; }, diff --git a/src/agent-device/shared/rpc.test.ts b/src/agent-device/shared/rpc.test.ts index ff964b359..2b55b17a1 100644 --- a/src/agent-device/shared/rpc.test.ts +++ b/src/agent-device/shared/rpc.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { commandLeaseId } from "./rpc.js"; +import { commandLeaseId, readReply } from "./rpc.js"; const first = "a".repeat(32); const second = "b".repeat(32); @@ -19,3 +19,34 @@ describe("a command's lease ID", () => { expect(commandLeaseId({})).toBeUndefined(); }); }); + +describe("readReply on the allocate reply agent-device sends", () => { + const lease = { + backend: "ios-instance", + clientId: "c902297e635eb082", + createdAt: 1791894026484, + deviceKey: "ios:mobile:45C1194B-0BE5-4BAE-AAC9-F48070759060", + expiresAt: 1791980426486, + heartbeatAt: 1791894026486, + leaseId: "278f30d59b069c0dde98555b9103b962", + leaseProvider: "proxy", + runId: "proxy-c902297e635eb082", + tenantId: "tok_04c37a6e", + }; + + it("a reply with the lease under `result.data`, as the slow lane recorded it, is a success", () => { + const text = JSON.stringify({ + id: "x", + jsonrpc: "2.0", + result: { data: { device: { platform: "ios", target: "mobile" }, lease }, ok: true }, + }); + + expect(readReply(text, "allocate").kind).toBe("success"); + }); + + it("a reply with the lease directly under `result` is unusable, since agent-device never sends that", () => { + const text = JSON.stringify({ id: "x", jsonrpc: "2.0", result: { lease, ok: true } }); + + expect(readReply(text, "allocate").kind).toBe("unusable"); + }); +}); diff --git a/src/agent-device/shared/rpc.ts b/src/agent-device/shared/rpc.ts index cae92747c..c4d27fa4d 100644 --- a/src/agent-device/shared/rpc.ts +++ b/src/agent-device/shared/rpc.ts @@ -118,6 +118,11 @@ export function commandLeaseId(params: unknown): string | undefined { return leaseIdOf(meta?.["leaseId"] ?? flags?.["leaseId"]); } +// why: agent-device answers `{ ok, data: { lease, device, provider } }`, so the lease and the device are one level down from `result`. +export function replyData(result: Record): Record | undefined { + return record(result["data"]); +} + export type ReplyReading = | { readonly kind: "success"; readonly result: Record } | { @@ -150,7 +155,7 @@ export function readReply(text: string, call?: CallClass): ReplyReading { } const result = record(body["result"]); if (result !== undefined && result["ok"] === true && body["error"] === undefined) { - if (call === "allocate" && readReleaseScope(result["lease"]) === undefined) { + if (call === "allocate" && readReleaseScope(replyData(result)?.["lease"]) === undefined) { return { kind: "unusable" }; } return { kind: "success", result }; diff --git a/src/agent-device/testing.ts b/src/agent-device/testing.ts index 19a949453..c57cceea7 100644 --- a/src/agent-device/testing.ts +++ b/src/agent-device/testing.ts @@ -418,10 +418,12 @@ export class FakeAgentDevice implements AgentDeviceUpstream { ttlMs: params["ttlMs"], }); return envelope(id, { - ...(picked === "none" || address === undefined - ? {} - : { device: { id: address, name: `simlock-${address}`, ...picked } }), - lease: { ...scope, ...edit, leaseId, tenantId: tenant, ttlMs: params["ttlMs"] }, + data: { + ...(picked === "none" || address === undefined + ? {} + : { device: { id: address, name: `simlock-${address}`, ...picked } }), + lease: { ...scope, ...edit, leaseId, tenantId: tenant, ttlMs: params["ttlMs"] }, + }, ok: true, }); } @@ -440,7 +442,7 @@ export class FakeAgentDevice implements AgentDeviceUpstream { message: reason.toLowerCase().replaceAll("_", " "), }); } - return envelope(id, { lease: params, ok: true }); + return envelope(id, { data: { lease: params }, ok: true }); } #claimed(address: string): boolean { From d0e10e571612fb882badbf673cd47a6a6fccf00d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 14:44:28 +0200 Subject: [PATCH 10/18] test(e2e): read the waiting requests from list --requests text, not JSON; one progress line per test; last observed state on a free-wait timeout (#477) --- e2e/slow-agent-device.test.ts | 47 ++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index d074fc9bb..4647661bb 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -1,8 +1,18 @@ 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"; -import { afterAll, afterEach, beforeAll, describe, expect, it, onTestFinished } from "vitest"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + onTestFinished, +} from "vitest"; import { assertPinnedAgentDevice, @@ -86,6 +96,11 @@ interface RequestRow { readonly requesterId: string; } +// 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); @@ -94,9 +109,20 @@ async function listRows(env: SharedTestEnv, flag: string): Promise { const listDevices = (env: SharedTestEnv) => listRows(env, "--devices"); const listLeases = (env: SharedTestEnv) => listRows(env, "--leases"); -const listRequests = (env: SharedTestEnv) => listRows(env, "--requests"); + +// 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([ @@ -104,6 +130,7 @@ async function waitForFree(env: SharedTestEnv): Promise { 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") && @@ -111,7 +138,11 @@ async function waitForFree(env: SharedTestEnv): Promise { requests.length === 0 ); }, - { timeout: 240_000, interval: 1_000, label: "every device ready, no lease, no request" }, + { + timeout: 240_000, + interval: 1_000, + label: () => `every device ready, no lease, no request; last observed: ${observed}`, + }, ); } @@ -261,6 +292,16 @@ function defineSuite(target: Target): void { sharedEnvs.delete(env); }, 120_000); + beforeEach((context) => { + progress(`START ${platform}: ${context.task.name.slice(0, 100)}`); + }); + + afterEach((context) => { + progress( + `END ${platform} (${context.task.result?.state ?? "unknown"}): ${context.task.name.slice(0, 100)}`, + ); + }); + afterEach(async () => { await cleanupAgents(); const released = await env.cli(["release", "--all", "--yes"], { timeout: 60_000 }); From 8ebbf57d61719e01d3cbbeeca5cf3dcf79e53fff Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 15:10:47 +0200 Subject: [PATCH 11/18] test(e2e): doctor has no --json flag (plain output is JSON); open the fixture app before snapshots on iOS (#477) --- e2e/slow-agent-device.test.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index 4647661bb..4b63d4a02 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -332,10 +332,10 @@ function defineSuite(target: Target): void { ); it( - "with this working agent-device, simlock doctor --json reports no agent-device-unavailable finding and no finding whose message names agent-device", + "with this working agent-device, simlock doctor reports no agent-device-unavailable finding and no finding whose message names agent-device", { timeout: 600_000 }, async () => { - const doctor = await env.cli(["doctor", "--json"], { timeout: 60_000 }); + const doctor = await env.cli(["doctor"], { timeout: 60_000 }); const findings = (doctor.json as { findings: { kind: string; message?: string }[] }).findings; expect(findings.map((finding) => finding.kind)).not.toContain("agent-device-unavailable"); expect(findings.filter((finding) => /agent-device/i.test(finding.message ?? ""))).toEqual([]); @@ -363,6 +363,8 @@ function defineSuite(target: Target): void { const a = await agent("a"); ok(await open(a)); ok(await a.run(["install", "Appduct", target.app])); + // why: an iOS snapshot needs an app session on the device (ios_app_session_required). + ok(await a.run(["open", target.bundleId])); ok(await a.run(["snapshot"])); const [lease] = await listLeases(env); const driverId = (await listDevices(env)).find((device) => device.id === lease?.deviceId) @@ -657,7 +659,7 @@ function defineSuite(target: Target): void { let finding: { kind: string; message: string } | undefined; await waitFor( async () => { - const doctor = await env.cli(["doctor", "--json"], { timeout: 60_000 }); + const doctor = await env.cli(["doctor"], { timeout: 60_000 }); finding = ( doctor.json as { findings: { kind: string; message: string }[] } ).findings.find((row) => row.kind === "agent-device-unavailable"); @@ -726,6 +728,11 @@ function defineSuite(target: Target): void { const b = await agent("b"); ok(await open(a)); ok(await open(b)); + // why: an iOS snapshot needs an app session on the device (ios_app_session_required). + for (const who of [a, b]) { + ok(await who.run(["install", "Appduct", target.app])); + ok(await who.run(["open", target.bundleId])); + } const leases = await listLeases(env); expect(new Set(leases.map((lease) => lease.deviceId)).size).toBe(2); const devices = await listDevices(env); From 09133ed4f1970b68ffbb4d7143b51b891c96d19c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 15:46:20 +0200 Subject: [PATCH 12/18] fix(agent-device): /health answers 200 while agent-device is unavailable, so the CLI runs its first command and prints the reason (#477) --- docs/HTTP-API.md | 5 ++++- src/agent-device/edge.test.ts | 1 + src/agent-device/front/front.ts | 7 ++++++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 41743fee9..4d32d87cc 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1514,7 +1514,10 @@ the status. - `agent-device is not available on this simlock: `: agent-device is turned on but missing, too old, starting or crashed. The rest of Simlock - works as before. + works as before. `GET /health` answers it with status 200, because the + agent-device CLI treats a `/health` status of 500 or more as an unreachable + daemon and would print only `Remote daemon is unavailable`; the first + command then prints the reason. - `timed out waiting for a device; nothing was leased`. - `refused by simlock: `: Simlock refused the lease request, for example a model it does not know, or a `ttlMs` above `lease.maxTtlMs`. diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 29c16847e..c79dd99b0 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -563,6 +563,7 @@ describe("the agent-device front, through the whole worker daemon", () => { const rpcAnswer = await allocate(rig, 1); const upload = await send(rig, "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/upload/preflight", { body: "{}" }); + expect(health.status).toBe(200); expect(await health.text()).toContain(`${notAvailable}${reason}`); expect((await envelopeOf(rpcAnswer)).error?.message).toBe(`${notAvailable}${reason}`); expect(await upload.text()).toContain(`${notAvailable}${reason}`); diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index 431ad0e30..c5e4b0df9 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -195,8 +195,13 @@ export function createFront(context: FrontContext): HttpMount { } if (isRpc) return handleRpc(context, request, identity); const status = await context.link.status(); - if (status.state === "unavailable") return frontReply(notAvailable(status.reason), undefined); const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); + if (status.state === "unavailable") { + // why: the agent-device CLI counts a /health answer of 500 or more as an unreachable daemon and prints only "Remote daemon is unavailable"; a lower status lets its first RPC run and print the reason. + const reply = notAvailable(status.reason); + const probe = request.method === "GET" && path === "/health"; + return frontReply(probe ? { ...reply, status: 200 } : reply, undefined); + } if (!isKnownRoute(request.method, path)) { return frontReply( refusal(`refused: unknown route ${request.method} ${path}`, 404), From 78b9c127f62870d20ba7dcb2191a472ac6c217c9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 15:47:18 +0200 Subject: [PATCH 13/18] fix(agent-device): log a warning with status and body for a 5xx on a passed-through call (#477) --- src/agent-device/edge.test.ts | 20 +++++++++++++++++++- src/agent-device/front/front.ts | 32 +++++++++++++++++++++++++++++++- src/agent-device/testing.ts | 8 ++++++++ 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index c79dd99b0..0f63db853 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -79,6 +79,7 @@ interface Rig { readonly driver: FakeDriver; readonly fake: FakeAgentDevice; readonly filesystem: MemoryFilesystem; + readonly logs: MemoryLogSink; readonly origin: string; readonly statePath: string; readonly started: Promise; @@ -157,6 +158,7 @@ async function setUp(options: SetUpOptions = {}): Promise { const fake = options.upstream ?? new FakeAgentDevice(); const drivers = options.drivers?.(clock) ?? [iosDriver(clock)]; const statePath = join(directory, "state.json"); + const logs = new MemoryLogSink(); const launch = () => startDaemon({ agentDeviceUpstream: fake, @@ -178,7 +180,7 @@ async function setUp(options: SetUpOptions = {}): Promise { dataDirectory: directory, drivers, filesystem, - logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), + logger: new JsonLinesLogger({ clock, level: "debug", sink: logs }), statePath, version: "1.2.3", } as StartDaemonOptions).then((daemon) => { @@ -195,6 +197,7 @@ async function setUp(options: SetUpOptions = {}): Promise { driver: drivers[0] as FakeDriver, fake, filesystem, + logs, origin, restart: () => Promise.reject(new Error("restart needs a started daemon")), started, @@ -207,6 +210,7 @@ async function setUp(options: SetUpOptions = {}): Promise { driver: drivers[0] as FakeDriver, fake, filesystem, + logs, origin, restart: async (between) => { await daemon.stop("test"); @@ -1818,6 +1822,20 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(await deadlineOf(rig, 1)).toBe(final); }); + it("a command agent-device answers with a 5xx reaches the CLI unchanged, and simlock logs a warning with that status and the start of the body", async () => { + const rig = await setUp(); + await granted(rig, 1); + rig.fake.failNextCommandWithStatus(500, "snapshot runner crashed"); + + const response = await command(rig, "snapshot", 1); + + expect(response.status).toBe(500); + expect(await response.text()).toBe("snapshot runner crashed"); + await expect + .poll(() => rig.logs.records.find((record) => record.message.includes("5xx"))?.fields) + .toEqual({ body: "snapshot runner crashed", status: 500 }); + }); + it("a command that fails, and one whose CLI hangs up, stop the renewals the same way", async () => { const rig = await setUp(); await granted(rig, 1, { ttlMs: 30_000 }); diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index c5e4b0df9..160dcb39c 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -53,6 +53,8 @@ function untilHangUp(signal: AbortSignal, work: Promise): return Promise.race([work.then((response) => response ?? gone), gone]); } +const FAILED_BODY_LOG_CHARS = 500; + async function handleRpc( context: FrontContext, request: Request, @@ -172,6 +174,32 @@ async function forwardCommand( return isDevices ? filterDevices(context, identity, response, read) : response; } +// why: a 5xx from agent-device reaches the CLI as it is, so the reason is only in the body; a copy is read in the background and cut short, so the stream the CLI waits on is not held. +function logFailedReply(context: FrontContext, response: Response): void { + const status = response.status; + void readStart(response.clone(), FAILED_BODY_LOG_CHARS) + .catch(() => "") + .then((body) => { + context.logger.warn("agent-device answered a passed-through call with a 5xx", { + body, + status, + }); + }); +} + +async function readStart(response: Response, chars: number): Promise { + if (response.body === null) return ""; + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + let text = ""; + while (text.length < chars) { + const { done, value } = await reader.read(); + if (done) break; + text += value; + } + await reader.cancel().catch(() => undefined); + return text.slice(0, chars); +} + async function passThrough( context: FrontContext, request: Request, @@ -179,7 +207,9 @@ async function passThrough( rpc: { readonly id: unknown } | undefined, ): Promise { try { - return await context.link.forward(request, identity); + const response = await context.link.forward(request, identity); + if (response.status >= 500) logFailedReply(context, response); + return response; } catch (error) { return frontReply(notAvailable(error instanceof Error ? error.message : String(error)), rpc); } diff --git a/src/agent-device/testing.ts b/src/agent-device/testing.ts index c57cceea7..19dee13ca 100644 --- a/src/agent-device/testing.ts +++ b/src/agent-device/testing.ts @@ -160,6 +160,7 @@ export class FakeAgentDevice implements AgentDeviceUpstream { #failRelease: FakeFailure | undefined; #failHeartbeat: FakeFailure | undefined; #failCommand: FakeFailure | undefined; + #failCommandStatus: { readonly status: number; readonly body: string } | undefined; readonly #goneReasons = new Map(); #allocateBody: string | undefined; #replyDeviceKey: string | undefined; @@ -221,6 +222,10 @@ export class FakeAgentDevice implements AgentDeviceUpstream { this.#failCommand = failure; } + failNextCommandWithStatus(status: number, body: string): void { + this.#failCommandStatus = { body, status }; + } + // why: agent-device answers a heartbeat for a lease it no longer holds with UNAUTHORIZED and one of three reasons; this makes it forget `leaseId` for the given one. loseLease(leaseId: string, reason: FakeLeaseGoneReason): void { this.leases.delete(leaseId); @@ -551,6 +556,9 @@ export class FakeAgentDevice implements AgentDeviceUpstream { const failure = this.#failCommand; this.#failCommand = undefined; if (failure !== undefined) return errorEnvelope(id, failure); + const status = this.#failCommandStatus; + this.#failCommandStatus = undefined; + if (status !== undefined) return new Response(status.body, { status: status.status }); const inventory = this.#devicesAnswer; if (command === "devices" && inventory !== undefined) { if ("body" in inventory) return new Response(inventory.body, { status: 200 }); From 86e8001772cc2ed3666dd87b28ac44bb15aa67cb Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 15:48:00 +0200 Subject: [PATCH 14/18] test(e2e): the first snapshot on a fresh simulator gets 180 s (#477) --- e2e/slow-agent-device.test.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index 4b63d4a02..803e6089e 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -96,6 +96,9 @@ 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`); @@ -317,7 +320,7 @@ function defineSuite(target: Target): void { ok(await open(a)); ok(await a.run(["install", "Appduct", target.app])); ok(await a.run(["open", target.bundleId])); - const snapshot = await a.run(["snapshot"]); + const snapshot = await a.run(["snapshot"], FIRST_SNAPSHOT); ok(snapshot); expect(snapshot.stdout).toContain("tab-status"); ok(await a.run(["click", 'id="tab-status"'])); @@ -365,7 +368,7 @@ function defineSuite(target: Target): void { ok(await a.run(["install", "Appduct", target.app])); // why: an iOS snapshot needs an app session on the device (ios_app_session_required). ok(await a.run(["open", target.bundleId])); - ok(await a.run(["snapshot"])); + ok(await a.run(["snapshot"], FIRST_SNAPSHOT)); const [lease] = await listLeases(env); const driverId = (await listDevices(env)).find((device) => device.id === lease?.deviceId) ?.driverDeviceId as string; @@ -741,10 +744,10 @@ function defineSuite(target: Target): void { return devices.find((device) => device.id === lease?.deviceId)?.driverDeviceId as string; }; - ok(await b.run(["snapshot", target.deviceFlag, driverIdOf(b)])); + ok(await b.run(["snapshot", target.deviceFlag, driverIdOf(b)], FIRST_SNAPSHOT)); refused(await b.run(["snapshot", target.deviceFlag, driverIdOf(a)])); ok(await b.run(["close"])); - ok(await a.run(["snapshot"])); + ok(await a.run(["snapshot"], FIRST_SNAPSHOT)); }, ); From 46b245583535f26881b05be682ec3008f69de9b5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 15:52:51 +0200 Subject: [PATCH 15/18] fix(agent-device): a sharded test names the agent's devices by name, as an open agent-device session requires; e2e: find a lease by its owner (#477) --- docs/HTTP-API.md | 3 ++- e2e/slow-agent-device.test.ts | 9 +++++-- src/agent-device/edge.test.ts | 33 +++++++++++++++++++------ src/agent-device/front/request-rules.ts | 7 +++++- 4 files changed, 41 insertions(+), 11 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 4d32d87cc..0323e174e 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1535,7 +1535,8 @@ the status. `reinstall` of a path on the worker. - `refused: no device leased; run open first`: a sharded `test` with no `--device` from an agent holding no matching device. With a device leased, - Simlock adds the agent's leased devices as `--device`. + Simlock adds the agent's leased devices as `--device`, each by the name + agent-device gave it (by its ID when it gave none or the name has a comma). - `refused: name the device with --udid ; run devices to see yours`: `capabilities` or `doctor` that names no device from an agent not holding exactly one. diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index 803e6089e..8f05f46a8 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -90,6 +90,7 @@ interface DeviceRow { interface LeaseRow { readonly id: string; readonly deviceId: string; + readonly ownerId: string; readonly requesterId: string; } interface RequestRow { @@ -740,8 +741,12 @@ function defineSuite(target: Target): void { expect(new Set(leases.map((lease) => lease.deviceId)).size).toBe(2); const devices = await listDevices(env); const driverIdOf = (who: Agent): string => { - const lease = leases.find((row) => row.requesterId === who.tokenId); - return devices.find((device) => device.id === lease?.deviceId)?.driverDeviceId as string; + // why: a lease's requesterId is the lease's own ID when the agent chose it; the token is its ownerId. + const lease = leases.find((row) => row.ownerId === who.tokenId); + const driverId = devices.find((device) => device.id === lease?.deviceId)?.driverDeviceId; + if (driverId === undefined) + throw new Error(`no leased device found for agent ${who.name}`); + return driverId; }; ok(await b.run(["snapshot", target.deviceFlag, driverIdOf(b)], FIRST_SNAPSHOT)); diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 0f63db853..546921980 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -2739,6 +2739,11 @@ function runCommand( }); } +// why: the fake agent-device names the device it leases `simlock-`, as the real one does. +function nameOf(rig: Rig, n: number): string { + return `simlock-${idOf(rig, n)}`; +} + function idOf(rig: Rig, n: number): string { const params = receivedAllocate(rig, n); return String(params["udid"] ?? params["serial"]); @@ -3162,7 +3167,7 @@ describe("the agent-device front's request rules", () => { const steps = flagsOf(params)["batchSteps"] as { flags: Record }[]; expect(steps[0]?.flags["udid"]).toBe(idOf(rig, 1)); expect(steps[0]?.flags).not.toHaveProperty("device"); - expect(steps[1]?.flags["device"]).toBe(idOf(rig, 1)); + expect(steps[1]?.flags["device"]).toBe(nameOf(rig, 1)); await refused( rig, () => batch(rig, 1, [{ command: "snapshot", flags: { leaseId: hex(2) } }]), @@ -3260,9 +3265,9 @@ describe("the agent-device front's request rules", () => { const one = await forwarded(rig, () => shard(rig, 1)); const two = await forwarded(rig, () => shard(rig, 2, {}, secrets.two)); - expect(flagsOf(one)["device"]).toBe(idOf(rig, 1)); + expect(flagsOf(one)["device"]).toBe(nameOf(rig, 1)); expect(String(flagsOf(two)["device"]).split(",").sort()).toEqual( - [idOf(rig, 2), idOf(rig, 3)].sort(), + [nameOf(rig, 2), nameOf(rig, 3)].sort(), ); }); @@ -3281,9 +3286,9 @@ describe("the agent-device front's request rules", () => { shard(rig, 2, { platform: "android", shardAll: 1 }), ); - expect(flagsOf(ios)["device"]).toBe(idOf(rig, 1)); - expect(flagsOf(tv)["device"]).toBe(idOf(rig, 3)); - expect(flagsOf(android)["device"]).toBe(idOf(rig, 2)); + expect(flagsOf(ios)["device"]).toBe(nameOf(rig, 1)); + expect(flagsOf(tv)["device"]).toBe(nameOf(rig, 3)); + expect(flagsOf(android)["device"]).toBe(nameOf(rig, 2)); const iosOnly = await setUp({ drivers: bothDrivers }); await granted(iosOnly, 1); await forwarded(iosOnly, () => shard(iosOnly, 1, { platform: "ios", shardAll: 1 })); @@ -3294,6 +3299,20 @@ describe("the agent-device front's request rules", () => { ); }); + it("`test --shard-all 2` names a device by the name agent-device gave it, and by its id when that name holds a comma or the reply named none", async () => { + const rig = await setUp(); + rig.fake.nameDeviceInNextReply({ name: "Lab, left" }); + await granted(rig, 1); + rig.fake.nameDeviceInNextReply("none"); + await granted(rig, 2, {}, { token: secrets.two }); + + const comma = await forwarded(rig, () => shard(rig, 1)); + const unnamed = await forwarded(rig, () => shard(rig, 2, {}, secrets.two)); + + expect(flagsOf(comma)["device"]).toBe(idOf(rig, 1)); + expect(flagsOf(unnamed)["device"]).toBe(idOf(rig, 2)); + }); + it('`test --shard-split 2` with `device: " , "` is filled as if no list were sent; from a token that holds no device it is refused with `refused: no device leased; run open first`', async () => { const rig = await setUp(); await granted(rig, 1); @@ -3302,7 +3321,7 @@ describe("the agent-device front's request rules", () => { const params = await forwarded(rig, () => split(secrets.one, 1)); - expect(flagsOf(params)["device"]).toBe(idOf(rig, 1)); + expect(flagsOf(params)["device"]).toBe(nameOf(rig, 1)); await refused(rig, () => split(secrets.two, undefined), noDeviceLeased); }); }); diff --git a/src/agent-device/front/request-rules.ts b/src/agent-device/front/request-rules.ts index 023c1f515..ce303aac6 100644 --- a/src/agent-device/front/request-rules.ts +++ b/src/agent-device/front/request-rules.ts @@ -230,7 +230,12 @@ async function ruleSharding(check: Check, unit: Unit): Promise { ); if (matching.length === 0) throw refuse(NO_DEVICE_LEASED); for (const place of found) delete place["device"]; - flagsOf(unit)["device"] = matching.map((device) => device.address).join(","); + // why: agent-device holds `--device` against the open session by device name, and an id there is a conflict; its shard lookup takes a name too. A name with a comma would split, so that device goes by its id. + flagsOf(unit)["device"] = matching + .map((device) => + device.name === undefined || device.name.includes(",") ? device.address : device.name, + ) + .join(","); check.changed = true; } From 0efec78eaa32f8164603b80ef08b679f463d1469 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 15:56:22 +0200 Subject: [PATCH 16/18] test(e2e): the shard suite declares its platform and runs a step that needs no app session (#477) --- e2e/slow-agent-device.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index 8f05f46a8..3689330c1 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -766,7 +766,8 @@ function defineSuite(target: Target): void { ok(await open(b)); const suite = await mkdtemp(join(tmpdir(), "simlock-ad-suite-")); onTestFinished(() => rm(suite, { force: true, recursive: true })); - await writeFile(join(suite, "smoke.ad"), "snapshot\n"); + // why: a script needs a `context platform=` line (agent-device refuses one without), and a step that needs no app session: the shard runs beside agent A's open session, so `open` fails with the device in use and a `snapshot` with no app session. + await writeFile(join(suite, "smoke.ad"), `context platform=${platform}\nwait 200\n`); ok(await a.run(["test", suite, "--shard-all", "1"])); const two = await a.run(["test", suite, "--shard-all", "2"]); From 9795521855e50890ce4b95930a7af82d7cfb4c56 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 16:43:09 +0200 Subject: [PATCH 17/18] test(e2e): Android tests name a device by its adb serial; the start-up check names a missing Android helper; the build step is documented (#477) --- .../smoke.ad/attempt-1/replay-timing.ndjson | 8 +++++++ .../shard-1/smoke.ad/attempt-1/replay.ad | 2 ++ .../shard-1/smoke.ad/attempt-1/result.txt | 6 +++++ .../smoke.ad/attempt-1/replay-timing.ndjson | 8 +++++++ .../shard-1/smoke.ad/attempt-1/replay.ad | 2 ++ .../shard-1/smoke.ad/attempt-1/result.txt | 6 +++++ e2e/helpers/agent-device.ts | 22 +++++++++++++++-- e2e/slow-agent-device.test.ts | 24 ++++++++++--------- 8 files changed, 65 insertions(+), 13 deletions(-) create mode 100644 .agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay-timing.ndjson create mode 100644 .agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad create mode 100644 .agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/result.txt create mode 100644 .agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay-timing.ndjson create mode 100644 .agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad create mode 100644 .agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/result.txt diff --git a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay-timing.ndjson b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay-timing.ndjson new file mode 100644 index 000000000..7cdd9f6a8 --- /dev/null +++ b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay-timing.ndjson @@ -0,0 +1,8 @@ +{"type":"replay_test_attempt_start","ts":"2026-10-13T14:40:40.096Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-b0xUkD/smoke.ad","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1","requestId":"a17e55a5c7b7c6d3:shard:1:test:1:smoke.ad:attempt:1","platform":"android"} +{"type":"replay_action_start","ts":"2026-10-13T14:40:40.098Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-b0xUkD/smoke.ad","line":2,"step":1,"command":"wait","positionals":[""]} +{"type":"replay_action_stop","ts":"2026-10-13T14:40:40.512Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-b0xUkD/smoke.ad","line":2,"step":1,"command":"wait","ok":true,"durationMs":414} +{"type":"replay_test_attempt_stop","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1","ok":true,"timedOut":false,"durationMs":418} +{"type":"replay_test_finalize_start","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1"} +{"type":"replay_test_finalize_stop","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1","ok":true,"durationMs":0} +{"type":"replay_test_cleanup_start","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1"} +{"type":"replay_test_cleanup_stop","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1","ok":true,"durationMs":0} diff --git a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad new file mode 100644 index 000000000..0dc93af3b --- /dev/null +++ b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad @@ -0,0 +1,2 @@ +context platform=android +wait 200 diff --git a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/result.txt b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/result.txt new file mode 100644 index 000000000..56382e33d --- /dev/null +++ b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/result.txt @@ -0,0 +1,6 @@ +file: /var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-b0xUkD/smoke.ad +session: tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1 +attempt: 1/1 +status: passed +replayed: 1 +healed: 0 diff --git a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay-timing.ndjson b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay-timing.ndjson new file mode 100644 index 000000000..7cc4830e7 --- /dev/null +++ b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay-timing.ndjson @@ -0,0 +1,8 @@ +{"type":"replay_test_attempt_start","ts":"2026-10-13T14:33:57.966Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-M4EFDV/smoke.ad","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1","requestId":"a38bc07eeb51ca18:shard:1:test:1:smoke.ad:attempt:1","platform":"ios"} +{"type":"replay_action_start","ts":"2026-10-13T14:33:57.971Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-M4EFDV/smoke.ad","line":2,"step":1,"command":"wait","positionals":[""]} +{"type":"replay_action_stop","ts":"2026-10-13T14:33:59.280Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-M4EFDV/smoke.ad","line":2,"step":1,"command":"wait","ok":true,"durationMs":1309} +{"type":"replay_test_attempt_stop","ts":"2026-10-13T14:33:59.285Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1","ok":true,"timedOut":false,"durationMs":1319} +{"type":"replay_test_finalize_start","ts":"2026-10-13T14:33:59.285Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1"} +{"type":"replay_test_finalize_stop","ts":"2026-10-13T14:33:59.286Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1","ok":true,"durationMs":1} +{"type":"replay_test_cleanup_start","ts":"2026-10-13T14:33:59.286Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1"} +{"type":"replay_test_cleanup_stop","ts":"2026-10-13T14:33:59.287Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1","ok":true,"durationMs":1} diff --git a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad new file mode 100644 index 000000000..165469e3e --- /dev/null +++ b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad @@ -0,0 +1,2 @@ +context platform=ios +wait 200 diff --git a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/result.txt b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/result.txt new file mode 100644 index 000000000..04c1ff739 --- /dev/null +++ b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/result.txt @@ -0,0 +1,6 @@ +file: /var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-M4EFDV/smoke.ad +session: tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1 +attempt: 1/1 +status: passed +replayed: 1 +healed: 0 diff --git a/e2e/helpers/agent-device.ts b/e2e/helpers/agent-device.ts index 04dc32dc8..fbadf3965 100644 --- a/e2e/helpers/agent-device.ts +++ b/e2e/helpers/agent-device.ts @@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process"; import { existsSync } from "node:fs"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { isAbsolute, join } from "node:path"; +import { dirname, isAbsolute, join } from "node:path"; import { afterEach } from "vitest"; @@ -48,7 +48,9 @@ function agentDeviceEntry(): string { } // why: the slow lane must run the integration build the repo pins, never an agent-device installed on the machine; the pinned version is in the vendored tarball's name. -export async function assertPinnedAgentDevice(): Promise { +export async function assertPinnedAgentDevice( + platform: "ios" | "android" = "ios", +): Promise { const entry = agentDeviceEntry(); if (!isAbsolute(entry) || !existsSync(entry)) { throw new Error( @@ -71,6 +73,22 @@ export async function assertPinnedAgentDevice(): Promise { `SIMLOCK_E2E_AGENT_DEVICE ${entry} is version ${actual}, the pinned build is ${pinned}`, ); } + if (platform === "android") { + // why: an Android snapshot needs the helper APK `pnpm build:android` packages into the checkout; without it every snapshot fails mid-test. + const manifest = join( + dirname(entry), + "..", + "android", + "snapshot-helper", + "dist", + `agent-device-android-snapshot-helper-${actual}.manifest.json`, + ); + if (!existsSync(manifest)) { + throw new Error( + `the Android snapshot helper is not built (${manifest} is missing); run \`pnpm build:android\` with ANDROID_HOME set in the agent-device checkout`, + ); + } + } return entry; } diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index 3689330c1..ee4317a6a 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -85,6 +85,8 @@ const ANDROID: Target = { 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 { @@ -275,7 +277,7 @@ function defineSuite(target: Target): void { } beforeAll(async () => { - const pinned = await assertPinnedAgentDevice(); + const pinned = await assertPinnedAgentDevice(platform); env = await withSharedDaemon({ driver: "real", configOverrides: { @@ -371,8 +373,8 @@ function defineSuite(target: Target): void { ok(await a.run(["open", target.bundleId])); ok(await a.run(["snapshot"], FIRST_SNAPSHOT)); const [lease] = await listLeases(env); - const driverId = (await listDevices(env)).find((device) => device.id === lease?.deviceId) - ?.driverDeviceId as string; + const address = (await listDevices(env)).find((device) => device.id === lease?.deviceId) + ?.address as string; const dir = await mkdtemp(join(tmpdir(), "simlock-ad-set-")); onTestFinished(() => rm(dir, { force: true, recursive: true })); @@ -383,7 +385,7 @@ function defineSuite(target: Target): void { expect(denied.error?.code).toBe("UNAUTHORIZED"); expect(denied.error?.details?.reason).toBe("DAEMON_POLICY_DENIED"); } - for (const flags of target.forbiddenFlags(driverId, dir)) { + for (const flags of target.forbiddenFlags(address, dir)) { refused(await a.run(["snapshot", ...flags])); } @@ -719,7 +721,7 @@ function defineSuite(target: Target): void { const after = await a.run(["devices"]); ok(after); expect(listField(after, "devices").map((device) => (device as { id: string }).id)).toEqual([ - bound?.driverDeviceId, + bound?.address, ]); }, ); @@ -740,17 +742,17 @@ function defineSuite(target: Target): void { const leases = await listLeases(env); expect(new Set(leases.map((lease) => lease.deviceId)).size).toBe(2); const devices = await listDevices(env); - const driverIdOf = (who: Agent): string => { + const addressOf = (who: Agent): string => { // why: a lease's requesterId is the lease's own ID when the agent chose it; the token is its ownerId. const lease = leases.find((row) => row.ownerId === who.tokenId); - const driverId = devices.find((device) => device.id === lease?.deviceId)?.driverDeviceId; - if (driverId === undefined) + const address = devices.find((device) => device.id === lease?.deviceId)?.address; + if (address === undefined) throw new Error(`no leased device found for agent ${who.name}`); - return driverId; + return address; }; - ok(await b.run(["snapshot", target.deviceFlag, driverIdOf(b)], FIRST_SNAPSHOT)); - refused(await b.run(["snapshot", target.deviceFlag, driverIdOf(a)])); + ok(await b.run(["snapshot", target.deviceFlag, addressOf(b)], FIRST_SNAPSHOT)); + refused(await b.run(["snapshot", target.deviceFlag, addressOf(a)])); ok(await b.run(["close"])); ok(await a.run(["snapshot"], FIRST_SNAPSHOT)); }, From 68dfcb9aa1dbcba2df2a1ea99a54036b746031a1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 17:25:26 +0200 Subject: [PATCH 18/18] fix(agent-device): drop committed run artifacts, tighten tests, correct comment (#477) --- .../shard-1/smoke.ad/attempt-1/replay-timing.ndjson | 8 -------- .../a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad | 2 -- .../shard-1/smoke.ad/attempt-1/result.txt | 6 ------ .../shard-1/smoke.ad/attempt-1/replay-timing.ndjson | 8 -------- .../a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad | 2 -- .../shard-1/smoke.ad/attempt-1/result.txt | 6 ------ .gitignore | 1 + src/agent-device/edge.test.ts | 2 ++ src/agent-device/front/context.test.ts | 4 ++-- src/agent-device/front/context.ts | 2 +- 10 files changed, 6 insertions(+), 35 deletions(-) delete mode 100644 .agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay-timing.ndjson delete mode 100644 .agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad delete mode 100644 .agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/result.txt delete mode 100644 .agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay-timing.ndjson delete mode 100644 .agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad delete mode 100644 .agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/result.txt diff --git a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay-timing.ndjson b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay-timing.ndjson deleted file mode 100644 index 7cdd9f6a8..000000000 --- a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay-timing.ndjson +++ /dev/null @@ -1,8 +0,0 @@ -{"type":"replay_test_attempt_start","ts":"2026-10-13T14:40:40.096Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-b0xUkD/smoke.ad","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1","requestId":"a17e55a5c7b7c6d3:shard:1:test:1:smoke.ad:attempt:1","platform":"android"} -{"type":"replay_action_start","ts":"2026-10-13T14:40:40.098Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-b0xUkD/smoke.ad","line":2,"step":1,"command":"wait","positionals":[""]} -{"type":"replay_action_stop","ts":"2026-10-13T14:40:40.512Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-b0xUkD/smoke.ad","line":2,"step":1,"command":"wait","ok":true,"durationMs":414} -{"type":"replay_test_attempt_stop","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1","ok":true,"timedOut":false,"durationMs":418} -{"type":"replay_test_finalize_start","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1"} -{"type":"replay_test_finalize_stop","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1","ok":true,"durationMs":0} -{"type":"replay_test_cleanup_start","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1"} -{"type":"replay_test_cleanup_stop","ts":"2026-10-13T14:40:40.514Z","session":"tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1","ok":true,"durationMs":0} diff --git a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad deleted file mode 100644 index 0dc93af3b..000000000 --- a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/replay.ad +++ /dev/null @@ -1,2 +0,0 @@ -context platform=android -wait 200 diff --git a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/result.txt b/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/result.txt deleted file mode 100644 index 56382e33d..000000000 --- a/.agent-device/test-artifacts/a17e55a5c7b7c6d3/shard-1/smoke.ad/attempt-1/result.txt +++ /dev/null @@ -1,6 +0,0 @@ -file: /var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-b0xUkD/smoke.ad -session: tok_ffa299b4-7df9-4a82-8a8f-6d46d46e8c27:adc-edd4834201d95285f4312533bc7238ac:shard-1:test:a17e55a5c7b7c6d3:1-smoke:attempt-1 -attempt: 1/1 -status: passed -replayed: 1 -healed: 0 diff --git a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay-timing.ndjson b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay-timing.ndjson deleted file mode 100644 index 7cc4830e7..000000000 --- a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay-timing.ndjson +++ /dev/null @@ -1,8 +0,0 @@ -{"type":"replay_test_attempt_start","ts":"2026-10-13T14:33:57.966Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-M4EFDV/smoke.ad","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1","requestId":"a38bc07eeb51ca18:shard:1:test:1:smoke.ad:attempt:1","platform":"ios"} -{"type":"replay_action_start","ts":"2026-10-13T14:33:57.971Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-M4EFDV/smoke.ad","line":2,"step":1,"command":"wait","positionals":[""]} -{"type":"replay_action_stop","ts":"2026-10-13T14:33:59.280Z","replayPath":"/var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-M4EFDV/smoke.ad","line":2,"step":1,"command":"wait","ok":true,"durationMs":1309} -{"type":"replay_test_attempt_stop","ts":"2026-10-13T14:33:59.285Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1","ok":true,"timedOut":false,"durationMs":1319} -{"type":"replay_test_finalize_start","ts":"2026-10-13T14:33:59.285Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1"} -{"type":"replay_test_finalize_stop","ts":"2026-10-13T14:33:59.286Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1","ok":true,"durationMs":1} -{"type":"replay_test_cleanup_start","ts":"2026-10-13T14:33:59.286Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1"} -{"type":"replay_test_cleanup_stop","ts":"2026-10-13T14:33:59.287Z","session":"tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1","ok":true,"durationMs":1} diff --git a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad deleted file mode 100644 index 165469e3e..000000000 --- a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/replay.ad +++ /dev/null @@ -1,2 +0,0 @@ -context platform=ios -wait 200 diff --git a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/result.txt b/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/result.txt deleted file mode 100644 index 04c1ff739..000000000 --- a/.agent-device/test-artifacts/a38bc07eeb51ca18/shard-1/smoke.ad/attempt-1/result.txt +++ /dev/null @@ -1,6 +0,0 @@ -file: /var/folders/tb/j39z273s5kn7lb9tz1dhk8l00000gn/T/simlock-ad-suite-M4EFDV/smoke.ad -session: tok_940277d2-b72a-4041-9669-465921028f23:adc-6aa503d4e031241a8e83d4fadd7c0c5d:shard-1:test:a38bc07eeb51ca18:1-smoke:attempt-1 -attempt: 1/1 -status: passed -replayed: 1 -healed: 0 diff --git a/.gitignore b/.gitignore index d5fe171b7..9b4525192 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ dist/ .stryker-tmp/ test-results/ playwright-report/ +.agent-device diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 546921980..447e64cc3 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -568,6 +568,8 @@ describe("the agent-device front, through the whole worker daemon", () => { const upload = await send(rig, "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/upload/preflight", { body: "{}" }); expect(health.status).toBe(200); + expect(rpcAnswer.status).toBe(503); + expect(upload.status).toBe(503); expect(await health.text()).toContain(`${notAvailable}${reason}`); expect((await envelopeOf(rpcAnswer)).error?.message).toBe(`${notAvailable}${reason}`); expect(await upload.text()).toContain(`${notAvailable}${reason}`); diff --git a/src/agent-device/front/context.test.ts b/src/agent-device/front/context.test.ts index 225a32e96..8b128c179 100644 --- a/src/agent-device/front/context.test.ts +++ b/src/agent-device/front/context.test.ts @@ -19,7 +19,7 @@ const identity = {} as TokenIdentity; describe("exchange", () => { it("a reply that is not JSON-RPC is logged with its status and the start of its body", async () => { const { context, warnings } = rig(() => - Promise.resolve(new Response(`bad gateway ${"x".repeat(900)}`, { status: 502 })), + Promise.resolve(new Response(`bad gateway ${"x".repeat(900)}`, { status: 200 })), ); const result = await exchange(context, request, identity, "allocate"); @@ -27,7 +27,7 @@ describe("exchange", () => { expect(result.reading.kind).toBe("unusable"); expect(warnings).toHaveLength(1); const fields = warnings[0]?.fields as { body: string; status: number }; - expect(fields.status).toBe(502); + expect(fields.status).toBe(200); expect(fields.body.startsWith("bad gateway xxx")).toBe(true); expect(fields.body.length).toBe(500); }); diff --git a/src/agent-device/front/context.ts b/src/agent-device/front/context.ts index 14ab7b788..6ea70ec82 100644 --- a/src/agent-device/front/context.ts +++ b/src/agent-device/front/context.ts @@ -38,7 +38,7 @@ export async function exchange( const response = await context.link.forward(request, identity); const text = await response.text(); const reading = readReply(text, call); - // why: a 5xx or a body that is not a JSON-RPC reply ends the call as a 502, and its reason is only in what agent-device sent. + // why: the reason for a 5xx or a body that is not a JSON-RPC reply is only in what agent-device sent. if (reading.kind === "unusable" || response.status >= 500) { context.logger.warn("agent-device lease call got an unusable or failed reply", { body: text.slice(0, BODY_LOG_CHARS),