Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/local-harmonyos-phone.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@e2e-dev/mobile": patch
"e2e": patch
---

Run a local HarmonyOS target against an installed ArkUI app. Select one phone by HDC serial, launch the app by bundle name, tap a button and assert its text with screen locators. The bundled setup guide shows how to configure the local phone target.
47 changes: 44 additions & 3 deletions docs/mobile.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Android:
}
```

A device target needs `bundleId`, `appPath`, or both. The engine installs
An iOS or Android target needs `bundleId`, `appPath`, or both. The engine installs
nothing on its own. Call `device.installApp()` once per device, in a
[worker fixture](/fixtures#share-a-fixture-across-a-worker) with
[`auto: true`](/fixtures#run-a-fixture-for-every-test). With no path, it
Expand All @@ -73,7 +73,7 @@ To run the suite in CI, see [Mobile jobs](/ci#mobile-jobs).

### Launch arguments and permissions

`app.launchArguments` and `app.permissions` apply to every fresh launch.
On iOS and Android, `app.launchArguments` and `app.permissions` apply to every fresh launch.

```ts
app: {
Expand Down Expand Up @@ -559,7 +559,7 @@ Then 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 iOS and Android phones, use the name. On those platforms 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
paired iPhone or iPad that is reachable (USB or network), or a connected
Expand Down Expand Up @@ -616,6 +616,47 @@ with agent-device's message.
second, and drops frames.
</Accordion>

### Local HarmonyOS phone

Connect an unlocked physical phone and confirm its serial with `hdc list targets`.
Sign and install the ArkUI app first. Configure its bundle name:

```ts title="e2e.config.ts"
import { mobile } from '@e2e-dev/mobile';
import type { E2EConfig } from 'e2e';

export default {
targets: [{
name: 'harmony-phone',
engine: mobile({ platform: 'harmonyos' }),
app: { bundleId: 'com.example.e2ecounter' },
}],
} satisfies E2EConfig;
```

With several phones connected, set `device` to the HDC serial or pass
`--device <serial>` to the run. Each target uses one worker. This example uses the ArkUI component IDs `counterValue` and `incrementButton`
so the same test can run with translated labels.

```ts
import { test } from '@e2e-dev/mobile';
import { expect } from 'e2e';

test('increments the ArkUI counter', async ({ app, screen }) => {
await app.open();
const counter = screen.getByTestId('counterValue');
await expect(counter).toHaveText(/\b0$/);
await screen.getByTestId('incrementButton').tap();
await expect(counter).toHaveText(/\b1$/);
await app.screenshot('counter-after-tap');
});
```

The local target supports taps and screenshots. Other device operations may
return `UNSUPPORTED_CAPABILITY`. The target accepts physical phones only.
HAP installation, launch arguments, permission presets, video recording,
emulators and hosted devices are outside its supported scope.

## Hosted devices

Use [Limrun](/integrations/limrun) for hosted iOS simulators and Android
Expand Down
11 changes: 7 additions & 4 deletions docs/reference/mobile.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ The app under test is the target's `app`, not an engine option; see

| Option | Type | Default |
| --- | --- | --- |
| [`platform`](#platform) | `'ios' \| 'android'` | required |
| [`platform`](#platform) | `'ios' \| 'android' \| 'harmonyos'` | required |
| [`device`](#device-option) | `string \| readonly string[] \| DeviceProvider` | every booted device |
| [`session`](#session) | `string` | `e2e-<target name>` |
| [`snapshot`](#snapshot) | `'full' \| 'interactive'` | `'full'` |
Expand All @@ -96,7 +96,7 @@ Every optional value also accepts `undefined`, so values read straight from
| --- | --- |
| `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` | `platform` is missing or outside `'ios'`, `'android'` and `'harmonyos'`; 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`). |
Expand All @@ -111,6 +111,9 @@ readonly platform: MobilePlatform;
mobile({ platform: 'android' });
```

- Required. Choose `'ios'`, `'android'` or `'harmonyos'`.
- A [local HarmonyOS phone](/mobile#local-harmonyos-phone) runs one worker against an installed app. Set `app.bundleId` and select a single phone by HDC serial or name.

#### `device` option

```ts
Expand Down Expand Up @@ -1461,9 +1464,9 @@ export interface DeviceSelection {
| 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.deviceId` | An iOS simulator UDID, an Android serial, or a HarmonyOS HDC 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). |
| `DeviceSelection` | The platform, then one of `device` (a name), `udid` (a simulator UDID), or `serial` (an Android or HDC serial). |
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

### Exported types

Expand Down
6 changes: 4 additions & 2 deletions packages/mobile/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ on a device target unchanged; neither `e2e` nor `@e2e-dev/core` imports this pac
To drive a device from a program without the test runner, import `mobile` from
`@e2e-dev/mobile/engine` with [`@e2e-dev/core`](https://www.npmjs.com/package/@e2e-dev/core).

For a local HarmonyOS phone, follow the [HarmonyOS setup and counter test](https://e2e.com/docs/mobile#local-harmonyos-phone) to configure an installed app by bundle name and run it over HDC.

## Install

Run `npx e2e init` and choose **Mobile (iOS/Android)** for a Settings
Expand Down Expand Up @@ -70,8 +72,8 @@ the other old app options are `INVALID_CONFIG` naming their key under `app`.

| Option | Meaning |
| --- | --- |
| `platform` | `'ios'` or `'android'`. |
| `device` | Simulator or emulator name or UDID, or a paired iPhone or iPad's name or a connected Android phone's name. A list is a pool: one worker per entry, worker slot `n` driving the `n`th. Omitted, every booted device of the platform is the pool, as many as the run has slots, a reachable paired iPhone or iPad included; with none booted, agent-device boots 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). |
| `platform` | `'ios'`, `'android'`, or `'harmonyos'`. |
| `device` | On HarmonyOS, one local phone by HDC serial or name. On iOS and Android: simulator or emulator name or UDID, or a paired iPhone or iPad's name or a connected Android phone's name. A list is a pool: one worker per entry, worker slot `n` driving the `n`th. Omitted, every booted device of the platform is the pool, as many as the run has slots, a reachable paired iPhone or iPad included; with none booted, agent-device boots 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). |
| `session` | agent-device session name, before the worker slot: slot `n` drives its device under `<session>-<n>`, `e2e-<target name>-<n>` by default. One run per session at a time. |
| `snapshot` | `'full'` (default, includes static text) or `'interactive'` (actionable nodes only). |
| `settle` | Milliseconds the UI must hold still after an agent action before the agent observes again, default `150`; `false` skips the wait. A test's steps do not settle, except `device.back()`; `expect` verifies their outcome. |
Expand Down
2 changes: 1 addition & 1 deletion packages/mobile/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@e2e-dev/mobile",
"version": "0.12.9",
"description": "Mobile engine (iOS and Android) for e2e agentic end-to-end testing, built on agent-device",
"description": "Mobile engine (iOS, Android, and local HarmonyOS phones) for e2e agentic end-to-end testing, built on agent-device",
"keywords": [
"e2e",
"end-to-end",
Expand Down
2 changes: 1 addition & 1 deletion packages/mobile/src/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export function deviceSelection(
const { device, deviceId } = binding ?? {};
const id = deviceId ?? (device !== undefined && (UDID.test(device) || EMULATOR_SERIAL.test(device)) ? device : undefined);
if (id === undefined) return obj({ platform, device });
return platform === 'android' ? { platform, serial: id } : { platform, udid: id };
return platform === 'ios' ? { platform, udid: id } : { platform, serial: id };
}

/**
Expand Down
18 changes: 14 additions & 4 deletions packages/mobile/src/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
import { stat } from 'node:fs/promises';
import path from 'node:path';
import { obj, type EngineDoctorCheck, type EngineDoctorInfo } from '@e2e-dev/core/engine';
import { runCommand } from './errors.ts';
import { message, runCommand } from './errors.ts';
import type { ClientFactory, MobileOptions } from './options.ts';
import { deviceSelection } from './bindings.ts';
import { isDeviceList } from './pool.ts';
import { deviceSelection, type SlotBinding } from './bindings.ts';
import { harmonyPhone, isDeviceList } from './pool.ts';
import type { DeviceProvider } from './provider.ts';

/** Checks that apply to the whole machine, reported once however many devices the target names. */
Expand Down Expand Up @@ -42,9 +42,19 @@ export async function mobileDoctor(options: MobileOptions, createClient: ClientF
const reported = new Set<string>();
for (const name of devices) {
info.log(`agent-device doctor${name === undefined ? '' : ` for "${name}"`}`);
let binding: Pick<SlotBinding, 'device' | 'deviceId'> | undefined = name === undefined ? undefined : { device: name };
if (options.platform === 'harmonyos') {
try {
const phone = await harmonyPhone(client, binding, session, info.signal);
binding = { deviceId: phone.id };
} catch (cause) {
if (info.signal.aborted) throw cause;
return [...checks, { id: 'device', status: 'fail', message: message(cause) }];
}
}
const result = await runCommand(
'doctor',
() => client.command.doctor(obj({ ...deviceSelection(options.platform, name === undefined ? undefined : { device: name }), targetApp, signal: info.signal })),
() => client.command.doctor(obj({ ...deviceSelection(options.platform, binding), targetApp, signal: info.signal })),
info.signal,
);
for (const check of result.checks) {
Expand Down
79 changes: 48 additions & 31 deletions packages/mobile/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import { createRequire } from 'node:module';
import { createAgentDeviceClient } from 'agent-device';
import { ConfigurationError, defineEngine, obj, type EngineAppCheckInfo, type EngineAppDeclaration, type EngineHandle, type EngineIsolation } from '@e2e-dev/core/engine';
import { ConfigurationError, defineEngine, obj, type Engine, type EngineAppCheckInfo, type EngineAppDeclaration, type EngineHandle, type EngineIsolation } from '@e2e-dev/core/engine';
import { createDeviceFixture } from './device.ts';
import type { ClientFactory, MobileOptions, MobilePlatform } from './options.ts';
import { assertLaunchArgumentsFor } from './launch-arguments.ts';
Expand All @@ -27,6 +27,41 @@ const surfaces = new WeakMap<EngineHandle, AgentDeviceSurface>();
export interface MobileEngine<Platform extends string = string, Isolation extends EngineIsolation = EngineIsolation>
extends EngineHandle<MobileFixtures, Platform, Isolation> {}

type MobileCapabilities = Pick<Engine, 'actions' | 'pointerActions' | 'keyboard' | 'session' | 'artifacts' | 'grantsAllPermissions' | 'launchArgumentValues'>;

function platformCapabilities(surface: AgentDeviceSurface): MobileCapabilities {
// The runner serves app.open() by restarting the pinned app.
const session: NonNullable<Engine['session']> = { restart: (operation) => surface.restart(operation) };
const artifacts: NonNullable<Engine['artifacts']> = {
screenshot: (label, operation) => surface.screenshot(label, operation, surface.inputBudget('screenshot', operation)),
};
if (surface.options.platform === 'harmonyos') {
return { actions: ['tap'], pointerActions: ['tap'], session, artifacts };
}
return {
actions: DEVICE_ACTIONS,
pointerActions: DEVICE_POINTER_ACTIONS,
grantsAllPermissions: true,
launchArgumentValues: true,
keyboard: {
type: (text, options, operation) => surface.typeText(text, options, operation, surface.inputBudget('type', operation)),
press: (key, operation) => surface.pressFocusedKey(key, operation, surface.inputBudget('press', operation)),
dismiss: (operation) => surface.dismissKeyboard(operation.signal, surface.inputBudget('keyboard dismiss', operation)),
},
session: {
...session,
back: (operation) => surface.back(operation, surface.inputBudget('back', operation)),
reset: (operation) => surface.reset(operation),
openLink: async (url, operation) => surface.openLink(linkTarget(url), undefined, operation.signal, surface.inputBudget('open link', operation)),
},
artifacts: {
...artifacts,
startVideo: (operation) => surface.startVideo(operation),
stopVideo: (operation) => surface.stopVideo(operation),
},
};
}

/** Assembles the manifest for one surface. Exported for tests that script the client. */
export function buildEngine<Platform extends MobilePlatform>(surface: AgentDeviceSurface<Platform>): MobileEngine<Platform, 'worker'> {
const handle = defineEngine<MobileFixtures, Platform, 'worker'>({
Expand All @@ -37,9 +72,7 @@ export function buildEngine<Platform extends MobilePlatform>(surface: AgentDevic
...(surface.pool.size === undefined ? {} : { workers: surface.pool.size }),
// `e2e run --device` names the device `prepare` binds; see DevicePool.prepare.
...(surface.pool.selectsDevice ? { selectsDevice: true } : {}),
// `app.permissions: 'all'` is one agent-device `all` grant; see AgentDeviceSurface.presetPermissions.
grantsAllPermissions: true,
launchArgumentValues: true,
...platformCapabilities(surface),
prepare: (info) => surface.pool.prepare(info),
finish: (info) => surface.pool.finish(info),
doctor: (info) => surface.doctor(info),
Expand All @@ -53,31 +86,8 @@ export function buildEngine<Platform extends MobilePlatform>(surface: AgentDevic
locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation)),
viewportIntersection: (ref, operation) => surface.viewportIntersection(ref, operation, surface.inputBudget('viewport intersection', operation)),
perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation)),
actions: DEVICE_ACTIONS,
performAt: (point, action, operation) => surface.performAt(point, action, operation, surface.inputBudget(action.kind, operation)),
pointerActions: DEVICE_POINTER_ACTIONS,
keyboard: {
type: (text, keyboardOptions, operation) => surface.typeText(text, keyboardOptions, operation, surface.inputBudget('type', operation)),
press: (key, operation) => surface.pressFocusedKey(key, operation, surface.inputBudget('press', operation)),
dismiss: (operation) => surface.dismissKeyboard(operation.signal, surface.inputBudget('keyboard dismiss', operation)),
},
validateApp: (app, info) => validateApp(app, info, surface.options.platform),
// No `open`: a device app has no URL to open, so the runner serves
// `app.open()` with `restart`, the fresh launch of the pinned app, which
// is also the device's "recreate the context".
session: {
back: (operation) => surface.back(operation, surface.inputBudget('back', operation)),
restart: (operation) => surface.restart(operation),
reset: (operation) => surface.reset(operation),
// `app.open(path)` on a target with `app.linkBase`: the link opens in the pinned app, as `device.openLink` would.
openLink: async (url, operation) =>
await surface.openLink(linkTarget(url), undefined, operation.signal, surface.inputBudget('open link', operation)),
},
artifacts: {
screenshot: (label, operation) => surface.screenshot(label, operation, surface.inputBudget('screenshot', operation)),
startVideo: (operation) => surface.startVideo(operation),
stopVideo: (operation) => surface.stopVideo(operation),
},
fixtures: {
device: (context) => createDeviceFixture(surface, context),
},
Expand All @@ -94,12 +104,12 @@ export function buildEngine<Platform extends MobilePlatform>(surface: AgentDevic
export function mobile<Platform extends MobilePlatform>(options: MobileOptions<Platform>): MobileEngine<Platform, 'worker'> {
// The type requires it; `e2e mcp`'s `open_session {engine}` calls this with the JSON an agent wrote.
const platform: unknown = (options as Partial<MobileOptions> | undefined)?.platform;
if (platform !== 'ios' && platform !== 'android') {
throw new ConfigurationError('INVALID_CONFIG', `mobile() needs platform: 'ios' or 'android', got ${JSON.stringify(platform) ?? 'no platform'}`);
if (platform !== 'ios' && platform !== 'android' && platform !== 'harmonyos') {
throw new ConfigurationError('INVALID_CONFIG', `mobile() needs platform: 'ios', 'android', or 'harmonyos', got ${JSON.stringify(platform) ?? 'no platform'}`);
}
const factory: ClientFactory = (session, connection) => {
// A provider's local daemon must not inherit the user's remote-daemon connection.
const local = connection?.client?.stateDir !== undefined && connection.daemon === undefined;
// Local-only targets and provider-local daemons connect on this host even when a remote daemon is configured.
const local = platform === 'harmonyos' || (connection?.client?.stateDir !== undefined && connection.daemon === undefined);
return createAgentDeviceClient(
obj({
...connection?.client,
Expand All @@ -115,6 +125,7 @@ export function mobile<Platform extends MobilePlatform>(options: MobileOptions<P

/** What reaching this machine from the device will take once a device target can open a URL. */
const LOOPBACK_NOTES: Readonly<Record<MobilePlatform, string>> = {
harmonyos: "a connected HarmonyOS phone uses its own loopback",
ios: "a simulator shares this machine's loopback, and a hosted device cannot reach it at all",
android: "127.0.0.1 on an Android emulator is the emulator itself (this machine is 10.0.2.2), and a hosted device cannot reach this machine's loopback at all",
};
Expand All @@ -127,6 +138,12 @@ const LOOPBACK_NOTES: Readonly<Record<MobilePlatform, string>> = {
*/
function validateApp(app: EngineAppDeclaration, { targetName }: EngineAppCheckInfo, platform: MobilePlatform): void {
const where = `target "${targetName}"`;
if (platform === 'harmonyos' && (app.appPath !== undefined || app.bundleId === undefined)) {
throw new ConfigurationError('INVALID_CONFIG', `${where} requires an installed HarmonyOS app. Set app.bundleId and omit app.appPath.`);
}
if (platform === 'harmonyos' && (app.permissions !== undefined || app.launchArgumentValues !== undefined || app.launchArguments !== undefined)) {
throw new ConfigurationError('INVALID_CONFIG', `${where} supports launching an installed HarmonyOS app by bundleId only. Omit permissions and launchArguments.`);
}
if (app.url !== undefined) {
throw new ConfigurationError(
'INVALID_CONFIG',
Expand Down
Loading