Files
e2e/docs/reference/agent-device.mdx
T

304 lines
14 KiB
Plaintext

---
title: agent-device
description: The mobile engine for iOS simulators and Android emulators, its options, and the device fixture it contributes.
---
`@e2edev/agent-device` drives iOS simulators and Android emulators through
[agent-device](https://github.com/callstack/agent-device). `agent`, `app`,
`screen`, and `expect` work as they do everywhere; this page covers what is
specific to a device target. Import `test` from the package to have `device`
typed, and declare `requires: ['device']` in a suite that also runs on the
web.
Choose **Mobile (iOS/Android)** in `e2e init` to add the package with a
Settings example. iOS needs Xcode and a simulator; Android needs the Android
SDK and an emulator.
The package installs the `agent-device` it was built and tested against,
pinned exactly: agent-device is 0.x and its minors break, so the pin moves
with each engine release. There is nothing else to add to your project.
## Engine
```ts title="e2e.config.ts"
import type { E2EConfig } from 'e2e';
import { createAgent } from 'e2e/agent';
import { agentDevice } from '@e2edev/agent-device';
import { agentDeviceTools } from '@e2edev/agent-device/tools';
import { gateway } from 'ai';
const iphone = agentDevice({ platform: 'ios', app: 'Settings' });
const pixel = agentDevice({ platform: 'android', app: 'com.android.settings' });
export default {
targets: [
{ name: 'iphone', engine: iphone },
{ name: 'pixel', engine: pixel },
],
workers: 1,
agents: {
default: createAgent({
model: gateway('openai/gpt-5.6-luna'),
tools: agentDeviceTools(iphone, pixel),
}),
},
} satisfies E2EConfig;
```
One engine per device family. Platform-specific labels or operations need
`platforms: ['ios']` or `platforms: ['android']`. Device attempts open their
configured app; `app.open()` is unavailable on these targets.
```ts
/**
* Options of the device engine. Every optional value also accepts `undefined`,
* so values read straight from `process.env` need no conditional spread.
*/
export interface AgentDeviceOptions {
/** Platform the target's device runs. */
readonly platform: AgentDevicePlatform;
/**
* App opened fresh at the start of every attempt: a bundle id, a package
* name, or a display name agent-device resolves (`Settings`). Without it the
* surface observes whatever is in the foreground, and `app.restart()` and
* `app.clearState()` are not available.
*/
readonly app?: string | undefined;
/**
* Build to install on the device once per worker, before the first attempt:
* an iOS `.app` bundle or an Android `.apk`, resolved against the project
* root (the config's directory). Without `app`, the installed bundle id or
* package becomes the app opened fresh at the start of every attempt.
*/
readonly appPath?: string | undefined;
/**
* Stable identity keying trace cache and session entries; defaults to `app`,
* else `appPath`. Declare one when the pinned app differs per run (a build
* path with a version in it) so entries survive the rename.
*/
readonly identity?: string | undefined;
/** Report label joining the cache identity; a simulator or emulator defaults to `test`. */
readonly environment?: 'test' | 'staging' | 'production' | undefined;
/**
* Simulator or emulator to use, by name or UDID. A list is a pool: the
* engine declares one worker per entry and worker slot `n` drives the
* `n`th, so `workers` at or above the pool size runs the target's files
* across every device at once. Omitted, the pool is every booted device of
* the platform at `prepare`, as many as the run has slots; with none booted,
* agent-device boots one.
*/
readonly device?: string | readonly string[] | undefined;
/**
* agent-device session name, before the worker slot: slot `n` drives its
* device under `<session>-<n>`, `e2e-<target name>-<n>` by default. One run
* per session at a time: concurrent runs on the same session interleave
* taps.
*/
readonly session?: string | undefined;
/**
* What an observation captures. `full` (default) includes static text, so
* judgments can read values; `interactive` keeps only actionable nodes and
* is cheaper on screens with long lists.
*/
readonly snapshot?: 'full' | 'interactive' | undefined;
/**
* How long the UI must hold still after a tap, fill, or back before the
* action counts as landed, in milliseconds; `false` skips the wait. The
* wait keeps the observation that follows an action off a transition
* frame; the runner's own polling (`expect`, actions waiting for their
* node) covers the rest, so a short window suffices. Default 150. Every
* frame of a running animation changes the tree, so a 150 ms window still
* catches a transition in flight; raise it for slow devices or apps that
* settle in stages, or lower it to 0 to keep only the first re-observation.
*/
readonly settle?: number | false | undefined;
/**
* How long a control that appeared or moved with the last action is given
* to finish arriving before a test acts on it, in milliseconds. Default
* 500, the length of a modal or screen transition. Accessibility frames
* report a control's final position from the first frame of a transition,
* so this budget is the only thing that keeps a test from tapping a point
* the control has not reached; controls already on screen at the same
* place before the action are acted on at once. Raise it for slower
* transitions.
*/
readonly transition?: number | undefined;
}
```
An empty `device` list is `INVALID_CONFIG`.
Devices boot in `prepare`, once per run and before the run's clock starts, so
a cold boot on CI is never charged against `launchTimeout`. agent-device
commands take no abort signal, so a timed-out command keeps running on the
device; the next attempt waits for it to settle. Each attempt relaunches
`app` when one is pinned; without it the model opens apps with the `open_app`
tool.
The engine declares one worker per configured device. With no `device`,
`prepare` uses the booted devices it finds, capped by the run's slots, and
boots one when none are. Two workers never drive the same simulator. To
split a target's files across devices, pass a pool and set `workers` to at
least its size.
```ts
import type { E2EConfig } from 'e2e';
import { agentDevice } from '@e2edev/agent-device';
const iphones = agentDevice({
platform: 'ios',
app: 'com.example.app',
device: ['iPhone 17', 'iPhone 17 Pro'],
});
export default {
targets: [{ name: 'ios', engine: iphones }],
workers: 2,
} satisfies E2EConfig;
```
### Capabilities
| Contract member | On a device |
| --- | --- |
| `observe` | The accessibility tree with rects. iOS: `Button` is `button`, `TextField` and `SearchField` are `textbox`, `SecureTextField` is a secure `textbox`, `Cell` is `listitem`, `StaticText` is `text`, `Switch` is `switch` with `checked`. Android: `TextView` is `text`, `EditText` is `textbox`, `Switch` and `CheckBox` keep their roles without a `checked` state, layouts are `group`, `RecyclerView` is `list`. The accessibility identifier (iOS) or resource id (Android) is the node's `testId`. Pixels on request, with every secure node's bounds painted black. |
| `perform` | `tap`, `doubleTap`, `longPress`, `fill`, `clear`, `hover`, `check`, `uncheck`, `press` (`Enter` or one character), `swipe`, `dragTo`, and `focus` on editable fields. A tap on a `switch` or `checkbox` lands on its innermost control, since UIKit reports a settings row as one labelled switch with the real toggle as a child. `check` and `uncheck` need a `checked` state, which Android switches lack. `selectOption`, `setInputFiles`, and `scrollIntoView` are not declared. |
| `locate` | Every `screen` query. Text queries answer with the innermost match. |
| `app` | `identity` from the pinned `app`, else `appPath`; no `url`. |
| `session` | `back`; `restart` and `reset` when `app` or `appPath` is pinned. No `open`, so `app.open()` and the agent's `navigate` verb are unavailable. |
| `artifacts` | Redacted screenshots under `screenshots/NNN-<label>.png`; a screenshot that cannot be redacted fails instead of being written. Video with `--video` as `video/video.mp4`. No traces. |
| `location` | `<bundle id> / <screen title>`, the trace cache's anchor. The title is the navigation bar's on iOS and the toolbar's on Android. |
| `state` | Not declared. `test.setup` and `session:` are unavailable. |
## Trace cache on a device
A step recorded on `com.apple.Preferences / General` replays only when
Settings is on General again. A mutating project-tool call such as
`open_app` ends a replay. Pin `app` so attempts start on the same screen,
and switch apps through the `device` fixture between steps rather than inside
one.
## Device
```ts
/** Deterministic device management exposed to tests as `device`. */
export interface Device {
/**
* A locator from an agent-device selector (`'id=SW_VERSION_SPECIFIER'`,
* `'role=StaticText label="26.2"'`), for nodes the closed `screen` query
* vocabulary cannot name. Same polling and strictness as any locator.
*/
locator(selector: string): Locator;
/** Toggles the device's Wi-Fi. */
setNetwork(state: 'online' | 'offline'): Promise<void>;
/** Toggles airplane mode. */
setAirplaneMode(enabled: boolean): Promise<void>;
/** Grants, denies, or resets one permission for the open app. */
setPermission(permission: DevicePermission, state: 'grant' | 'deny' | 'reset'): Promise<void>;
/** Sets the simulated location. */
setLocation(coordinates: { latitude: number; longitude: number }): Promise<void>;
/** Turns simulated location off. */
clearLocation(): Promise<void>;
/** Sets the system appearance. */
setAppearance(mode: 'light' | 'dark'): Promise<void>;
/** Rotates the device. */
setOrientation(orientation: DeviceOrientation): Promise<void>;
/** Simulates one biometric attempt on the open app. */
setBiometrics(sensor: BiometricSensor, result: 'match' | 'nonmatch'): Promise<void>;
/** Enrolls or unenrolls the simulator's Face ID or Touch ID. */
enrollBiometrics(sensor: 'faceid' | 'touchid', enrolled: boolean): Promise<void>;
/**
* Installs a build (an iOS `.app` bundle or an Android `.apk`, resolved
* against the project root) on the device. `reinstall: true` removes
* the app first so it starts with no data; a plain install replaces the
* binary and keeps its data. Resolves to the identity to `openApp` it by.
*/
installApp(appPath: string, options?: InstallAppOptions): Promise<InstalledApp>;
/** Brings an app to the foreground; `relaunch` restarts it fresh. */
openApp(app: string, options?: { relaunch?: boolean }): Promise<void>;
/** Closes the session's current app. */
closeApp(): Promise<void>;
/** The app currently in the foreground of the session. */
foregroundApp(): Promise<ForegroundApp>;
/** Sends the device to its home screen. */
home(): Promise<void>;
/** Navigates back once (in-app back). */
back(): Promise<void>;
/** Accepts or dismisses the visible system alert. */
alert(action: 'accept' | 'dismiss'): Promise<void>;
/** Dismisses the soft keyboard. */
dismissKeyboard(): Promise<void>;
/** Reads the clipboard. */
clipboard(): Promise<string>;
/** Writes the clipboard. */
setClipboard(text: string): Promise<void>;
}
/** Permissions agent-device can grant, deny, or reset on an open app. */
export type DevicePermission =
| 'camera'
| 'microphone'
| 'photos'
| 'contacts'
| 'notifications'
| 'calendar'
| 'location'
| 'reminders'
| 'motion'
| 'siri'
| 'media-library';
/** Orientations `setOrientation` accepts. */
export type DeviceOrientation = 'portrait' | 'portrait-upside-down' | 'landscape-left' | 'landscape-right';
```
Every async method is a recorded step named `device.<method>`, bounded by
`config.actionTimeout`. A lost session is `APP_NOT_OPEN`, a timeout is
`ACTION_FAILED`, a command the platform cannot run is
`UNSUPPORTED_CAPABILITY`, anything else `ENGINE_FAILURE`.
`installApp` installs a build from inside a test, for upgrade paths. A plain
install keeps the app's data; `reinstall: true` removes the app named by
`app` (default: the pinned app) first. It resolves to the id to `openApp`
the build by.
```ts
const { app } = await device.installApp('./build/MyApp.app', { reinstall: true });
await device.openApp(app);
```
`locator` mints a core `Locator` from an agent-device selector, for nodes the
`screen` vocabulary cannot name.
```ts
await expect(device.locator('role=NavigationBar id=About')).toBeVisible();
await expect(device.locator('role=StaticText label="iOS Version"')).toHaveText('iOS Version');
await device.locator('id=SW_VERSION_SPECIFIER role=Button').tap();
```
Selector terms are agent-device's: `id`, `role`, `text`, `label`, `value`,
`appname`, `windowtitle`, and the flags `visible`, `hidden`, `editable`,
`selected`, `focused`, `enabled`, `hittable`. `role` accepts the platform
type (`StaticText`) or the contract role (`text`).
## Agent tools
`agentDeviceTools(...engines)` returns a `defineTool` pack for `createAgent`.
Pass every device engine the config declares; two packs cannot be merged. The
pack dispatches each call to the engine whose attempt is running:
| Tool | Replay | Purpose |
| --- | --- | --- |
| `open_app` | gap | Bring an app to the foreground, optionally relaunched. |
| `swipe` | gap | Free-form swipe between two points in logical pixels. |
| `type_text` | gap | Type into the focused field, optionally pressing Return; for editors that hide the focused field from the tree. |
| `alert` | gap | Accept or dismiss a system alert. |
The grammar verbs (`tap`, `type`, `scroll`) come from the engine and need no
tool. The engine declares `tapAt`, so a `tap_at` on nothing the tree lists
taps the bare point. `type_secret` is not offered on a device.
After a secret fill the agent offers neither `screenshot` nor `tap_at`,
including in later members of the same serial group. Pixels whose masking the
engine cannot prove are withheld as `MASKING_UNPROVEN`.