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/docs/HTTP-API.md b/docs/HTTP-API.md index 0353edd7b..0323e174e 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`. @@ -1532,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. @@ -1550,8 +1554,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/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..fbadf3965 --- /dev/null +++ b/e2e/helpers/agent-device.ts @@ -0,0 +1,208 @@ +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 { dirname, 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 { + 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; +} + +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; +} + +// 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( + platform: "ios" | "android" = "ios", +): 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}`, + ); + } + 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; +} + +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 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(); + // why: a developer's own AGENT_DEVICE_* settings must never point an agent at their own daemon. + const inherited = Object.fromEntries( + Object.entries(process.env).filter(([key]) => !key.startsWith("AGENT_DEVICE_")), + ); + const childEnv: NodeJS.ProcessEnv = { + ...inherited, + HOME: home, + 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 ?? 60_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 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 }); + }), + ); +} + +// 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 { + let last = "no answer"; + await waitFor( + async () => { + try { + const response = await fetch(`${proxyUrl(env)}/health`, { + headers: { authorization: `Bearer ${token}` }, + }); + 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 (last reply: ${last})`, + }, + ); +} 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 cd950efda..6c03bc2d1 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"; @@ -178,15 +178,19 @@ export interface TestEnv { * it itself (e.g. `waitForLeaseCount(env, 0)`). */ 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"); + const { testEnv, state } = await buildEnv(options); + activeEnvs.add(state); + return testEnv; +} +function processEnv( + options: WithDaemonOptions, + 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 @@ -201,13 +205,35 @@ export async function withDaemon(options: WithDaemonOptions = {}): Promise | 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"); } @@ -315,15 +341,82 @@ export async function withDaemon(options: WithDaemonOptions = {}): Promise; + restart(): Promise; +} + +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); + const restartSteps = async (): Promise => { + const pids = await pidsHoldingSocket(state.socketPath); + 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, + 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); + } + }, + }; } interface TeardownState { @@ -403,6 +496,32 @@ async function teardown(state: TeardownState): Promise { } } +async function readAgentDevicePid(home: string): Promise { + const text = await readFileIfExists(join(home, "agent-device-daemon.json")); + if (text === undefined) return undefined; + try { + const record = JSON.parse(text) as { pid?: unknown }; + return typeof record.pid === "number" ? record.pid : undefined; + } catch { + return undefined; + } +} + +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(pid, "SIGKILL"); + } catch { + // why: the process may have 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 diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index d4f367a3f..d950693e3 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -2,11 +2,19 @@ // 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 { + 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 // 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..ee4317a6a --- /dev/null +++ b/e2e/slow-agent-device.test.ts @@ -0,0 +1,793 @@ +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, + beforeEach, + describe, + expect, + it, + onTestFinished, +} from "vitest"; + +import { + assertPinnedAgentDevice, + 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; + // why: the address agent-device names the device by (an iOS UDID, an Android adb serial); on Android it is not the driver's device id. + readonly address: string; + readonly state: string; +} +interface LeaseRow { + readonly id: string; + readonly deviceId: string; + readonly ownerId: string; + readonly requesterId: string; +} +interface RequestRow { + readonly requesterId: string; +} + +// why: the first snapshot on a fresh simulator starts the XCTest runner, which agent-device gives 45 s to start (RUNNER_STARTUP_TIMEOUT_MS in packages/platform-apple/src/runner/runner-startup-transport.ts), so with the command's own 45 s it can pass the CLI's 60 s default and cut off agent-device's answer. +const FIRST_SNAPSHOT = { timeout: 180_000 } as const; + +// why: vitest holds a test's console output until the test ends; a write to fd 2 reaches the log at once, so a stuck test shows while it runs. +function progress(line: string): void { + writeSync(2, `${new Date().toISOString()} ${line}\n`); +} + +async function listRows(env: SharedTestEnv, flag: string): Promise { + const result = await env.cli(["list", flag], { timeout: 60_000 }); + expect(result.code, `simlock list ${flag}: ${result.stderr}`).toBe(0); + return result.json as T[]; +} + +const listDevices = (env: SharedTestEnv) => listRows(env, "--devices"); +const listLeases = (env: SharedTestEnv) => listRows(env, "--leases"); + +// why: `simlock list --requests` prints one text line per request (`Request : [ on ], ...`) or "No requests are waiting.", never JSON. +async function listRequests(env: SharedTestEnv): Promise { + const result = await env.cli(["list", "--requests"], { timeout: 60_000 }); + expect(result.code, `simlock list --requests: ${result.stderr}`).toBe(0); + return result.stdout + .split("\n") + .map((line) => /^Request \S+: ([^\s,]+)/.exec(line)) + .filter((match) => match !== null) + .map((match) => ({ requesterId: match[1] as string })); +} + +async function waitForFree(env: SharedTestEnv): Promise { + let observed = "nothing read yet"; + await waitFor( + async () => { + const [devices, leases, requests] = await Promise.all([ + listDevices(env), + listLeases(env), + listRequests(env), + ]); + observed = `devices ${devices.map((device) => device.state).join(",") || "none"}; leases ${String(leases.length)}; requests ${String(requests.length)}`; + return ( + devices.length > 0 && + devices.every((device) => device.state === "ready") && + leases.length === 0 && + requests.length === 0 + ); + }, + { + timeout: 240_000, + interval: 1_000, + label: () => `every device ready, no lease, no request; last observed: ${observed}`, + }, + ); +} + +function ok(result: AgentDeviceResult): void { + expect(result.code, `${result.stdout}\n${result.stderr}`).toBe(0); +} + +function failureText(result: AgentDeviceResult): string { + return result.error?.message ?? `${result.stdout}\n${result.stderr}`; +} + +function refused(result: AgentDeviceResult): void { + expect(result.code, "the command was accepted").not.toBe(0); + expect(failureText(result)).toContain("refused:"); +} + +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); + // 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 tryOpen(who); + if (result.code !== 0) { + throw new Error(`open failed for ${who.name}: ${result.stdout}\n${result.stderr}`); + } + return result; + }; + + 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 () => { + const pinned = await assertPinnedAgentDevice(platform); + env = await withSharedDaemon({ + driver: "real", + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, + agentDevice: { enabled: true, command: pinned }, + 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); + + 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 }); + 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"], FIRST_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 reports no agent-device-unavailable finding and no finding whose message names agent-device", + { timeout: 600_000 }, + async () => { + 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([]); + }, + ); + + 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])); + // 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"], FIRST_SNAPSHOT)); + const [lease] = await listLeases(env); + 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 })); + + 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(address, 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 { requester?: string }).requester === 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"], { 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 tryOpen(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?.address, + ]); + }, + ); + + 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)); + // 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); + 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 address = devices.find((device) => device.id === lease?.deviceId)?.address; + if (address === undefined) + throw new Error(`no leased device found for agent ${who.name}`); + return address; + }; + + 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)); + }, + ); + + 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 })); + // 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"]); + 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), +); diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 8a2ab9d2f..447e64cc3 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"); @@ -563,6 +567,9 @@ 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(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}`); @@ -761,6 +768,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 +818,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(); @@ -830,7 +861,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"]) { @@ -844,7 +875,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"); @@ -863,7 +894,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)]); }); @@ -1793,6 +1824,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 }); @@ -2696,6 +2741,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"]); @@ -3119,7 +3169,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) } }]), @@ -3217,9 +3267,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(), ); }); @@ -3238,9 +3288,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 })); @@ -3251,6 +3301,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); @@ -3259,7 +3323,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/allocate.ts b/src/agent-device/front/allocate.ts index 4046cd32d..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, @@ -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( @@ -288,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( @@ -320,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..8b128c179 --- /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: 200 })), + ); + + 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(200); + 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..6ea70ec82 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: 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), + 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/front/front.ts b/src/agent-device/front/front.ts index 431ad0e30..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); } @@ -195,8 +225,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), 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; } 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..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); @@ -418,10 +423,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 +447,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 { @@ -549,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 });