> ## Documentation Index
> Fetch the complete documentation index at: https://e2e.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Mobile

> API reference for @e2e-dev/mobile, the engine for iOS simulators, Android emulators, and connected phones, with its options and the device fixture.

`@e2e-dev/mobile` is the engine for iOS simulators, Android emulators, and
connected phones, driven through
[agent-device](https://github.com/callstack/agent-device). It contributes the
`device` fixture. `agent`, `app`, `screen`, and `expect` work as they do
everywhere; this page covers what is specific to a device target.

```ts title="e2e.config.ts"

export default {
  targets: [
    { name: 'iphone', engine: mobile({ platform: 'ios' }), app: { bundleId: 'com.apple.Preferences' } },
  ],
} satisfies E2EConfig;
```

```ts title="tests/settings.e2e.ts"

test('General opens in dark mode', async ({ app, device, screen }) => {
  await device.setAppearance('dark');
  await app.open();
  await screen.getByText('General').tap();
  await expect(screen.getByText('About')).toBeVisible();
});
```

- Import `test` from `@e2e-dev/mobile` to have `device` typed. Declare
  `platforms: ['ios', 'android']` 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 includes a compatible version of `agent-device`; no separate
  installation is needed.

## Reference

### Engine

`mobile(options)` creates an engine for one platform. Create one for each
platform you test, and use `platforms: ['ios']` or `platforms: ['android']`
on tests with platform-specific labels or operations.

```ts title="e2e.config.ts"

const iphone = mobile({ platform: 'ios' });
const pixel = mobile({ platform: 'android' });

export default {
  targets: [
    { name: 'iphone', engine: iphone, app: { bundleId: 'Settings' } },
    { name: 'pixel', engine: pixel, app: { bundleId: 'com.android.settings' } },
  ],
  workers: 1,
  agents: {
    default: {
      model: gateway('openai/gpt-6-luna-fast'),
      tools: mobileTools(iphone, pixel),
    },
  },
} satisfies E2EConfig;
```

`mobile()` takes `MobileOptions`: which devices the engine drives and how.
The app under test is the target's `app`, not an engine option; see
[The app under test](#the-app-under-test).

| Option | Type | Default |
| --- | --- | --- |
| [`platform`](#platform) | `'ios' \| 'android'` | required |
| [`device`](#device-option) | `string \| readonly string[] \| DeviceProvider` | every booted device |
| [`session`](#session) | `string` | `e2e-<target name>` |
| [`snapshot`](#snapshot) | `'full' \| 'interactive'` | `'full'` |
| [`settle`](#settle) | `number \| false` | `150` |
| [`transition`](#transition) | `number` | `500` |
| [`videoTouches`](#videotouches) | `boolean` | `true` |

Every optional value also accepts `undefined`, so values read straight from
`process.env` need no conditional spread.

| Throws | When |
| --- | --- |
| `INVALID_CONFIG` | An empty `device` list, a blank `device` name, or a blank or non-string list entry. |
| `INVALID_CONFIG` | A `device` value that is neither a string, a list, nor a valid provider: a provider without a non-empty `name`, without `acquire()` or `release()`, or with a `record` that is not a function. |
| `INVALID_CONFIG` | `platform` is missing or not `'ios'` or `'android'`; the match is case-sensitive. |
| `INVALID_CONFIG` | A provided `snapshot` value is not `'full'` or `'interactive'`, or a provided `videoTouches` value is not a boolean. |
| `INVALID_CONFIG` | An option `mobile()` does not take, such as `mobile({ app })` and the other old app options. The message names the nearest known option for a likely typo, or lists every option. |
| `INVALID_CONFIG` | `settle` or `transition` is not a non-negative integer of milliseconds (`settle` may also be `false`). |

#### `platform`

```ts
readonly platform: MobilePlatform;
```

```ts
mobile({ platform: 'android' });
```

#### `device` option

```ts
readonly device?: string | readonly string[] | DeviceProvider | undefined;
```

```ts
mobile({ platform: 'ios' }); // default: every booted iOS device no other agent-device session holds
mobile({ platform: 'ios', device: 'iPhone 17' });
mobile({ platform: 'android', device: 'emulator-5554' });
mobile({ platform: 'ios', device: ['iPhone 17', 'iPhone 17 Pro'] });
```

- A name picks a simulator or emulator by name, simulator UDID, or emulator
  serial (`emulator-5554`), or a connected phone by name.
- 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.
- Without `device`, the pool is every booted device of the platform at
  [`prepare`](#boot-and-prepare) that no other agent-device session holds, as
  many as the run has slots. A paired iPhone or iPad that is reachable (USB or
  network) counts as booted. With every booted one held, `prepare` fails.
- With none booted, agent-device boots a shut-down one: on iOS an iPhone over
  an iPad over an Apple TV, on Android a phone or tablet over a TV, then the
  newest OS, then name order. A stopped Android emulator reports no OS
  version, so the name decides.
- A `DeviceProvider` leases hosted devices instead, one per worker slot at
  `prepare`, and holds each lease until the run ends.
- `device.closeApp()` ends the agent-device session, so another session can
  take the device.
- Two workers never drive the same device, as long as each `device` entry
  names a different one.
- Without `device`, a booted device nothing holds, such as one you are using
  by hand, is in the pool: name the device to keep the run off it.
- A pooled device that another agent-device session claims while the run
  prepares is swapped for the next free one. With none free, a run with
  several workers goes on with one worker fewer. A named device or a
  provider's lease is never swapped.
- [Hosted devices](https://e2e.com/docs/mobile#hosted-devices) has the `DeviceProvider` contract
  and an example provider.

#### `session`

```ts
readonly session?: string | undefined;
```

```ts
mobile({ platform: 'ios', session: 'checkout' }); // default: e2e-<target name>
```

- The name comes 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.
- Without this option, a `launch()` host drives
  `e2e-<target name>-<host token>-<n>`, a session of its own.

#### `snapshot`

```ts
readonly snapshot?: 'full' | 'interactive' | undefined;
```

```ts
mobile({ platform: 'android', snapshot: 'interactive' }); // default: 'full'
```

What an observation captures. `'full'` includes static text, so judgments
can read values. `'interactive'` keeps only actionable nodes and is cheaper
on screens with long lists.

#### `settle`

```ts
readonly settle?: number | false | undefined;
```

```ts
mobile({ platform: 'ios', settle: 300 }); // default: 150
```

- How long the UI must hold still, in milliseconds, after a tap, fill, screen
  scroll, or back before the agent observes again. `false` skips the wait.
- Raise it for slow devices or apps that settle in stages, or lower it to `0`
  to keep only the first re-observation.
- A test's steps do not settle, except `device.back()`: `expect` verifies
  their outcome, and [`transition`](#transition) covers a control that is
  still arriving.

#### `transition`

```ts
readonly transition?: number | undefined;
```

```ts
mobile({ platform: 'ios', transition: 800 }); // default: 500
```

The wait, in milliseconds, before acting on a control that just appeared or
moved. Raise it for slower transitions.

- An unmoved control is acted on at once only when keyboard visibility is
  unchanged. Opening or closing the keyboard also uses the remaining budget.
- A screen swipe in a test waits out the remaining budget before scrolling.

If the control changes during the wait, the action finds it again within its timeout before acting.

`back`, `home`, `pressRemote`, `pressButton`, `shake`, `lock`, `unlock`, `alert`,
`dismissKeyboard`, `setOrientation`, and `fold` on [`device`](#device) change the screen, so they count as actions for this
budget the way a tap does. A control that arrives with the screen they reveal
waits out the budget before the next action lands on it.

`fill` and `clear` on a field that is missing, changed its security state, or
was captured incompletely return `NODE_STALE` before typing, then retry after
a fresh observation. Non-input targets return `UNSUPPORTED_CAPABILITY`. An
iOS `other`, the type of an element the platform did not classify, is typed
into when it holds a value or only text, as a custom-drawn field (Compose
Multiplatform, Flutter) can.

#### `videoTouches`

```ts
readonly videoTouches?: boolean | undefined;
```

```ts
mobile({ platform: 'ios', videoTouches: false }); // default: true
```

Whether a video recording draws agent-device's touch indicator where a test
tapped. `false` records the plain screen and skips the pass that draws the
indicator once the recording stops. On a hosted daemon such as Expo
Simulators' that pass can outlast the attempt's `cleanupTimeout`.

#### The app under test

The app is the target's `app`: `bundleId`, `appPath`, `launchArguments`,
`permissions`, `identity`, and `environment` are documented under
[the app under test](https://e2e.com/docs/reference/config#the-app-under-test).

```ts title="e2e.config.ts"
export default {
  targets: [{ name: 'ios', engine: mobile({ platform: 'ios' }), app: { appPath: './build/MyApp.app' } }],
} satisfies E2EConfig;
```

- A device target needs `app.bundleId` or `app.appPath`.
- `app.open()` launches the target's app fresh. An attempt launches nothing
  on its own, so a test starts where the previous one left the app.
- `app.open(path)` opens the path as a link in the app when the target
  declares [`app.linkBase`](https://e2e.com/docs/reference/config#linkbase); without it, `app.open`
  takes no path and a link goes through [`device.openLink`](#openlink).
- `app.appPath` is the build the suite runs against. The engine installs
  nothing on its own: [`device.installApp()`](#installapp) installs it where
  the suite says so. A device provider installs it on the device it leases.
- Without `bundleId`, the installed bundle id or package becomes the app
  `app.open()` launches.
- Declare an `identity` when the build path changes per run (a version in
  it), so recordings survive the rename.

| Throws | When |
| --- | --- |
| `INVALID_CONFIG` | At config load: no `app.bundleId` and no `app.appPath`; an `app.url` (not supported yet); a link in `bundleId` (a test opens one with `device.openLink`); an unknown permission name; an Apple launch argument such as `AppleLocale`, or a list item `am start` cannot carry, in an object on an Android target. |
| `UNSUPPORTED_CAPABILITY` | `app.open()`, `app.restart()`, or `app.clearState()` on a target with no `app.bundleId` before its build is installed. |

#### Launch arguments and permissions

`app.launchArguments` and `app.permissions` ride every fresh launch of the
pinned app: `app.open()`, `app.restart()`, and `app.clearState()`, which
resets the permissions with the data.

```ts title="e2e.config.ts"
export default {
  targets: [
    {
      name: 'pixel',
      engine: mobile({ platform: 'android' }),
      app: {
        bundleId: 'com.example.app',
        launchArguments: ['--ez', 'e2e', 'true'],
        permissions: { camera: 'grant', notifications: 'deny' },
      },
    },
  ],
} satisfies E2EConfig;
```

- iOS hands the arguments to the app process
  (`ProcessInfo.processInfo.arguments`). Android appends them to `am start`,
  so `['--ez', 'e2e', 'true']` is a boolean intent extra.
- An object gives each argument a name.
  - On iOS, each entry becomes `-name value` in the format that
    `NSUserDefaults` reads. A string that the parser could read as a plist or
    a comment, such as `(draft)`, `a b`, or `//cdn`, gets quotes. An app that
    reads `ProcessInfo.processInfo.arguments` receives this format, with `NO`
    for `false` and the quotes included. If your app reads
    `ProcessInfo.processInfo.arguments`, use the list format instead:
    `launchArguments: ['-flag', 'false', '-title', 'a b']`.
  - On Android, each entry becomes an `am start` extra of the value's type.
    The app reads it with the matching `Intent` getter. A whole number such
    as `1.0` is an `int`. Android does not read Apple arguments, so
    `AppleLanguages` or `AppleLocale` in an object on an Android target fails
    with `INVALID_CONFIG`. A list of strings goes to `am start` unchanged.
- On Android, a list in an object fails with `INVALID_CONFIG` when the list
  is empty, or when an item is empty, contains a comma, or ends with a
  backslash.

| Value | iOS | Android |
| --- | --- | --- |
| `'fr_FR'` | `-name fr_FR` | `--es name fr_FR` |
| `'(draft)'` | `-name "(draft)"` | `--es name (draft)` |
| `true` | `-name YES` | `--ez name true` |
| `3` | `-name 3` | `--ei name 3`, `--el` outside Java's `int` |
| `1.5` | `-name 1.5` | `--ef name 1.5` |
| `-1` | `-name "-1"` | `--ei name -1` |
| `['fr', 'de']` | `-name (fr, de)` | `--esa name fr,de` |

- Each permission is `grant`, `deny`, or `reset`. `reset` puts it back to not
  asked for yet, so the OS asks again. `deny` is a recorded
  refusal on iOS, where the app is told no without a prompt, and a revocation
  on Android, where the OS asks again when the app requests the permission.
- `permissions: 'all'` grants every permission the platform can set. It
  replaces the map; name permissions instead to deny or reset one.
  - On Android: each runtime permission the app's manifest declares.
    Permissions that are not grantable at run time, such as `INTERNET`, are
    skipped, so an app that declares none launches with nothing changed.
  - On an iOS simulator: each privacy service the runtime can set, with
    location `always`. The simulator refuses notifications, so accept that
    prompt with `device.alert('accept')`.
- The open in [`prepare`](#boot-and-prepare) passes no launch argument and
  touches no permission.
- [`device.openApp(app, { relaunch: true, launchArguments, permissions })`](#openapp)
  does the same for one launch of any app.

| Throws | When |
| --- | --- |
| `INVALID_CONFIG` | In `app.permissions`: a permission name outside `DevicePermission` (naming the nearest one when it is a likely typo), or a state other than `grant`, `deny`, or `reset`. Fails before any device command. |
| `INVALID_ARGUMENT` | The same, in `device.openApp`. |

#### Boot and prepare

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`.

- On iOS, `prepare` starts the automation runner on every device.
- Then, on both platforms, it opens the target's `app.bundleId` once per
  device. A build the suite installs itself comes up with the first
  `app.open()`.
- A device that cannot boot, or a runner that is busy, wedged, or past its
  watchdog, ends the run in `prepare`.
- A runner that does not start for another reason is logged and left to the
  first attempt, and that device's app is not opened there.

Each device logs one line of how long its prepare steps took, a failed step
included: `boot`, `iOS runner` (the automation runner's start, on iOS only),
and `open <app>`, which is missing where the open is skipped. A cold iOS
simulator:

```text
ℹ booting E93FA5E5-1592-43C7-9149-F1B5FE0AD5F5 (1 of 1)
ℹ E93FA5E5-1592-43C7-9149-F1B5FE0AD5F5: boot 36.3s, iOS runner 61.6s, open dev.e2e.benchmark 9.2s
```

An ordinary app-open failure is logged on a line of its own,
`<device>: <app> did not open (<reason>); the first attempt opens it`, and
the run goes on.

<Note>
A pending tap, double tap, multi-tap, focus, check or uncheck is cancelled when
the step stops waiting for it or the run is interrupted. Input already sent
to the device may still finish. Other commands can outlive their caller's
timeout; the next attempt waits for them to finish.
</Note>

#### Capabilities

| Contract member | On a device |
| --- | --- |
| `observe` | The accessibility tree with rects. Element types map onto roles as listed under [Roles](#roles); a `Switch` or `CheckBox`, and an Android `RadioButton`, carry the `checked` state the device reports, and a `SecureTextField` or an Android field flagged as `password` is a secure `textbox`. An iOS field keeps a value equal to its label (an unlabeled field is named by its text); Android's echo of a text view's label as its value is dropped. The accessibility identifier (iOS) or resource id (Android) is the node's `testId`. An Android node is named by the content description its app set (React Native's `accessibilityLabel`), or by its text, and its `text` is what it shows, so a labeled text view or a filled field answers `getByLabel` by its label and `getByText` by its text. Nodes also carry `label`, `resource-id`, `class`, and Android `content-desc` attributes (see [`getAttribute`](https://e2e.com/docs/reference/screen#getattribute)). A field's hint is its `placeholder` attribute, showing or not. Compose Multiplatform reports no placeholder on iOS: an empty field appends the text it draws to its label (`Name, Ada Lovelace`) over one `StaticText` child, so that text is the field's `placeholder` and the child is left out. An empty field has no value: an iOS field whose value equals its placeholder (trimmed) reads empty, text typed to match the placeholder exactly included. On Android, `rect` and every point are the screen's physical pixels; the display density is not applied yet. Android's status bar and navigation bar are left out; the notification shade, system dialogs, and a heads-up notification or other popup inset from the sides stay. Pixels on request, with every secure node's bounds painted black. |
| `perform` | `tap`, `doubleTap`, `multiTap`, `longPress`, `fill`, `clear`, `hover`, `check`, `uncheck`, `press` (`Enter`, `Space`, or one character), `swipe`, `scrollTo`, `dragTo`, and `focus` on editable fields. `scrollTo` drags the node, or the screen on the root, until the content stops changing. A tap on a `switch` or `checkbox` lands on its innermost control. `check` and `uncheck` need a `checked` state. Switches report one on both platforms, and so does a native Android `CheckBox`; a React Native checkbox or radio reports one only when the app sets `accessibilityState.checked`. A control with no state is `UNSUPPORTED_CAPABILITY`, so tap it instead. `doubleTap` is two presses, 284 to 285 ms apart on iOS. A detector with a window of 300 ms or less can read the pair as two single taps. `multiTap` is `count` presses at the same cadence as `doubleTap`, so the same short-window caveat applies; a `count` above 200 is `UNSUPPORTED_CAPABILITY` before any press. At about 285 ms a press on iOS, 200 presses take about a minute, past the default action timeout of 30 s, so pass a longer `timeout` for a large `count`. `longPress` holds for one second unless the test passes `duration`. `blur`, `selectOption`, `setInputFiles`, `scrollIntoView`, and `secondaryTap` are not declared, and neither is `tapModifiers`, so `tap`, `doubleTap`, or `multiTap` with `modifiers` is `UNSUPPORTED_CAPABILITY`. |
| `performAt` | `tap`, `doubleTap`, `longPress`, and `swipeTo` at a bare screen point, so `screen.tapAt`, `screen.doubleTapAt`, `tap({ position })`, `screen.swipe({ from, to })`, and the agent's `tap_at` reach a control the tree does not list. On iOS, while the soft keyboard is open, a `screen.swipe({ from, to })` with no `duration` has to stay above it, and fails with `ACTION_FAILED` before anything is sent when it doesn't. With `duration` the path goes out as given, across the keyboard, as a test of interactive keyboard dismissal needs. No `hover`, `secondaryTap`, or `dragTo` at a point, so `hover_at` needs a listed control. |
| `keyboard` | `type` and `press` into the focused field, the agent's `type` and `press` without a target and the fallback of `type_at` and `press_at`, and `dismiss`, the agent's `dismiss_keyboard`. |
| `locate` | Every `screen` query. Text and label queries answer with the innermost match. On Android a test id query, a string or a RegExp, also matches a resource id without its `<package>:id/` prefix, for any package but the framework's `android`, when nothing on the screen matches the full id. `screen.locator('id=…')` is agent-device's selector and takes the full id. |
| `validateApp` | Requires `app.bundleId` or `app.appPath` and refuses `app.url` for now, with a note on reaching this machine from the platform's device. |
| `session` | `back`, `restart`, `reset`, and `openLink`, behind `app.open(path)` on a target with `app.linkBase`. No `open`: `app.open()` with no path is served with `restart`, the fresh launch of the pinned app; the agent's `navigate` verb is unavailable, and `device.openLink(url)` opens a deep link or web link. |
| `artifacts` | Redacted screenshots under `screenshots/NNN-<label>.png`; a screenshot that cannot be redacted fails instead of being written. Video, when the attempt's [video mode](https://e2e.com/docs/reference/config#video) records, as `video/video.mp4`, or a device provider's own recording. |
| `location` | `<bundle id> / <screen title>`, the replay 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. |

### Device

The `device` fixture is deterministic device management. A test calls it
directly to arrange or assert device state.

```ts
test('offline banner', { platforms: ['android'] }, async ({ app, device, screen }) => {
  await app.open();
  await device.setNetwork('offline');
  await expect(screen.getByText('You are offline')).toBeVisible();
  await device.setNetwork('online');
});
```

| Member | Returns |
| --- | --- |
| [`unstable_raw`](#unstable_raw) | `DeviceSession` |
| [`locator`](#locator) | `Locator` |
| [`setNetwork`](#setnetwork) | `Promise<void>` |
| [`setAirplaneMode`](#setairplanemode) | `Promise<void>` |
| [`setPermission`](#setpermission) | `Promise<void>` |
| [`setLocation`](#setlocation) | `Promise<void>` |
| [`clearLocation`](#clearlocation) | `Promise<void>` |
| [`setAppearance`](#setappearance) | `Promise<void>` |
| [`setOrientation`](#setorientation) | `Promise<void>` |
| [`fold`](#fold) | `Promise<void>` |
| [`setBiometrics`](#setbiometrics) | `Promise<void>` |
| [`enrollBiometrics`](#enrollbiometrics) | `Promise<void>` |
| [`installApp`](#installapp) | `Promise<InstalledApp>` |
| [`uninstallApp`](#uninstallapp) | `Promise<boolean>` |
| [`isAppInstalled`](#isappinstalled) | `Promise<boolean>` |
| [`openApp`](#openapp) | `Promise<void>` |
| [`openLink`](#openlink) | `Promise<void>` |
| [`closeApp`](#closeapp) | `Promise<void>` |
| [`clearKeychain`](#clearkeychain) | `Promise<void>` |
| [`foregroundApp`](#foregroundapp) | `Promise<ForegroundApp>` |
| [`viewport`](#viewport) | `Promise<ViewportSize>` |
| [`home`](#home) | `Promise<void>` |
| [`back`](#back) | `Promise<void>` |
| [`pressRemote`](#pressremote) | `Promise<void>` |
| [`pressButton`](#pressbutton) | `Promise<void>` |
| [`shake`](#shake) | `Promise<void>` |
| [`lock`](#lock) | `Promise<void>` |
| [`unlock`](#unlock) | `Promise<void>` |
| [`alert`](#alert) | `Promise<void>` |
| [`dismissKeyboard`](#dismisskeyboard) | `Promise<void>` |
| [`isKeyboardShown`](#iskeyboardshown) | `Promise<boolean>` |
| [`clipboard`](#clipboard) | `Promise<string>` |
| [`setClipboard`](#setclipboard) | `Promise<void>` |

Every async method is a recorded step named `device.<method>`, bounded by
`config.actionTimeout`. The methods that change the screen count as actions
for the [`transition`](#transition) budget; that entry lists them. The types
the entries use are under [Types](#device-fixture).

| Throws | When |
| --- | --- |
| `APP_NOT_OPEN` | The session is lost. |
| `ACTION_FAILED` | `actionTimeout` expires. |
| `UNSUPPORTED_CAPABILITY` | The platform cannot run the command. |
| `ENGINE_FAILURE` | Anything else, with agent-device's message. A timeout the device itself reports (a boot, the runner connecting) keeps its text and hint there. A busy or wedged iOS automation runner names itself and the recovery (see [Troubleshooting](https://e2e.com/docs/mobile#troubleshooting)). |

#### `unstable_raw`

```ts
readonly unstable_raw: DeviceSession;
```

```ts
const { client, selection } = device.unstable_raw;
await client.apps.list(selection);
```

`client` is typed as `DeviceSessionClient`, exported from `@e2e-dev/mobile`.
After the worker disposes the session, reading `unstable_raw` or `client`
throws `INVALID_STATE`.

- Use it for what the methods here do not cover.
- Calls through `client` bypass e2e. They are not steps, so the report and
  trace leave them out and the agent's cache does not replay them. Their
  arguments reach the driver unredacted, and nothing waits for the screen to
  settle after one.
- It is unstable: it may change or go away in any release.

#### `locator`

```ts
locator(selector: string): Locator;
```

```ts
await expect(device.locator('role=navigation-bar id=About')).toBeVisible();
await expect(device.locator('role=text label="iOS Version"')).toHaveText('iOS Version');
await device.locator('id=SW_VERSION_SPECIFIER role=button').tap();
```

Use it for a node the `screen` queries cannot name. It polls and is strict
like any locator.

Selector terms and their rules are agent-device's, the ones `agent-device
find ... list` applies:

- Terms: `id`, `role`, `text`, `label`, `value`, `appname`, `windowtitle`,
  and the flags `visible`, `hidden`, `editable`, `selected`, `focused`,
  `enabled`, `hittable`.
- `role` takes agent-device's kind, the role `agent-device snapshot` prints:
  `button`, `text`, `text-field`, `navigation-bar`, `scroll-area`, `switch`,
  `image`. It is not the `getByRole` role (`textbox`).
- Text terms compare case-insensitively after collapsing whitespace.
- `visible` means the node is hittable or has a non-empty frame; `hidden` is
  its opposite.
- `text` reads the first non-empty label, value, or identifier.

<Note>
An action on a selector that matches several nodes fails, where an
agent-device action skips an ambiguous `||` alternative.
</Note>

#### `setNetwork`

```ts
setNetwork(state: 'online' | 'offline'): Promise<void>;
```

```ts
await device.setNetwork('offline');
await device.setNetwork('online');
```

- It switches an Android device's Wi-Fi. Cellular data stays on, so an
  emulator hands the app over to its cellular link;
  [`setAirplaneMode(true)`](#setairplanemode) cuts both.
- On iOS, `online` sends nothing, so a cleanup hook shared with Android
  passes.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | `offline` on iOS. |

#### `setAirplaneMode`

```ts
setAirplaneMode(enabled: boolean): Promise<void>;
```

```ts
await device.setAirplaneMode(true);
```

- It switches Wi-Fi and cellular together, on Android 11 or newer.
- On iOS, `false` sends nothing.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | `true` on iOS. |

#### `setPermission`

```ts
setPermission(permission: DevicePermission, state: PermissionState): Promise<void>;
```

```ts
await device.setPermission('location', 'deny');
await app.open();
```

- It sets one permission for the pinned app, which need not be running.
- A change terminates a running app on iOS, and a revoke one on Android, so
  call it before the `app.open()` a test starts with.

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | A permission name outside `DevicePermission` (naming the nearest one when it is a likely typo), or a state other than `grant`, `deny`, or `reset`. Fails before any device command. |

#### `setLocation`

```ts
setLocation(coordinates: { latitude: number; longitude: number }): Promise<void>;
```

```ts
await device.setLocation({ latitude: 52.23, longitude: 21.01 });
```

On Android it switches location services on first.

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | A latitude outside -90 to 90, a longitude outside -180 to 180, or either one not a finite number. Fails before any device command. |

#### `clearLocation`

```ts
clearLocation(): Promise<void>;
```

```ts
await device.clearLocation();
```

On Android, location services stay off until the next `setLocation`.

#### `setAppearance`

```ts
setAppearance(mode: 'light' | 'dark'): Promise<void>;
```

```ts
await device.setAppearance('dark');
```

#### `setOrientation`

```ts
setOrientation(orientation: DeviceOrientation): Promise<void>;
```

```ts
await device.setOrientation('landscape-left');
```

- `'portrait'`, `'portrait-upside-down'`, `'landscape-left'`, or
  `'landscape-right'`.

#### `fold`

```ts
fold(pose: FoldPose): Promise<void>;
```

```ts
await device.fold('half-open');
```

- It works on a foldable simulator or emulator. `closed` lights the outer
  display; `half-open` and `open` light the inner one.
- On the iPhone Duo it resolves typically 10 to 16 seconds later, and
  `half-open` is a 130° book.
- On a foldable Android emulator it resolves within a few seconds, and
  `half-open` is the profile's own angle (90° on the Pixel folds). A fold to
  the cover display dismisses the lock screen it raises.
- The app window changes size, so the next observation reads a new screen.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | The device has no hinge. |

#### `setBiometrics`

```ts
setBiometrics(sensor: BiometricSensor, result: 'match' | 'nonmatch'): Promise<void>;
```

```ts
await device.setBiometrics('faceid', 'nonmatch');
```

- It simulates one biometric attempt on the open app.
- `faceid` and `touchid` work on an iOS simulator. `fingerprint` works on an
  Android emulator and on a phone that exposes `cmd fingerprint`.
- An Android app's prompt reads the touch only once the device has a screen
  lock and an enrolled fingerprint, which
  [`enrollBiometrics`](#enrollbiometrics) cannot set up.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | `fingerprint` on iOS, `faceid` or `touchid` on Android or on a physical iOS device, or `fingerprint` on an Android phone without `cmd fingerprint`. |

#### `enrollBiometrics`

```ts
enrollBiometrics(sensor: 'faceid' | 'touchid', enrolled: boolean): Promise<void>;
```

```ts
await device.enrollBiometrics('touchid', true);
```

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | Any call on Android or a physical iOS device. |

#### `installApp`

```ts
installApp(appPath?: string, options?: InstallAppOptions): Promise<InstalledApp>;
```

```ts
await device.installApp(); // the target's app.appPath
const { app } = await device.installApp('./build/MyApp.app', { reinstall: true });
await device.openApp(app);
```

- The build is an iOS `.app` bundle or an Android `.apk`.
- The engine installs nothing on its own, so call it once per device in a
  fixture or test.
- `reinstall: true` removes the app first, so the build starts with no data;
  a plain install replaces the binary and keeps its data.
- `app` in the options is the build's bundle id or package, and defaults to
  the pinned app. `reinstall` needs one.
- A remote daemon receives an upload when the build exists on the runner.
  Otherwise it checks the absolute path on its own filesystem and reports
  the install error if the build is missing.
- The resolved id is the bundle id or package agent-device read from the
  build, or the `app` passed in.

| Throws | When |
| --- | --- |
| `INVALID_STATE` | No path was passed and the target has no `app.appPath`; or `reinstall: true` with no `app` passed and no app pinned (no `app.bundleId`, build not installed yet). |
| `INVALID_ARGUMENT` | The explicit path is empty or blank, or a required runner-side build is missing. Relative paths resolve against the project root. Fails before any device command. |
| `ENGINE_FAILURE` | agent-device reported no id and no `app` was passed. See [Troubleshooting](https://e2e.com/docs/mobile#troubleshooting). |

#### `uninstallApp`

```ts
uninstallApp(app?: string): Promise<boolean>;
```

```ts
expect(await device.uninstallApp()).toBe(true);
expect(await device.isAppInstalled('com.example.app')).toBe(false);
await device.installApp(); // a fresh install, for a first-launch flow
```

- `app` is a bundle id or package; without one, the pinned app is removed.
- It resolves to whether the app was installed, so removing an app that is
  not there passes.
- Without `app.bundleId` on the target, removing the build `installApp`
  pinned unpins it: `app.open()` then needs another install.
- Removing the app on screen leaves the device on its home screen, and
  locators resolved before point at nothing. Install it again with
  `device.installApp()`, then `device.openApp(app)`, to keep testing it.
- The device keeps the removal for the tests that run on it later. Reinstall
  the app before the test ends, in a `finally` block, or any later test on
  that device that opens it fails at `app.open()`.

| Throws | When |
| --- | --- |
| `APP_NOT_OPEN` | No `app` was passed and none is pinned (no `app.bundleId`, build not installed yet). |

#### `isAppInstalled`

```ts
isAppInstalled(app?: string): Promise<boolean>;
```

```ts
expect(await device.isAppInstalled('com.example.companion')).toBe(true);
```

- `app` is a bundle id or package; without one, the pinned app is checked.
- System apps count. On Android, only launchable apps do.
- The app's display name, as the device lists it, matches too.

| Throws | When |
| --- | --- |
| `APP_NOT_OPEN` | No `app` was passed and none is pinned. |

#### `openApp`

```ts
openApp(app: string, options?: OpenAppOptions): Promise<void>;
```

```ts
await device.openApp('Settings');
await device.openApp('com.example.app', { relaunch: true, permissions: { camera: 'grant' } });
await device.openApp('com.example.app', { relaunch: true, launchArguments: { AppleLocale: 'fr_FR' } });
```

- `app` is a bundle id, package, or display name.
- `relaunch: true` terminates the app first, so it starts fresh. Without it,
  a running app is brought forward as it is.
- `launchArguments` and `permissions` apply to this launch alone. On a
  relaunch of the pinned app they replace the target's `app.launchArguments`
  and `app.permissions`, which apply otherwise. An open without `relaunch`
  gets neither of the target's, only what the call passes.

| Throws | When |
| --- | --- |
| `POLICY_DENIED` | A `file:`, `data:`, `javascript:`, `view-source:`, `blob:`, or `filesystem:` link. |
| `INVALID_ARGUMENT` | Any other link, with a message pointing at `openLink`; an invalid permission name or state; or `launchArguments` outside the declared shape, or one Android cannot carry (see [Launch arguments and permissions](#launch-arguments-and-permissions)). |

#### `openLink`

```ts
openLink(url: string, options?: { app?: string }): Promise<void>;
```

```ts
await device.openLink('myapp://orders/42');
await expect(screen.getByText('Order #42')).toBeVisible();
```

- It opens a deep link (`myapp://orders/42`) or a web link (`https://...`)
  into `app`, by default the pinned app, which the session observes
  afterwards.
- iOS launches the app for a web link and then opens the URL. A web link the
  app does not claim goes to Safari, and the next observation brings the app
  back. Android starts the link on that package.
- Without an app, Android routes the link to a verified app link owner or
  the browser, and the session follows the package that took it.
- The report shows the link without its userinfo (`user:password@` or `token@`),
  query, or fragment, where a login or a magic link's token rides. A string
  that does not parse shows as `<link>`, never as typed.

| Throws | When |
| --- | --- |
| `POLICY_DENIED` | A `file:`, `data:`, `javascript:`, `view-source:`, `blob:`, or `filesystem:` link. |
| `INVALID_ARGUMENT` | No app on iOS. |
| `INVALID_ARGUMENT` | A string that does not parse as an absolute URL. The message names no part of the input, which may carry a magic-link token in its query, path, or userinfo. |

#### `closeApp`

```ts
closeApp(): Promise<void>;
```

```ts
await device.closeApp();
await device.openApp('com.example.app'); // launches fresh, on its first screen
```

- It terminates the session's app and ends the session.
- Until the next `openApp`, the screen is unobservable: a screen query and
  [`foregroundApp`](#foregroundapp) fail with `APP_NOT_OPEN`.

#### `clearKeychain`

```ts
clearKeychain(): Promise<void>;
```

```ts
await device.clearKeychain();
await app.open(); // see it signed out
```

It resets the keychain of an iOS simulator, every app's: what
`app.clearState()` leaves behind, such as a session token or a Firebase
sign-in.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | On Android, before any device command. |

#### `foregroundApp`

```ts
foregroundApp(): Promise<ForegroundApp>;
```

```ts
const { name, bundleId } = await device.foregroundApp();
```

iOS answers from the session, not the device, so it names the app the session
opened even after `home()`. Android reads the device's foreground activity.

| Throws | When |
| --- | --- |
| `APP_NOT_OPEN` | `closeApp` ended the session. |

#### `viewport`

```ts
viewport(): Promise<ViewportSize>;
```

Returns `{ width, height }` in the coordinate space of screen taps, read fresh on each call. `ViewportSize` is exported from `@e2e-dev/mobile`.

```ts
const { width, height } = await device.viewport();
await screen.tapAt({ x: width / 2, y: height / 2 });
```

| Throws | When |
| --- | --- |
| `ENGINE_FAILURE` | The device's screen size cannot be determined. |

#### `home`

```ts
home(): Promise<void>;
```

```ts
await device.home();
```

#### `back`

```ts
back(): Promise<void>;
```

```ts
await device.back();
```

#### `pressRemote`

```ts
pressRemote(key: RemoteKey): Promise<void>;
```

```ts
await device.pressRemote('down');
await device.pressRemote('select');
await device.pressRemote('play-pause');
```

Most Android TV remotes carry one Play button that toggles: that is
`play-pause`. `play` is the dedicated Play key.

[`RemoteKey`](#device-fixture) lists the buttons. On an Apple TV, `back` and
`menu` are the same Siri Remote button.

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | `key` is not a `RemoteKey` name. |
| `UNSUPPORTED_CAPABILITY` | The device is not an Android TV or an Apple TV, or the button is one an Apple TV does not take: it takes `up`, `down`, `left`, `right`, `select`, `back`, `menu`, and `home`. Android TV takes every button. |

#### `pressButton`

```ts
pressButton(button: HardwareButton): Promise<void>;
```

```ts
await device.pressButton('volume-up');
await expect(screen.getByRole('slider', { name: 'Media' })).toBeVisible();
```

It resolves once the press is sent, with no volume level or screen state, so
assert on what the screen shows next. An Android emulator or phone takes all
three buttons, and a physical iPhone or iPad the volume buttons.

On Android a volume press opens the system volume panel over the app, so
the next read shows its sliders until the panel hides itself a few seconds
later. `power` turns the screen off, and the screen cannot be read until it
is on again: a read or an action times out. Two quick `power` presses can
trigger the phone's double-press shortcut, which opens the camera on a stock
emulator, instead of waking the app.
To lock the screen and wait until the device reports it locked, use
[`lock`](#lock), then [`unlock`](#unlock).

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | `button` is not one of the three names. Nothing is sent to the device. |
| `UNSUPPORTED_CAPABILITY` | The device cannot press that button: an iOS simulator, an Android TV, `power` on an iPhone or iPad, or a hosted device whose WebDriver backend does not expose the button. |

#### `shake`

```ts
shake(): Promise<void>;
```

```ts
await device.shake();
await expect(screen.getByText('Report a problem')).toBeVisible();
```

It resolves once the shake is sent. An app reads the shake the way it reads one on a real device: a React Native dev build opens its dev menu, and an app with a shake handler runs it.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | The device is not one agent-device can shake: a physical device, a TV or watch target, or a device a provider drives through its own backend, such as a WebDriver session or a provider's own iOS simulator. |
| `ENGINE_FAILURE` | The Android emulator's console refused the shake, as an image with no accelerometer does. |

#### `lock`

```ts
lock(): Promise<void>;
```

```ts
try {
  await device.lock();
} finally {
  await device.unlock();
}
await expect(screen.getByText('Welcome back')).toBeVisible();
```

- It resolves once the device reports the screen locked. A screen that is
  already locked stays locked.
- A lock that asks for a PIN, pattern, password, or passcode is locked too,
  but `unlock()` refuses it, so the device stays locked until someone unlocks
  it by hand: use Swipe on Android and no passcode on iOS.

To lock the screen for a time, as Appium's `lock(seconds)` does, wait between `lock()` and `unlock()`.

On an iPhone simulator with an always-on display, such as the iPhone 17 Pro, `unlock()` can leave the display off while the device reports it unlocked. Taps and screen reads still work, but a screenshot shows the last frame before the display went off, and on iOS 26.5 every later `fill` on that simulator fails its read-back for the rest of the run. An iPhone without an always-on display, such as the iPhone 16e, is not affected.

The engine never unlocks the device for you. A test that fails while the screen is locked leaves it locked for the next test on that device, so unlock in a `finally` block or in `afterEach`. Both methods run on the app session: after [`closeApp`](#closeapp) they fail with `APP_NOT_OPEN` until `openApp` opens an app, so unlock before you close the app.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | The device is not one agent-device can lock: a physical iPhone or iPad, an Android TV or Apple TV, or a device a provider drives through its own backend with no lock command. |
| `UNSUPPORTED_CAPABILITY` | The Android device's screen lock is set to None, on Android 16 or newer. The message says so; set any other screen lock, such as Swipe, in Settings > Security. |
| `ACTION_FAILED` | `actionTimeout` expired before the device reported the screen locked. On an Android device with a PIN, pattern, or password and "Power button instantly locks" off, the keyguard waits for "Lock after screen timeout", up to one minute; raise `actionTimeout` or turn that setting on. |
| `ENGINE_FAILURE` | The device did not report the screen locked: on Android within 5 seconds, plus the "Lock after screen timeout" delay up to one minute. On Android 11 to 15 with the screen lock set to None, this is the failure, with the message `still reports the keyguard hidden`, and the display is left off. |
| `ENGINE_FAILURE` | Android 10 or older, on an unlocked screen: agent-device cannot read the lock type (`Unable to read the screen lock type`), and no key is sent. |

#### `unlock`

```ts
unlock(): Promise<void>;
```

```ts
await device.unlock();
```

- It resolves once the device reports the screen unlocked. Nothing brings an
  app to the front: check the screen you expect next.
- A display that is off turns on even when the screen is not locked. An
  unlocked screen that is on stays as it is. [`lock`](#lock) has the
  exception for an iPhone simulator with an always-on display.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | The lock asks for a PIN, pattern, password, or passcode. The message names it; unlock the device by hand, or remove the credential. |
| `UNSUPPORTED_CAPABILITY` | The device is not one agent-device can lock: a physical iPhone or iPad, an Android TV or Apple TV, or a device a provider drives through its own backend with no lock command. An Android device whose screen lock is set to None is not refused: `unlock()` wakes it. |
| `ENGINE_FAILURE` | The device still reported the screen locked after the unlock. |
| `ENGINE_FAILURE` | Android 10 or older, on a locked screen: agent-device cannot read the lock type (`Unable to read the screen lock type`), and no key is sent. |

#### `alert`

```ts
alert(action: 'accept' | 'dismiss'): Promise<void>;
```

```ts
await device.alert('accept');
```

#### `dismissKeyboard`

```ts
dismissKeyboard(): Promise<void>;
```

```ts
await device.dismissKeyboard();
```

- Android hides the keyboard directly. iOS has no such call, so there it goes
  the way a user sends it away: a short drag that a scroll view turns into a
  dismissal, horizontal first and vertical second.
- Each drag starts at a point no control in the accessibility tree covers. A
  control the tree leaves out, such as pressable text, can still be hit.
- When it fails, the message names the alternatives: the app's own Done or
  close control, or pressing Enter on the field.

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | Every point above the keyboard (in a scroll view, when the screen has one) is on a control, agent-device reports the keyboard up with no frame and no keyboard element on screen, or the keyboard outlives both drags. |

#### `isKeyboardShown`

```ts
isKeyboardShown(): Promise<boolean>;
```

```ts
await screen.getByTestId('email-input').fill('jane@example.com');
await device.dismissKeyboard();
await expect.poll(() => device.isKeyboardShown()).toBe(false);
```

- It reads the screen as it is now, so right after an action that opens or
  closes the keyboard, poll it with `expect.poll`.
- A poll reads again after any error. An `ENGINE_FAILURE` clears once the
  keyboard settles; an `UNSUPPORTED_CAPABILITY` that lasts, as with a
  provider that cannot read the keyboard at all, makes the poll wait out its
  whole timeout before it fails.

| Throws | When |
| --- | --- |
| `ENGINE_FAILURE` | The capture cannot answer yet, as while the keyboard slides in or out or the tree is still incomplete. Read it again; `expect.poll` does. |
| `UNSUPPORTED_CAPABILITY` | The tree shows no keyboard or key drawn on screen (the suggestion strip alone is not one), and agent-device did not prove the keyboard absent: for example an Android capture without the input method's window, a WebDriver provider with no keyboard probe, or no keyboard reading at all. The message names the reason. |

#### `clipboard`

```ts
clipboard(): Promise<string>;
```

```ts
const copied = await device.clipboard();
```

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | The Android build has no shell command for the clipboard service. |

#### `setClipboard`

```ts
setClipboard(text: string): Promise<void>;
```

```ts
await device.setClipboard('SAVE20');
```

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | The Android build has no shell command for the clipboard service. |

### Agent tools

`mobileTools(...engines)` from `@e2e-dev/mobile/tools` adds device tools to
an agent's `tools`.

```ts
tools: mobileTools(iphone, pixel),
```

- It takes at least one engine. Pass all device engines in one call; the
  tools use the current attempt's engine.

| Tool | Replay | Purpose |
| --- | --- | --- |
| `open_app` | gap | Bring an app to the foreground by id, optionally relaunched. Without an id it returns to the target's app. A link is refused, as it is for `device.openApp`. |
| `swipe` | gap | Free-form swipe between two points in logical pixels. |
| `alert` | gap | Accept or dismiss a system alert; prefer a listed button, whose tap replays. |

`tvTools(...engines)` adds the TV remote for engines that drive an Android TV
or an Apple TV. It is a pack of its own, so a config with no TV offers no
remote.

```ts
tools: { ...mobileTools(tv), ...tvTools(tv) },
```

Tools are offered by platform. When a phone target shares the TV's platform,
put `tvTools` on a [named agent](https://e2e.com/docs/reference/config#agents) and select it on
the TV tests.

| Tool | Replay | Purpose |
| --- | --- | --- |
| `tv_remote` | gap | Press a [remote button](#pressremote) by `key`, up to 20 `times` in one call. |

`foldTools(...engines)` adds the hinge for engines that drive a foldable: the
iPhone Duo simulator or a foldable Android emulator. With it in the agent's
`tools`, `agent.act`, `e2e explore`, and the MCP server's `call` can fold the
device.

```ts
tools: { ...mobileTools(iphoneDuo), ...foldTools(iphoneDuo) },
```

- Tools are offered by platform, as with `tvTools`. When a device without a
  hinge shares the foldable's platform, put `foldTools` on a
  [named agent](https://e2e.com/docs/reference/config#agents) and select it on the foldable
  tests.
- The engine never resets the pose, so a pose the agent leaves carries over
  to the next test. Fold back in `afterEach`, as for
  [`device.fold`](#fold).

| Tool | Replay | Purpose |
| --- | --- | --- |
| `fold` | gap | Put the device in a hinge [`pose`](#fold): `closed`, `half-open`, or `open`. A device without a hinge fails with `UNSUPPORTED_CAPABILITY`. |

| Throws | When |
| --- | --- |
| `INVALID_STATE` | An engine that `mobile()` did not return. In the config this fails the load as `CONFIG_LOAD_FAILED`, whose message includes this one. |

A tool that fails during a built-in agent step returns
`Tool "<name>" failed: <message>` to the model as the call's result; the step
goes on. `open_app` fails with `INVALID_STATE` when it names no app, the
target has no `app.bundleId`, and nothing has installed its `app.appPath`
build yet (no `device.installApp()`, no device provider install); with
`INVALID_ARGUMENT` when it names an app that is not installed or a link; and
with `POLICY_DENIED` for a link with a forbidden scheme. Any tool fails with
`INVALID_STATE` when no device attempt is running, or when several device
attempts are running in one worker.

The grammar verbs need no tool pack. The engine's declared actions give the
agent:

- `tap`, `double_tap`, `long_press`, `hover`, `type`, `press`, `check`,
  `scroll`, `drag`, `scroll_to` by `text` (paging the list until a row
  reading it is drawn), `back`, and `dismiss_keyboard`.
- The pixel tools `screenshot`, `tap_at`, `hover_at` (on a listed control
  only), `drag_at` (between two different listed controls only), `type_at`, and
  `press_at`. Point actions can tap controls absent from the accessibility
  tree.
- `type_secret`, which fills only a secret the step declares.

There is no `right_click`, `select`, `scroll_to` by node id, `upload`, or
`navigate` on a device, and `select_at` is not offered.

<Note>
Pixels whose masking the engine cannot prove are withheld as `MASKING_UNPROVEN`. An accessibility
capture failure still stops the observation.
</Note>

#### `unstable_deviceSession`

`unstable_deviceSession(...engines)` from `@e2e-dev/mobile/tools` gives a custom tool
the running attempt's `DeviceSession`, the same object a test reads from
[`device.unstable_raw`](#unstable_raw), for capabilities e2e does not wrap
yet. Its `client` is typed as `DeviceSessionClient`.
The following example assumes the current driver supports `settings.update`.

```ts

const mobileData = defineTool(
  tool({
    description: 'Turn cellular mobile data on or off. Wi-Fi is not affected.',
    inputSchema: z.object({ on: z.boolean() }),
    execute: async ({ on }) => {
      const { client, selection } = unstable_deviceSession(iphone, pixel);
      await client.settings.update({ ...selection, setting: 'mobile-data', state: on ? 'on' : 'off' });
      return on ? 'mobile data is on' : 'mobile data is off';
    },
  }),
  { mutates: true, platforms: ['android'] },
);

tools: { ...mobileTools(iphone, pixel), mobileData },
```

- Pass every device engine the config declares, as with `mobileTools`.
  Outside an attempt it throws `INVALID_STATE`.
- Spread `selection` into a call so it reaches the worker's device even
  before the session has an app open, as the engine's own calls do.
- Client calls are not steps: the report shows the tool call, not what the
  client did, and a cache replay runs a `mutates: true` tool live.
- Client calls skip e2e's guards, as with `unstable_raw`. A snapshot or
  screenshot a tool returns is not redacted or masked, even after a secret
  fill, nothing waits for the screen to settle after a call, and a tool
  whose calls change the device must declare `mutates: true`.
- Like `unstable_raw`, it can change in any release.

## Roles

`getByRole` on a device matches the role each element type maps to. A type
not listed keeps its own name in lower kebab case (`picker-wheel`), so it
matches a `getByRole` role only when that name is one (`group`, `table`).
A node the platform reports editable is a `textbox`, unless it already maps
to `combobox`.

| Role | iOS | Android |
| --- | --- | --- |
| `button` | `Button` | `Button`, `ImageButton`, `MaterialButton` |
| `link` | `Link` | React Native's `role="link"`, see below |
| `textbox` | `TextField`, `SearchField`, `TextView`, `SecureTextField` | `EditText`, `AutoCompleteTextView`, `TextInputEditText`, `SearchView` |
| `combobox` | | `Spinner` |
| `switch` | `Switch`, `Toggle` | `Switch`, `SwitchCompat`, `SwitchMaterial`, `ToggleButton` |
| `checkbox` | `CheckBox` | `CheckBox`, `MaterialCheckBox` |
| `radio` | `RadioButton` | `RadioButton` |
| `radiogroup` | `RadioGroup` | `RadioGroup` |
| `slider` | `Slider` | `SeekBar`, `Slider` |
| `spinbutton` | `Stepper` | `NumberPicker` |
| `progressbar` | `ProgressIndicator` | `ProgressBar` |
| `status` | `ActivityIndicator` | |
| `image` | `Image`, `ImageView` | `ImageView` |
| `heading` | `Heading`, `Header` | A view flagged as a heading |
| `list` | | `RecyclerView`, `ListView`, `AbsListView` (React Native's `FlatList`), `GridView` |
| `listitem` | `Cell`, `ListItem`, `TableCell`, `CollectionCell` | |
| `row` | `TableRow` | |
| `tablist` | `TabBar`, `TabGroup`, `SegmentedControl` | `TabLayout`, `TabWidget`, `BottomNavigationView` |
| `tab` | `Tab`, `TabBarItem`, `TabBarButton`, and a `Button` inside a `TabBar` or `SegmentedControl`, through any `Other` wrappers between them | `TabLayout$TabView`, `BottomNavigationItemView` |
| `menu` | `Menu` | |
| `menubar` | `MenuBar` | |
| `menuitem` | `MenuItem`, `MenuBarItem`, `MenuButton` | |
| `toolbar` | `Toolbar` | `Toolbar` |
| `alert` | `Alert` | |
| `dialog` | `Dialog`, `Sheet`, `ActionSheet` | |
| `navigation` | `NavigationBar` | |
| `group` | | `ScrollView`, `ViewGroup`, `View`, `ComposeView`, `ViewFactoryHolder`, `CardView`, and any other `*Layout` |

React Native writes a role the platform has no type for into the
accessibility value on iOS (`checkbox, unchecked`) and into the role
description on Android (`Tab List`). A node with one of these descriptions
takes the role in place of its type's: `alert`, `checkbox`, `combo box`,
`menu`, `menu bar`, `menu item`, `progress bar`, `radio button`,
`radio group`, `scroll bar`, `spin button`, `switch`, `tab`, `tab list`,
`timer`, and `tool bar`. The `scrollbar` and `timer` roles that `scroll bar`
and `timer` give are not `getByRole` roles.
On iOS only an `Other` carries one, and the state words after the role set
`checked` and `expanded`; only what follows them is the node's value.

On Android, React Native's `role="link"`, which expo-router's `Link` sets, is
a `link`, and a `Text` link matches once. Before React Native 0.84, Android
names a `Text` link by its text, even when an `accessibilityLabel` gives it a
different name on iOS.

React Native writes the Android description in the device's language, so
on a device whose word for it isn't one of these, such as French `Lien` for
`Link`, the node keeps its type's role.

`StaticText` and `Text` on iOS and `TextView` on Android are `text`, and an
Android `WebView` is `document`. Neither is a `getByRole` role: find text
with `getByText`.

## Visibility

A device node is hidden when the platform reports it off screen, or when the
soft keyboard covers its centre. So `toBeVisible()`, `scrollUntilVisible`,
and `getByRole` treat a field under the keyboard like a field scrolled out
of view. The keyboard's own keys, suggestion bar, and dock stay visible, and
so does the focused field.

- A container whose centre is under the keyboard stays visible while one of
  its children shows above it.
- A node under another view, such as a footer the keyboard lifts, is not
  hidden. A tap on it fails with `ACTION_FAILED` when agent-device finds the
  cover, and the message names the cover. A tap under the keyboard fails the
  same way. Dismiss the cover, or scroll the target clear of it.

## Video recording cleanup

If a recording fails to stop, cleanup retries the stop. For a device
provider's recording the retries come at attempt end, before another attempt
on that worker, and during worker disposal. The next attempt starts only
after the provider confirms the stop; a failed or cancelled stop wait
prevents that attempt from starting.

A recording recovered by a retry is not added to the report: its file can
stay in the original attempt's video directory, and a returned URL is
dropped. A required video whose first stop failed stays a cleanup failure.

Recording handles do not survive worker exit. Providers must clean up any
remaining external recordings when releasing a lease: closing an
agent-device session cannot guarantee that a cloud recording stops, and a
failed stop callback does not confirm that the recording stopped.

## Replay cache on a device

The replay cache anchors on the [`location`](#capabilities) a device reports,
`<bundle id> / <screen title>`. A step recorded on
`com.apple.Preferences / General` replays only when Settings is on General
again.

```ts
await app.open();
await screen.getByText('General').tap();
await agent.act('Open About and read the iOS version');
```

- A mutating project-tool call such as `open_app` ends a replay.
- Declare `app.bundleId` and call `app.open()` first, so steps start on the
  same screen.
- Switch apps through the `device` fixture between steps rather than inside
  one.
- A step recorded after [`device.openLink`](#openlink) replays when the link
  lands on the same screen again.

## Types

### Engine options

Each `MobileOptions` member is declared in its
[Engine](#engine) entry.

```ts
export type PermissionState = 'grant' | 'deny' | 'reset';

export type LaunchPermissions = Readonly<Partial<Record<DevicePermission, PermissionState>>> | 'all';
```

### Device fixture

Each `Device` member is declared in its [Device](#device) entry.

```ts
export interface OpenAppOptions {
  readonly relaunch?: boolean;
  readonly launchArguments?: LaunchArguments;
  readonly permissions?: LaunchPermissions;
}

export type DevicePermission =
  | 'camera'
  | 'microphone'
  | 'photos'
  | 'contacts'
  | 'notifications'
  | 'calendar'
  | 'location'
  | 'reminders'
  | 'motion'
  | 'siri'
  | 'media-library';

export type RemoteKey =
  | 'up'
  | 'down'
  | 'left'
  | 'right'
  | 'select'
  | 'back'
  | 'menu'
  | 'home'
  | 'play'
  | 'pause'
  | 'play-pause'
  | 'stop'
  | 'rewind'
  | 'fast-forward'
  | 'next'
  | 'previous';

export type HardwareButton = 'volume-up' | 'volume-down' | 'power';

export type DeviceOrientation = 'portrait' | 'portrait-upside-down' | 'landscape-left' | 'landscape-right';

export type FoldPose = 'closed' | 'half-open' | 'open';

export interface InstallAppOptions {
  readonly app?: string;
  readonly reinstall?: boolean;
}

export interface InstalledApp {
  readonly app: string;
  readonly bundleId?: string;
}

export interface ForegroundApp {
  readonly name: string;
  readonly bundleId?: string;
}

export type BiometricSensor = 'faceid' | 'touchid' | 'fingerprint';

export interface DeviceSession {
  readonly platform: MobilePlatform;
  readonly session: string;
  readonly deviceId: string;
  readonly deviceName: string;
  readonly selection: DeviceSelection;
  readonly client: DeviceSessionClient;
}

export interface DeviceSelection {
  readonly platform: MobilePlatform;
  readonly device?: string;
  readonly udid?: string;
  readonly serial?: string;
}
```

| Field | Description |
| --- | --- |
| `DeviceSession.session` | `e2e-<target>-<worker slot>`, `e2e-<target>-<hostId>-<worker slot>` for a `launch()` host, or `<session>-<worker slot>` with the [`session`](#session) option. |
| `DeviceSession.deviceId` | A simulator UDID or an Android serial. |
| `DeviceSession.selection` | Spread it into a call that can run before `app.open()`. |
| `DeviceSelection` | The platform, then one of `device` (a name), `udid` (a simulator UDID), or `serial` (an Android serial). |

### Exported types

`MobileEngine`, `MobileOptions`, `MobilePlatform`, `DevicePermission`, `LaunchPermissions`,
`PermissionState`, `DeviceClientConfig`, `DeviceConnection`, `DeviceDaemon`,
`DeviceProvider`, `DeviceLease`, `DeviceReleaseContext`, `DeviceRequest`,
`Device`, `DeviceSession`, `DeviceSessionClient`, `DeviceSelection`, `DeviceOrientation`, `BiometricSensor`, `ForegroundApp`,
`FoldPose`, `InstallAppOptions`, `InstalledApp`, and `OpenAppOptions` are exported from
`@e2e-dev/mobile`. The runtime exports are `mobile`, and `test`, `describe`,
`beforeEach`, `afterEach`, `beforeAll`, and `afterAll`, typed with the `device`
fixture. A device keeps its state between tests, so `device`, `app`, and
`screen` are [worker fixtures](https://e2e.com/docs/reference/test#worker-fixtures), and
`beforeAll` and `afterAll` get them. `mobileTools`, `tvTools`, and `foldTools`
come from `@e2e-dev/mobile/tools`.

## Related

The [Mobile](https://e2e.com/docs/mobile) guide covers setup, hosted devices, and troubleshooting.
The portable lifecycle methods are on [`app`](https://e2e.com/docs/reference/app).
