Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
0dd04d8
test: end-to-end tests for agent-device through a simlock worker on r…
V3RON Oct 13, 2026
8a4a57c
test(e2e): agent-device helpers and a shared simlock daemon for the s…
V3RON Oct 13, 2026
e0f6489
test(e2e): split env building to keep complexity down (#477)
V3RON Oct 13, 2026
86383d1
test(e2e): agent env drops AGENT_DEVICE_* and sets HOME; shared daemo…
V3RON Oct 13, 2026
aba056d
test(e2e): never-granted filter reads requester; module-level cleanup…
V3RON Oct 13, 2026
6e5757f
fix(agent-device): accept the backend connect proxy sends on allocate…
V3RON Oct 13, 2026
56aa45b
test(e2e): tryOpen for the open that is expected to fail (#477)
V3RON Oct 13, 2026
d096577
test(e2e): the unavailable-daemon open is expected to fail (#477)
V3RON Oct 13, 2026
0e0b3d6
fix(agent-device): read the allocate reply's lease and device under r…
V3RON Oct 13, 2026
d0e10e5
test(e2e): read the waiting requests from list --requests text, not J…
V3RON Oct 13, 2026
8ebbf57
test(e2e): doctor has no --json flag (plain output is JSON); open the…
V3RON Oct 13, 2026
09133ed
fix(agent-device): /health answers 200 while agent-device is unavaila…
V3RON Oct 13, 2026
78b9c12
fix(agent-device): log a warning with status and body for a 5xx on a …
V3RON Oct 13, 2026
86e8001
test(e2e): the first snapshot on a fresh simulator gets 180 s (#477)
V3RON Oct 13, 2026
46b2455
fix(agent-device): a sharded test names the agent's devices by name, …
V3RON Oct 13, 2026
0efec78
test(e2e): the shard suite declares its platform and runs a step that…
V3RON Oct 13, 2026
9795521
test(e2e): Android tests name a device by its adb serial; the start-u…
V3RON Oct 13, 2026
68dfcb9
fix(agent-device): drop committed run artifacts, tighten tests, corre…
V3RON Oct 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ dist/
.stryker-tmp/
test-results/
playwright-report/
.agent-device
13 changes: 9 additions & 4 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -1514,7 +1514,10 @@ the status.

- `agent-device is not available on this simlock: <reason>`: 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: <message>`: Simlock refused the lease request, for
example a model it does not know, or a `ttlMs` above `lease.maxTtlMs`.
Expand All @@ -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 <id>; run devices to see yours`:
`capabilities` or `doctor` that names no device from an agent not holding
exactly one.
Expand All @@ -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`
Expand Down
1 change: 1 addition & 0 deletions docs/internal/agent-rules/toolchain.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
3 changes: 2 additions & 1 deletion e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
208 changes: 208 additions & 0 deletions e2e/helpers/agent-device.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> } | 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<AgentDeviceResult>;
start(args: readonly string[]): CliBackgroundHandle;
}

interface MadeAgent {
readonly env: SharedTestEnv;
readonly agent: Agent;
readonly background: Set<CliBackgroundHandle>;
}

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<string> {
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<string, string>;
};
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<Agent> {
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<CliBackgroundHandle>();
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<void> {
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<void> {
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})`,
},
);
}
5 changes: 3 additions & 2 deletions e2e/helpers/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export interface CliOptions {
readonly env?: NodeJS.ProcessEnv;
readonly input?: string;
readonly timeout?: number;
readonly entry?: string;
}

export interface CliError {
Expand Down Expand Up @@ -36,7 +37,7 @@ export function cli(
options: CliOptions = {},
): Promise<CliResult> {
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 = "";
Expand Down Expand Up @@ -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 = "";
Expand Down
Loading
Loading