Mobile
Set up a simulator, emulator, or connected phone as a target, write a device test, and know what differs from the web.
@e2e-dev/mobile runs tests on iOS simulators, Android emulators, and
phones connected to your machine. It is built on
agent-device. Tests use the
same agent, screen, and expect APIs as browser tests.
Set up
Install Xcode with an iOS simulator runtime, or the Android SDK with an
emulator. Then follow the Quickstart and choose Mobile
(iOS/Android). The wizard selects iOS on macOS and Android elsewhere, and
targets the Settings app with one worker, so a test runs before you point it
at your app. Device boot happens before test timing starts and doesn’t count
toward launchTimeout. See the example projects for
finished setups.
Check your setup:
npx e2e doctorpnpm exec e2e doctorbunx e2e doctorIt checks agent-device, Xcode or the Android SDK, each device the target
names, and the appPath build. Without appPath, it checks that the
bundleId is installed when one device is booted. See
e2e doctor.
Point at your app
Set the target’s app.bundleId to your app’s bundle id or package name.
app.open(), app.restart(), and app.clearState() launch that app. Add
appPath to name a build, an .app bundle for iOS or an .apk for
Android:
{
name: 'ios',
engine: mobile({ platform: 'ios' }),
app: {
bundleId: 'com.example.app',
appPath: './build/MyApp.app', // the iOS .app bundle
},
}A device target needs bundleId, appPath, or both. The engine installs
nothing on its own. Call device.installApp() once per device, for example
in a fixture every test takes. With no path, it installs app.appPath.
Without bundleId, app.open() launches the app the build installed.
To run the suite in CI, see Mobile jobs.
Launch arguments and permissions
app.launchArguments and app.permissions apply to every fresh launch.
app: {
bundleId: 'com.example.app',
launchArguments: ['-e2e', 'YES'],
permissions: { camera: 'grant', notifications: 'deny', location: 'reset' },
},- Launch arguments are the process arguments on iOS and
am startarguments on Android. - Permissions are set before the launch, so no system prompt appears.
app.clearState()resets them with the data, then sets them again. denyon iOS tells the app no without a prompt. On Android it revokes the permission, so the OS asks again.- The warm-up before the run passes neither, so start each test with
app.open(). - Arguments that select a build mode change what the app is. Give each mode
its own
app.identityso its recordings stay apart.
To launch one test with its own, use device.openApp. Each option it passes
replaces the target’s whole value: permissions: { camera: 'deny' } drops
the target’s other permissions. On a relaunch of the target’s app, options
it doesn’t pass keep the target’s values:
await device.openApp('com.example.app', { relaunch: true, permissions: { camera: 'deny' } });Run the app in another language
On iOS, launch arguments set the app’s language and region for that launch. The device keeps its own language. Add one target per language:
{
name: 'ios-fr',
engine: mobile({ platform: 'ios' }),
app: {
bundleId: 'com.example.app',
launchArguments: ['-AppleLanguages', '(fr)', '-AppleLocale', 'fr_FR'],
},
}- The app must ship the language. If it doesn’t, iOS shows its development language.
- Android has no launch argument for the language. On a hosted device, set
languageandlocaleonbrowserstack()ortestmu(). On a local device, set the device’s language before the run.
Expo development builds
A development build (expo-dev-client) opens on the dev launcher and loads
its JavaScript from a dev server. On an iOS simulator, these launch
arguments open the server directly and turn off the dev menu, its
onboarding sheet, and its floating button. app.command starts the server:
import type { E2EConfig } from 'e2e';
import { mobile } from '@e2e-dev/mobile';
export default {
targets: [
{
engine: mobile({ platform: 'ios' }),
app: {
bundleId: 'com.example.app',
launchArguments: [
'--initialUrl', 'http://localhost:8081',
'-EXDevMenuShowsAtLaunch', 'NO',
'-EXDevMenuIsOnboardingFinished', 'YES',
'-EXDevMenuShowFloatingActionButton', 'NO',
],
command: { executable: 'npx', args: ['expo', 'start', '--port', '8081'] },
readyUrl: 'http://localhost:8081/status',
},
},
],
} satisfies E2EConfig;- The warm-up leaves the app on the dev launcher. Start each test with
app.open(). - The first launch waits for the dev server to bundle the app. Give the test’s first check a longer timeout.
- On Android, expo-dev-launcher doesn’t read
--initialUrl. Open the server withdevice.openLinkand the build’sexp+<slug>://expo-development-client/?url=<encoded server URL>link.
Write a device test
screen maps native controls to common roles such as button, textbox,
listitem, and switch. Use getByTestId for native element identifiers.
import { test } from '@e2e-dev/mobile';
import { expect } from 'e2e';
test('shows the version in dark mode', async ({ agent, app, device, screen }) => {
await device.setAppearance('dark');
await app.open();
await agent.act('go to General, then About');
await expect(screen.getByRole('button', /^iOS Version/)).toBeVisible();
await expect(device.locator('role=navigation-bar id=About')).toBeVisible();
});Between tests, the app stays where the last test left it. Devices don’t
support selectOption, setInputFiles, scrollIntoView, secondaryTap,
or modifiers on tap and doubleTap. Use taps and swipes on native
controls.
Test ids by framework
getByTestId reads the accessibility identifier on iOS and the resource id
on Android. Each UI framework sets them its own way:
- On Android, a native
android:idand a .NET MAUIAutomationIdread as<package>:id/<id>.getByTestId('greet')finds them without the app’s package, as on iOS. Framework ids such asandroid:id/contentmatch only in full. - On Android, Compose hides test tags until a root composable sets
Modifier.semantics { testTagsAsResourceId = true }. Without it,getByTestIdfinds nothing. iOS reads a Compose Multiplatform tag as is, so a shared screen sets the flag in its Android activity. - In SwiftUI, an
.accessibilityIdentifier()on a container such as aVStackreplaces the ids of every element inside it.getByTestIdthen fails withLOCATOR_AMBIGUOUSon the container’s id and finds nothing for the children’s ids. Put.accessibilityElement(children: .contain)before the identifier to keep both. - In Flutter, wrap a button’s
SemanticsinMergeSemanticsso the id and the button role land on one node. - In NativeScript,
testIDandaccessibilityIdentifierset the same id:getByTestId('login-button')finds<Button text="Login" testID="login-button" />on both platforms.accessibilityLabelsets the name, not the id. On Android, NativeScript puts it before the text, so<Button text="Help" accessibilityLabel="Open help" />is namedOpen help. Help. Match it withgetByRole('button', /^Open help/).
The device fixture
device changes device settings without a model call: network,
permissions, appearance, app installs, and more. Each call is a
device.<method> step in the report. The
mobile engine reference lists every method.
device.locator takes an agent-device selector, as in the test above, for
controls that screen queries can’t name.
device.installApp also tests upgrades and fresh installs:
const { app } = await device.installApp('./build/MyApp.app', { reinstall: true });
await device.openApp(app);device.openApp takes a bundle id, package, or display name, never a link.
device.openLink opens a deep link or a web link into the pinned app, or
the app in its options, for magic-link sign-in and deep-link routes:
await device.openLink('myapp://orders/42');
await expect(screen.getByText('Order #42')).toBeVisible();device.setNetwork('offline') and device.setAirplaneMode(true) work on
Android only. An iOS simulator shares the Mac’s network, and simctl can only
change its status bar, so on iOS both fail with UNSUPPORTED_CAPABILITY.
setNetwork('online') and setAirplaneMode(false) do nothing on iOS, so a
cleanup hook that both platforms run still passes.
On Android, setNetwork('offline') turns off Wi-Fi only, and the app can
stay online over cellular. To take the app offline, use
setAirplaneMode(true). It needs Android 11 or later. The engine doesn’t
restore the network after a test, so turn it back on in afterEach, which
runs when the test fails too:
import { afterEach, test } from '@e2e-dev/mobile';
import { expect } from 'e2e';
afterEach(async ({ device }) => {
await device.setAirplaneMode(false);
});
test('shows the offline banner', { platforms: ['android'] }, async ({ app, device, screen }) => {
await app.open();
await device.setAirplaneMode(true);
await expect(screen.getByText('You are offline')).toBeVisible();
});device.clearKeychain() resets the simulator’s keychain, which
app.clearState() leaves alone, so a stored session token is gone on the
next launch. It is iOS only.
For anything device doesn’t cover, device.unstable_raw has an
agent-device client
bound to the test’s session, plus the session name, the device’s id and
name, and a selection to spread into a client call. It is unstable and
may change or go away in any release:
const { client, deviceId } = device.unstable_raw;
const { nodes } = await client.capture.snapshot({});Client calls aren’t steps: the report and trace leave them out, the agent cache doesn’t replay them, secrets passed to them aren’t redacted, and nothing waits for the screen to settle after one.
Text size and animations
device has no method for the system text size or animations, so set them
through unstable_raw. Change the text size before app.open(). A running
app can keep the old size until it launches again, so call app.restart()
after a change mid-test:
import { afterEach, test } from '@e2e-dev/mobile';
import { expect } from 'e2e';
afterEach(async ({ app, device }) => {
const { client, selection } = device.unstable_raw;
await client.settings.update({ ...selection, setting: 'text-size', state: 'large' });
});
test('the checkout button shows at the largest text size', async ({ app, device, screen }) => {
const { client, selection } = device.unstable_raw;
await client.settings.update({ ...selection, setting: 'text-size', state: 'accessibility-extra-extra-extra-large' });
await app.open();
await expect(screen.getByRole('button', 'Checkout')).toBeVisible();
});text-size works on iOS simulators and Android; large is the default on
both. setting: 'animations' with state: 'off' or 'on' is Android only
and fails on iOS. On Android it sets the window, transition, and animator
scales to 0 or 1. Both settings outlast the test, so put them back in afterEach. The next
test’s app.open() relaunches the app, so restoring the setting is enough.
Photos for a picker test
device can’t add photos to the library, so add them from the host before
app.open(). On an iOS simulator, xcrun simctl addmedia does it, and
deviceId is the simulator’s UDID. addmedia adds a copy on every call, and
an agent step can’t tell identical photos apart, so the sample leaves a marker
file in the simulator’s own data directory and adds the photo once. The marker
goes with the library when the simulator is erased:
import { execFileSync } from 'node:child_process';
import { existsSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { test, type Device } from '@e2e-dev/mobile';
import { expect } from 'e2e';
// Put a JPEG named receipt.jpg beside this test.
const receipt = resolve(import.meta.dirname, 'receipt.jpg');
function addPhotoOnce(device: Device, file: string): void {
const { deviceId } = device.unstable_raw;
const listing = execFileSync('xcrun', ['simctl', 'list', 'devices', '-j'], { encoding: 'utf8' });
const { devices } = JSON.parse(listing) as {
devices: Record<string, { udid: string; dataPath: string }[]>;
};
const simulator = Object.values(devices).flat().find((d) => d.udid === deviceId);
if (!simulator) throw new Error(`No simulator ${deviceId}`);
const marker = resolve(simulator.dataPath, 'tmp', 'receipt-photo-added');
if (existsSync(marker)) return;
execFileSync('xcrun', ['simctl', 'addmedia', deviceId, file]);
writeFileSync(marker, file);
}
test('attaches the receipt from the photo library', { platforms: ['ios'] }, async ({ app, device, screen }) => {
addPhotoOnce(device, receipt);
await app.open();
await screen.getByLabel('Choose photo').tap();
await screen.getByRole('image', /^Photo, /).first().tap();
await expect(screen.getByText(/^Receipt attached/)).toBeVisible();
});The system picker runs outside the app, but its photos are in the screen
tree, each an image named Photo, and the date it was taken. The picker
sorts by that date, newest first, which is the date in the photo’s EXIF data,
not the day you added it.
An Android emulator needs the file pushed with adb and a media scan, and
its picker is another app with its own names. This page has not been checked
on Android, so read the picker’s tree in the trace before you write that
locator.
Foldable simulators and emulators
device.fold(pose) puts the iPhone Duo simulator or a foldable Android
emulator (a Pixel Fold profile, or the generic “7.6in Foldable”) in a hinge
pose. closed lights the outer display. half-open and open light the
inner one. On the Duo the call returns when the hinge reaches the pose,
typically after 10 to 16 seconds, so keep actionTimeout at 20 seconds or
more; half-open is a 130° book there. On an Android emulator it returns
within a few seconds, once Android commits the matching device state;
half-open is the profile’s own angle (90° on the Pixel folds), and a fold
to the cover display dismisses the “Swipe up to continue” lock screen the
emulator raises. The next observation reads the app on the other display.
The engine never resets the pose, so a retry and the next test start where
the last test left it. Fold back in afterEach, which also runs when the
test fails:
import { afterEach, test } from '@e2e-dev/mobile';
afterEach(async ({ device }) => {
await device.fold('closed');
});
test('the list and the detail split across the fold', async ({ agent, app, device }) => {
await app.open();
await device.fold('half-open');
await agent.assert('the list and the detail sit on either side of the fold', { vision: true });
});Record a transition
app.startRecording() and app.stopRecording()
record one span of the screen as an .mp4. A locator’s boundingBox()
gives an element’s frame in points (physical pixels on Android).
test('the sheet slides up', { video: 'off' }, async ({ app, screen }) => {
await app.open();
await app.startRecording({ name: 'sheet' });
await screen.getByRole('button', 'Open sheet').tap();
await expect(screen.getByText('Sheet title')).toBeVisible();
const [video] = await app.stopRecording();
});Start it after app.open(). A recording started after device.closeApp()
ends the device session when it stops, so open the app again after it.
Taps show unless videoTouches is false.
Several devices
Add a target for each platform:
import type { E2EConfig } from 'e2e';
import { mobile } from '@e2e-dev/mobile';
const app = { bundleId: 'com.example.app' };
export default {
targets: [
{ name: 'iphone', engine: mobile({ platform: 'ios' }), app },
{ name: 'pixel', engine: mobile({ platform: 'android' }), app },
],
workers: 1,
} satisfies E2EConfig;Tests run on both targets. Set platforms: ['ios'] or
platforms: ['android'] on a test with platform-specific labels or
behavior.
To run files in parallel, give a device pool and set workers to at least
its size. Each device gets one worker:
mobile({ platform: 'ios', device: ['iPhone 17', 'iPhone 17 Pro'] })Without device, the engine uses booted devices, up to the worker limit.
If none are booted, it boots a shut-down one: newest OS first, then name
order. Two workers never drive the same device.
Agent tools
The agent already has basic actions such as tap, type, and scroll.
Add mobileTools for app switching, free-form swipes, and system alerts.
Pass every device engine in the config to one call:
import type { E2EConfig } from 'e2e';
import { mobile } from '@e2e-dev/mobile';
import { mobileTools } from '@e2e-dev/mobile/tools';
import { gateway } from 'ai';
const app = { bundleId: 'com.example.app' };
const iphone = mobile({ platform: 'ios' });
const pixel = mobile({ platform: 'android' });
export default {
targets: [
{ name: 'iphone', engine: iphone, app },
{ name: 'pixel', engine: pixel, app },
],
agents: { default: { model: gateway('openai/gpt-6-luna-fast'), tools: mobileTools(iphone, pixel) } },
} satisfies E2EConfig;Calls go to the engine that runs the current attempt. open_app, swipe,
and alert change device state, so the agent runs them live during a cache
replay. The mobile engine reference
describes each tool. To add your own beside them, see
Project tools.
Physical devices
agent-device drives a phone plugged into your machine as it drives a simulator, with no other engine or option. List the devices it sees:
npx agent-device devices --platform iospnpm exec agent-device devices --platform iosbunx agent-device devices --platform iosThen name the phone in device as it is listed:
mobile({ platform: 'ios', device: 'QA iPhone' })Use the name, not the id. The engine reads a device string as an id only
for a simulator UDID or an emulator-<port> serial. The first device with
a matching name wins, so give each phone a unique name. Without device, a
connected phone counts as booted and joins the pool beside booted
simulators.
Set the phone up one time:
- Pair and trust the phone, unlock it, and turn on Developer Mode.
- agent-device builds and signs its XCTest runner onto the phone. Set
AGENT_DEVICE_IOS_TEAM_IDto your team id andAGENT_DEVICE_IOS_BUNDLE_IDto a unique reverse-DNS id, such ascom.example.agentdevice.runner. The signing profile must allow that id and<id>.uitests. The first run builds the runner and takes longer. - After you change these variables, run
npx agent-device daemon stop. A running daemon keeps the environment it started with. app.appPathmust be a signed device build, not a simulator.app.
npx agent-device help physical-device covers iOS signing in detail.
- Turn on USB debugging and authorize the phone.
adb deviceslists it asdevice. app.appPathis the same.apkas on an emulator.
On a phone, localhost in the app is the phone itself. Point the app at
your machine’s network address, or on Android forward the port with
adb reverse tcp:<port> tcp:<port>.
What doesn't work on a phone
Some device controls need a simulator or emulator. On a phone, they fail with agent-device’s message.
- On an iPhone, every device setting is simulator-only:
app.permissions,device.setPermission,app.clearState(),device.setLocation,device.clearLocation,device.setAppearance, the biometric methods, anddevice.clearKeychain. So aredevice.clipboard,device.setClipboard, anddevice.fold. - For a fresh start on an iPhone, reinstall with
device.installApp(path, { reinstall: true }). Setapp.bundleIdor theappoption so agent-device knows which app to remove. - agent-device drives an older iPhone without CoreDevice when
xcrun devicectl list devicesdoesn’t list it. Taps, typing, and the screen work. Installs,--video,device.openLink, andapp.launchArgumentsfail. Install the build from Xcode and pinapp.bundleId. - On an Android phone,
device.setLocationis emulator-only.device.setBiometrics('fingerprint', ...)works only where the phone exposescmd fingerprint. --videoon an iPhone is built from screenshots at about 15 frames a second, and drops frames.
Hosted devices
Use Limrun for hosted iOS simulators and Android emulators with automatic app installation and device cleanup.
Set device to a DeviceProvider to run on devices a service hosts. Any
service that runs an agent-device daemon next to a simulator, an emulator,
or a phone works. The provider leases one device per worker slot when the
run starts, and releases it when the run ends.
For Expo Simulators, use expoSimulators() from
@e2e-dev/eas. For TestMu AI, use testmu() from
@e2e-dev/testmu. For BrowserStack, use
browserstack() from @e2e-dev/browserstack. For Android on E2B, use e2b() from
@e2e-dev/e2b. For another service, write a provider of a few dozen lines,
such as hostedDevices in the example below:
mobile({
platform: 'ios',
device: hostedDevices({ serviceUrl: 'https://devices.example.com', image: 'ios-18-iphone-17' }),
})- Each worker leases its own session, and a service bills a session while
it runs. Keep
workersat what the suite can fill. - The replay cache keys on
app.bundleId, so recordings made locally replay on hosted devices. - Leased devices warm up like local ones, before test timing starts.
The DeviceProvider contract
export interface DeviceProvider {
/** Label in progress lines and error messages. */
readonly name: string;
acquire(request: DeviceRequest): Promise<DeviceLease>;
release(lease: DeviceLease, context: DeviceReleaseContext): Promise<void>;
record?(lease: DeviceLease, context: ProviderRecordContext): Promise<ProviderRecording>;
}
export interface DeviceLease {
/** The provider's handle (a session id), handed back to `release`. */
readonly id: string;
/** The agent-device daemon the worker connects to; a lease names this, `client`, or both. */
readonly daemon?: { readonly baseUrl: string; readonly authToken?: string };
/** agent-device client configuration the worker's client is created with: a lease scope, a `stateDir`. */
readonly client?: DeviceClientConfig;
/** Device to select inside that daemon, when it hosts more than one. */
readonly device?: string;
/** Device to select inside that daemon by the id agent-device lists it under: a simulator UDID or an Android serial. */
readonly deviceId?: string;
/** Bundle id or package the provider installed itself; skips the target's `app.appPath`. */
readonly installedApp?: string;
}acquire runs for every worker slot at once, in the runner process.
The request carries platform, runId, targetName, slot, slots, app (the
target’s app.bundleId), the resolved appPath, agentDeviceVersion (for
a service that starts a daemon of a chosen version), projectRoot, env,
an interrupt signal, and a log that reaches the reporter.
- Read tokens from
request.env, notprocess.env. Read project files underrequest.projectRoot, notprocess.cwd(). - A target with nothing to run leases nothing.
- Set
installedApponly when the request has anappPath. Otherwise the run fails.
release runs after the last worker exits, within cleanupTimeout, on
every exit path: a failure, an interrupt, or a prepare that threw. It gets
the object acquire returned, so a provider can keep its own fields on it.
Only the DeviceLease fields reach the workers. When one slot fails to
lease, the run ends before any test, and the engine still releases every
lease it got.
client is agent-device client configuration, as JSON data, applied on
top of the session name and the daemon address. A lease that sets
session, daemonBaseUrl, daemonAuthToken, or daemonTransport is
refused. For agent-device’s own device-cloud runtimes, client carries the
lease scope that leases.allocate returned: tenant, runId, leaseId,
leaseBackend, and leaseProvider. A command without a scope falls back
to the local devices. A stateDir in client points the worker at a
daemon the provider started, so no daemon address is needed.
record is optional. When an attempt records video, the worker calls
it instead of agent-device’s screen recording. The worker may be another
process, so record gets only the lease fields, not state acquire kept.
It returns a ProviderRecording (a type from e2e/engine) whose stop
either writes a file into the directory it gets and returns { file },
kept as video/<file>, or returns { url, mediaType } for a recording the
service keeps, which the report links. A record that fails fails the
attempt’s launch. A stop that fails is tried one more time when the
attempt ends.
Example: a provider for a session API
A typical session API needs three requests: create a session, poll it until the daemon is reachable, and stop it.
import type { DeviceProvider } from '@e2e-dev/mobile';
/**
* Leases devices from a service that starts an agent-device daemon per
* session. Replace the three requests with your service's API.
*/
export function hostedDevices(options: { serviceUrl: string; image: string }): DeviceProvider {
return {
name: 'hosted-devices',
async acquire(request) {
const token = request.env['DEVICE_SERVICE_TOKEN'];
if (token === undefined || token === '') throw new Error('DEVICE_SERVICE_TOKEN is not set');
const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
// 1. Ask for a device; name the session after the run so it can be found later.
const created = await fetch(`${options.serviceUrl}/sessions`, {
method: 'POST',
headers,
body: JSON.stringify({
platform: request.platform,
image: options.image,
name: `e2e ${request.runId} ${request.targetName} ${request.slot + 1}/${request.slots}`,
}),
signal: request.signal,
});
if (!created.ok) throw new Error(`device service: HTTP ${created.status}`);
const { id } = (await created.json()) as { id: string };
// 2. Wait until the session exposes its agent-device daemon.
for (;;) {
const response = await fetch(`${options.serviceUrl}/sessions/${id}`, { headers, signal: request.signal });
const session = (await response.json()) as { status: string; daemonUrl?: string; daemonToken?: string; viewerUrl?: string };
if (session.status === 'ready' && session.daemonUrl !== undefined) {
if (session.viewerUrl !== undefined) request.log(`watch at ${session.viewerUrl}`);
return { id, daemon: { baseUrl: session.daemonUrl, authToken: session.daemonToken } };
}
if (session.status !== 'starting') throw new Error(`device service: session ${id} is ${session.status}`);
await new Promise((resolve) => setTimeout(resolve, 5_000));
}
},
async release(lease, context) {
// 3. Stop the session; the run waits for this within cleanupTimeout.
const token = context.env['DEVICE_SERVICE_TOKEN'] ?? '';
await fetch(`${options.serviceUrl}/sessions/${lease.id}/stop`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
signal: context.signal,
});
},
};
}Example: a device cloud that agent-device supports
A device cloud that agent-device itself speaks to needs no session API of
your own. agentDeviceLeases() from @e2e-dev/mobile/lease starts an
agent-device daemon per worker slot with the credentials in env, allocates
a lease with the selectors, keeps it alive while the run holds it, and on
release fails unless agent-device confirms the session ended. testmu()
from @e2e-dev/testmu works this way for TestMu AI,
and browserstack() from @e2e-dev/browserstack for
BrowserStack.
import type { DeviceProvider } from '@e2e-dev/mobile';
import { agentDeviceLeases } from '@e2e-dev/mobile/lease';
/**
* Leases devices from a device cloud agent-device itself speaks to. Each
* worker slot gets its own agent-device daemon, whose runtime for the cloud
* starts the session when the lease is allocated and ends it on release.
* `provider` is agent-device's name for the cloud.
*/
export function cloudDevices(options: { provider: string; device: string; osVersion: string; app: string }): DeviceProvider {
const leases = agentDeviceLeases({ provider: options.provider, label: options.provider });
return {
name: options.provider,
async acquire(request) {
const token = request.env['CLOUD_TOKEN'];
if (token === undefined || token === '') throw new Error('CLOUD_TOKEN is not set');
return leases.acquire(request, {
// The daemon's runtime reads the credentials from its environment.
env: { CLOUD_TOKEN: token },
selectors: { device: options.device, providerOsVersion: options.osVersion, providerApp: options.app },
summary: `${options.device}, ${request.platform} ${options.osVersion}`,
});
},
release: (lease, context) => leases.release(lease, context),
};
}What differs from the web
Known device limitations
placeholderis the only attribute a device node has.- A React Native tab (
accessibilityRole="tab") on iOS has roleother. Query it by test id or label and asserttoBeSelected. Checkboxes, radios, andtoBeCheckedwork on both platforms. - On iOS, a plain React Native
Viewhas no children in the tree, sofilter({ has })on it and queries scoped to it match nothing, whilefilter({ hasNot })keeps every such row, including one you meant to exclude. Scope to the screen’sScrollView(device.locator('role=scroll-area')), or give the children test ids. - A Jetpack Compose clickable drawn smaller than 48dp shows as two buttons
in the tree, and a tap fails with
has no parent-owned touch point. Make the control at least 48dp, Android’s minimum touch target. - An element hidden with
display: noneisn’t in the tree, sotoBeAttachedfails. AsserttoHaveCount(0)ortoBeHidden. doubleTap()on iOS is two taps about 285 ms apart. Give a double-tap detector a window of 350 ms or more.- On iOS,
device.foregroundApp()still names the session’s app afterdevice.home(). Check the screen instead. - On an Android build with no shell command for the clipboard service (the
Android 16 emulator is one),
device.clipboard()anddevice.setClipboard()throwUNSUPPORTED_CAPABILITY. To check a copy, paste into a field and read the field back. - On an iPhone Duo,
--videorecords the display that was lit when the recording started. Afterdevice.foldmoves the app to the other display, the rest of the video is black.
Troubleshooting
A device failure shows agent-device’s own message. Under the agent, an
engine fault with no more specific code reports as APP_UNREACHABLE, so
read the message before the code: often the app isn’t what failed.
The iOS automation runner is busy, wedged, or can’t present a snapshot. A heavy or animating screen can overrun the runner, and a run stopped with Ctrl-C can leave it busy. The message names the runner and the first move, usually a rerun. If the next run meets it again, stop the daemon and reboot the simulator with the commands below.
device.installApp() on Android reports no bundle id or package.
agent-device couldn’t tell which package the build is, so app.open() has
nothing to launch. When it can’t read the APK’s manifest, it falls back to
the Android SDK’s aapt, found under ANDROID_SDK_ROOT, ANDROID_HOME,
~/Library/Android/sdk on macOS, or ~/Android/Sdk. Set the target’s
app.bundleId. Or export ANDROID_HOME, then stop the agent-device daemon
so the next run starts it with the variable.
Android reports insufficient foreground app content, or iOS reports the
app is not running. agent-device couldn’t read the screen yet, often an
app still loading after a cold start. On iOS this only counts until the
first readable screen after app.open(), app.restart(), or
device.openLink(), as on a physical iPhone that is still launching the
app; an app that exits later fails at once. A waiting locator action or
expect waits through it, as for an element not there yet. If the screen
is still unreadable when the wait runs out, the step fails with this
message. Immediate reads like count() and isVisible() see no matches
instead, so not.toBeVisible() can pass while the screen is unreadable,
including on an app that crashed before it rendered. An observation, such
as the agent’s next turn, fails on it at once.
A timeout on the device. A simulator boot, runner connection, or app
launch that times out on the device is ENGINE_FAILURE with agent-device’s
message and hint, never LAUNCH_TIMEOUT, ACTION_FAILED, or
STEP_TIMEOUT.
An action that outlives its timeout. A tap, fill, key, swipe, or
back gets its timeout (default actionTimeout). If the device doesn’t
answer in time, the step fails with ACTION_FAILED and isn’t retried: the
input may have landed. A longPress that holds at least as long as the
time left is refused before it’s sent; raise its timeout. Snapshots and
screenshots run within the timeout of the call that takes them, so a device
that stops answering fails the step with ACTION_FAILED instead of holding
it until the test timeout. locator.waitFor, expect, and
toHaveScreenshot give their last snapshot extra time, up to their slowest
one so far and within the test timeout, so a screen that shows up during it
still passes. An element that never shows up fails as
LOCATOR_NOT_FOUND, or ASSERTION_FAILED for expect.
npx e2e doctor # agent-device, the toolchain, the devices, the app
npx agent-device daemon stop # after a wedge: drops every session, the next run starts the daemon
xcrun simctl shutdown <udid> && xcrun simctl boot <udid>pnpm exec e2e doctor # agent-device, the toolchain, the devices, the app
pnpm exec agent-device daemon stop # after a wedge: drops every session, the next run starts the daemon
xcrun simctl shutdown <udid> && xcrun simctl boot <udid>bunx e2e doctor # agent-device, the toolchain, the devices, the app
bunx agent-device daemon stop # after a wedge: drops every session, the next run starts the daemon
xcrun simctl shutdown <udid> && xcrun simctl boot <udid>