From 6d610e1092f7d6352eee61e2d3a33478b4da94bd Mon Sep 17 00:00:00 2001 From: fryandev <268098688+fryandev@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:03:22 +0800 Subject: [PATCH 1/8] feat(mobile): prototype a local HarmonyOS phone target --- docs/mobile.mdx | 4 +++ packages/mobile/examples/harmonyos/Index.ets | 36 +++++++++++++++++++ packages/mobile/examples/harmonyos/README.md | 31 ++++++++++++++++ .../mobile/examples/harmonyos/e2e.config.ts | 10 ++++++ .../examples/harmonyos/tests/counter.e2e.ts | 10 ++++++ packages/mobile/src/engine.ts | 23 +++++++----- packages/mobile/src/nodes.ts | 10 ++++-- packages/mobile/src/options.ts | 2 +- packages/mobile/src/pool.ts | 17 ++++++--- packages/mobile/src/provider.ts | 6 ++-- packages/mobile/src/surface.ts | 15 ++++++-- packages/mobile/tests/types/options.ts | 3 +- packages/mobile/tests/unit/engine.test.ts | 2 +- packages/mobile/tests/unit/nodes.test.ts | 7 ++++ 14 files changed, 153 insertions(+), 23 deletions(-) create mode 100644 packages/mobile/examples/harmonyos/Index.ets create mode 100644 packages/mobile/examples/harmonyos/README.md create mode 100644 packages/mobile/examples/harmonyos/e2e.config.ts create mode 100644 packages/mobile/examples/harmonyos/tests/counter.e2e.ts diff --git a/docs/mobile.mdx b/docs/mobile.mdx index 170dd9ffd6..3a06773ec9 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -12,6 +12,10 @@ phones connected to your machine. It is built on [agent-device](https://github.com/callstack/agent-device). Tests use the same `agent`, `screen`, and `expect` APIs as browser tests. +## Local HarmonyOS prototype + +This fork accepts `mobile({ platform: 'harmonyos' })` for a connected, unlocked phone with the target app already installed. Set `app.bundleId` to its bundle name. The [counter example](https://github.com/fryandev/e2e/tree/prototype/harmonyos-local/packages/mobile/examples/harmonyos) exercises app launch, ArkUI test IDs, button taps by role and name, and text assertions. + ## Set up Install Xcode with an iOS simulator runtime, or the Android SDK with an diff --git a/packages/mobile/examples/harmonyos/Index.ets b/packages/mobile/examples/harmonyos/Index.ets new file mode 100644 index 0000000000..ae1204bd8d --- /dev/null +++ b/packages/mobile/examples/harmonyos/Index.ets @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Entry +@Component +struct Index { + @State count: number = 0; + + build() { + Column({ space: 20 }) { + Text(`计数:${this.count}`) + .id('counterValue') + .fontSize(32) + Button('加一') + .id('incrementButton') + .onClick(() => { + this.count += 1; + }) + } + .justifyContent(FlexAlign.Center) + .height('100%') + .width('100%') + } +} diff --git a/packages/mobile/examples/harmonyos/README.md b/packages/mobile/examples/harmonyos/README.md new file mode 100644 index 0000000000..e8570ae688 --- /dev/null +++ b/packages/mobile/examples/harmonyos/README.md @@ -0,0 +1,31 @@ +# ArkUI counter on a local HarmonyOS phone + +This prototype runs a deterministic test through the mobile engine against an installed ArkUI app. The test uses the public app, screen, and expect APIs. It requires a connected, unlocked phone, DevEco's hdc on PATH, and the repository's Node and pnpm toolchain. + +## Prepare the phone + +Use a HarmonyOS stage-model phone project with bundle name `com.example.e2ecounter`. For example, scaffold one outside this repository with DevEco CLI: + +```sh +devecocli create --app-name E2ECounter --bundle-name com.example.e2ecounter --api-level 26 +``` + +Replace its `entry/src/main/ets/pages/Index.ets` with [Index.ets](./Index.ets), then sign and run it on the phone with DevEco Studio. Check that `hdc list targets` lists the phone. Use a single connected phone for the test below. + +## Run from the fork + +From the repository root: + +```sh +pnpm install --frozen-lockfile +pnpm --filter @e2e-dev/core run build +pnpm --filter e2e run build +pnpm --filter @e2e-dev/mobile run build +(cd packages/mobile/examples/harmonyos && node ../../../e2e/dist/cli/bin.js run) +``` + +[The test](./tests/counter.e2e.ts) launches the app, expects “计数:0”, taps the “加一” button, and expects “计数:1”. It needs no model or credentials. The runner writes its report to `.e2e/report.json` in the example directory. + +## Verification + +On November 24, 2026, the test passed on a physical Huawei Mate 70 Air running HarmonyOS 7 (API 26), with agent-device 0.21.41. This covers the local device and installed-app path. Cloud devices, HAP deployment, agent replay, emulator provisioning, and other HarmonyOS versions are outside this prototype's tested scope. diff --git a/packages/mobile/examples/harmonyos/e2e.config.ts b/packages/mobile/examples/harmonyos/e2e.config.ts new file mode 100644 index 0000000000..537df47f08 --- /dev/null +++ b/packages/mobile/examples/harmonyos/e2e.config.ts @@ -0,0 +1,10 @@ +import { mobile } from '@e2e-dev/mobile'; +import type { E2EConfig } from 'e2e'; + +export default { + targets: [{ + name: 'harmony-phone', + engine: mobile({ platform: 'harmonyos', device: process.env['E2E_DEVICE'] }), + app: { bundleId: 'com.example.e2ecounter' }, + }], +} satisfies E2EConfig; diff --git a/packages/mobile/examples/harmonyos/tests/counter.e2e.ts b/packages/mobile/examples/harmonyos/tests/counter.e2e.ts new file mode 100644 index 0000000000..86f5d47a4f --- /dev/null +++ b/packages/mobile/examples/harmonyos/tests/counter.e2e.ts @@ -0,0 +1,10 @@ +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('计数:0'); + await screen.getByRole('button', '加一').tap(); + await expect(counter).toHaveText('计数:1'); +}); diff --git a/packages/mobile/src/engine.ts b/packages/mobile/src/engine.ts index be2787cd54..23b444c97d 100644 --- a/packages/mobile/src/engine.ts +++ b/packages/mobile/src/engine.ts @@ -27,6 +27,7 @@ export interface MobileEngine extends EngineHandle {} /** Assembles the manifest for one surface. Exported for tests that script the client. */ export function buildEngine(surface: AgentDeviceSurface): MobileEngine { + const harmony = surface.options.platform === 'harmonyos'; const handle = defineEngine({ name: 'mobile', version: ownVersion(), @@ -47,14 +48,14 @@ export function buildEngine(surface: AgentDeviceSurface): MobileEngine { observe: (operation, options) => surface.observe(operation, options, surface.inputBudget('observe', operation)), locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation)), perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation)), - actions: DEVICE_ACTIONS, + actions: harmony ? ['tap'] : DEVICE_ACTIONS, performAt: (point, action, operation) => surface.performAt(point, action, operation, surface.inputBudget(action.kind, operation)), - pointerActions: DEVICE_POINTER_ACTIONS, - keyboard: { + pointerActions: harmony ? ['tap'] : DEVICE_POINTER_ACTIONS, + ...(!harmony && { 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 @@ -69,8 +70,10 @@ export function buildEngine(surface: AgentDeviceSurface): MobileEngine { }, artifacts: { screenshot: (label, operation) => surface.screenshot(label, operation, surface.inputBudget('screenshot', operation)), - startVideo: (operation) => surface.startVideo(operation), - stopVideo: (operation) => surface.stopVideo(operation), + ...(!harmony && { + startVideo: (operation) => surface.startVideo(operation), + stopVideo: (operation) => surface.stopVideo(operation), + }), }, fixtures: { device: (context) => createDeviceFixture(surface, context), @@ -88,8 +91,8 @@ export function buildEngine(surface: AgentDeviceSurface): MobileEngine { export function mobile(options: MobileOptions): MobileEngine { // The type requires it; `e2e mcp`'s `open_session {engine}` calls this with the JSON an agent wrote. const platform: unknown = (options as Partial | 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. @@ -109,6 +112,7 @@ export function mobile(options: MobileOptions): MobileEngine { /** What reaching this machine from the device will take once a device target can open a URL. */ const LOOPBACK_NOTES: Readonly> = { + 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", }; @@ -121,6 +125,9 @@ const LOOPBACK_NOTES: Readonly> = { */ function validateApp(app: EngineAppDeclaration, { targetName }: EngineAppCheckInfo, platform: MobilePlatform): void { const where = `target "${targetName}"`; + if (platform === 'harmonyos' && app.appPath !== undefined) { + throw new ConfigurationError('INVALID_CONFIG', 'The local HarmonyOS target requires an installed app and app.bundleId.'); + } if (app.url !== undefined) { throw new ConfigurationError( 'INVALID_CONFIG', diff --git a/packages/mobile/src/nodes.ts b/packages/mobile/src/nodes.ts index f13223f0fb..fe57131ebf 100644 --- a/packages/mobile/src/nodes.ts +++ b/packages/mobile/src/nodes.ts @@ -565,6 +565,7 @@ export function projectSnapshot( raw: readonly RawNode[], options: { readonly mintId: () => string; + readonly arkUI?: boolean; readonly viewport?: ViewportSize | undefined; readonly refsGeneration?: number | undefined; readonly keyboard?: Rect | undefined; @@ -608,8 +609,11 @@ export function projectSnapshot( const kids = children.get(position) ?? []; const blank = editable && !secure && (value === undefined || value === '') && nonEmpty(source.placeholder) === undefined; const folded = !android && blank ? foldedPlaceholder(source, kids, raw, children) : undefined; + // ArkUI exposes Button captions and Text content in value. + const arkText = options.arkUI && !secure && (kind === 'button' || kind === 'text') ? nonEmpty(value) : undefined; const label = folded === undefined ? nonEmpty(source.label) : folded.label; - const name = nonEmpty(source.contentDescription) ?? label; + const text = arkText ?? label; + const name = nonEmpty(source.contentDescription) ?? label ?? arkText; const placeholder = folded?.placeholder ?? nonEmpty(source.placeholder); const projected: { node: SemanticNode | undefined } = { node: undefined }; const entry: ProjectedNode = { @@ -645,13 +649,13 @@ export function projectSnapshot( // field answers `getByLabel` by that description and `getByText` by // what it shows. The model rendering elides `text` whenever it equals `name`. ...(name === undefined ? {} : { name }), - ...(label === undefined ? {} : { text: label }), + ...(text === undefined ? {} : { text }), // A secure field's value is never observed; the tree carries that it is // secure, not what it holds. Android echoes a text view's label as its // value, which would render every line twice, so that echo is dropped; // a field keeps a value equal to its label, since iOS names an // unlabeled field by its text and the value is what a test reads. - ...(secure || value === undefined || value === '' || (android && !editable && value === source.label) + ...(secure || value === undefined || value === '' || arkText === value || (android && !editable && value === source.label) ? {} : { value }), ...(secure ? { inputPurpose: 'password' as const } : {}), diff --git a/packages/mobile/src/options.ts b/packages/mobile/src/options.ts index f6f138d65e..bb4cc02a5c 100644 --- a/packages/mobile/src/options.ts +++ b/packages/mobile/src/options.ts @@ -17,7 +17,7 @@ export type AgentDeviceClient = ReturnType; */ export type ClientFactory = (session: string, connection?: DeviceConnection) => AgentDeviceClient; -export type MobilePlatform = 'ios' | 'android'; +export type MobilePlatform = 'ios' | 'android' | 'harmonyos'; /** Every permission agent-device can grant, deny, or reset on an app: what a target's `app.permissions` and `device.openApp` may name. */ export const DEVICE_PERMISSIONS = [ diff --git a/packages/mobile/src/pool.ts b/packages/mobile/src/pool.ts index a2f16a8e17..cff831ffff 100644 --- a/packages/mobile/src/pool.ts +++ b/packages/mobile/src/pool.ts @@ -52,7 +52,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 }; } /** @@ -100,7 +100,10 @@ function sourceFor(options: MobileOptions, createClient: ClientFactory, session: } return new ConfiguredDevices(device.map(namedDevice)); } - return new LeasedDevices(asDeviceProvider(device), options); + if (options.platform === 'harmonyos') { + throw new ConfigurationError('INVALID_CONFIG', 'HarmonyOS requires a locally connected device.'); + } + return new LeasedDevices(asDeviceProvider(device), { platform: options.platform }); } /** A device name from the `device` option; a blank one would select no device, and the daemon would refuse several booted ones as ambiguous. */ @@ -160,6 +163,9 @@ class BootedDevices implements DeviceSource { ); } if (chosen.length === 0) { + if (this.platform === 'harmonyos') { + throw new EngineError('ENGINE_FAILURE', 'Connect a HarmonyOS phone and check hdc list targets.', { retryable: false }); + } info.log(`no booted ${this.platform} device; agent-device boots a shut-down one (iPhone over iPad over Apple TV on iOS, phone or tablet over TV on Android, then newest OS, then name)`); return [{}]; } @@ -350,10 +356,13 @@ export class DevicePool { const at = `session ${session} on ${label}`; const client = this.createClient(session, binding); this.retain(info.targetName, { session, client }); - info.log(`booting ${label} (${slot + 1} of ${bindings.length})`); + const phase = this.options.platform === 'harmonyos' ? 'preparing' : 'booting'; + info.log(`${phase} ${label} (${slot + 1} of ${bindings.length})`); const took: string[] = []; try { - await timed(took, 'boot', () => runCommand('boot', () => client.devices.boot(bootRequest(where)), info.signal, at)); + if (this.options.platform !== 'harmonyos') { + await timed(took, 'boot', () => runCommand('boot', () => client.devices.boot(bootRequest(where)), info.signal, at)); + } const runnerUp = this.options.platform !== 'ios' || (await timed(took, 'iOS runner', () => prepareRunner(client, where, info, at))); const app = pinnedApp(info.app, binding.installedApp); if (app === undefined || !runnerUp) continue; diff --git a/packages/mobile/src/provider.ts b/packages/mobile/src/provider.ts index fa46237f27..81ad1d8a7a 100644 --- a/packages/mobile/src/provider.ts +++ b/packages/mobile/src/provider.ts @@ -25,12 +25,12 @@ import { isSlotBinding, type DeviceClientConfig, type DeviceDaemon, type DeviceS import { message } from './errors.ts'; import { isLink } from './links.ts'; import { cancelled } from './support.ts'; -import type { MobileOptions, MobilePlatform } from './options.ts'; +import type { MobilePlatform } from './options.ts'; /** What the engine asks a provider for: one device for one worker slot of a run. */ export interface DeviceRequest { /** Platform the target's device must run. */ - readonly platform: MobilePlatform; + readonly platform: Exclude; /** The run id, for naming the session at the provider. */ readonly runId: string; /** The target the device serves. */ @@ -239,7 +239,7 @@ export class LeasedDevices implements DeviceSource { constructor( private readonly provider: DeviceProvider, - private readonly options: Pick, + private readonly options: Pick, ) { this.recorder = provider.record === undefined ? undefined : (provider as RecordingDeviceProvider); } diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index 23a38e5c08..d176b56460 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -680,8 +680,18 @@ export class AgentDeviceSurface { provider === undefined || lease === undefined ? undefined : { provider, lease, runId: info.runId, targetName: info.targetName, env: info.env }; - const booted = await this.command('boot', (client) => client.devices.boot(bootRequest(this.selection())), info.signal); - this.bound = { session, deviceId: booted.id, deviceName: booted.device }; + if (this.options.platform === 'harmonyos') { + const devices = await this.command('devices', (client) => client.devices.list({ platform: 'harmonyos' }), info.signal); + const selected = binding?.deviceId ?? binding?.device; + const matches = devices.filter((item) => item.booted && (selected === undefined || item.id === selected || item.name === selected)); + if (matches.length !== 1) throw invalidState('Expected one connected HarmonyOS phone matching the device selection.'); + const phone = matches[0]!; + this.device = { deviceId: phone.id }; + this.bound = { session, deviceId: phone.id, deviceName: phone.name }; + } else { + const booted = await this.command('boot', (client) => client.devices.boot(bootRequest(this.selection())), info.signal); + this.bound = { session, deviceId: booted.id, deviceName: booted.device }; + } // Nothing is installed here: a device provider that installed the build // from `appPath` says so on the binding, and otherwise the suite installs // it where it wants to, with `device.installApp()`. @@ -1189,6 +1199,7 @@ export class AgentDeviceSurface { private project(raw: RawSnapshot): ProjectedScreen { const projected = { ...projectSnapshot(raw.nodes ?? [], { + arkUI: this.options.platform === 'harmonyos', mintId: () => { this.idCounter += 1; return `n${this.idCounter}`; diff --git a/packages/mobile/tests/types/options.ts b/packages/mobile/tests/types/options.ts index a666c1bab8..09e02df37e 100644 --- a/packages/mobile/tests/types/options.ts +++ b/packages/mobile/tests/types/options.ts @@ -19,7 +19,8 @@ const farm = { ({ platform: 'ios', device: farm }) satisfies MobileOptions; ({ id: 'lease-1', daemon: { baseUrl: 'http://10.0.0.7:4700' } }) satisfies DeviceLease; -// @ts-expect-error the platform is ios or android. +({ platform: 'harmonyos' }) satisfies MobileOptions; +// @ts-expect-error web belongs to the browser engine. ({ platform: 'web' }) satisfies MobileOptions; // @ts-expect-error the snapshot mode is full or interactive. ({ platform: 'ios', snapshot: 'all' }) satisfies MobileOptions; diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index 2c6db457d3..bc9579051c 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -112,7 +112,7 @@ describe('manifest', () => { ); // What `e2e mcp` passes when an agent names the package alone, or leaves the platform out. for (const options of [undefined, {}, { platform: 'tvos' }, { platform: 'iOS' }, { platform: 'Android' }]) { - expect(() => mobile(options as never)).toThrowError(expect.objectContaining({ code: 'INVALID_CONFIG', message: expect.stringContaining("mobile() needs platform: 'ios' or 'android'") })); + expect(() => mobile(options as never)).toThrowError(expect.objectContaining({ code: 'INVALID_CONFIG', message: expect.stringContaining("mobile() needs platform: 'ios', 'android', or 'harmonyos'") })); } expect(() => mobile({ platform: 'ios', app: 'x' } as never)).toThrowError( expect.objectContaining({ code: 'INVALID_CONFIG', message: expect.stringMatching(/^mobile\(\) has unknown key "app"/) }), diff --git a/packages/mobile/tests/unit/nodes.test.ts b/packages/mobile/tests/unit/nodes.test.ts index b65b7c4e09..ad90805262 100644 --- a/packages/mobile/tests/unit/nodes.test.ts +++ b/packages/mobile/tests/unit/nodes.test.ts @@ -13,6 +13,13 @@ function project(nodes: readonly RawNode[]) { } describe('snapshot projection', () => { + it('exposes an ArkUI caption as text and preserves a separate accessibility label', () => { + const { roots } = projectSnapshot([{ type: 'Button', label: 'Increase count', value: '+1', identifier: 'incrementButton' }], { + mintId: () => 'n1', arkUI: true, + }); + expect(roots[0]).toMatchObject({ name: 'Increase count', text: '+1', testId: 'incrementButton', role: 'button' }); + }); + it('rebuilds the tree from parentIndex and keeps document order in the index', () => { const projected = project(SETTINGS_NODES); expect(projected.roots).toHaveLength(1); From 7107dd8672cc6cc1dc325ac28b947ce827f80d89 Mon Sep 17 00:00:00 2001 From: fryandev <268098688+fryandev@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:12:43 +0800 Subject: [PATCH 2/8] feat(mobile): define and test local HarmonyOS target support --- .changeset/local-harmonyos-phone.md | 5 ++ docs/mobile.mdx | 14 +++- docs/reference/mobile.mdx | 7 +- packages/mobile/README.md | 2 + packages/mobile/src/engine.ts | 24 ++++--- packages/mobile/src/options.ts | 3 +- packages/mobile/src/pool.ts | 41 +++++++++-- packages/mobile/src/surface.ts | 10 ++- .../mobile/tests/unit/client-binding.test.ts | 15 +++- packages/mobile/tests/unit/engine.test.ts | 70 +++++++++++++++++++ 10 files changed, 161 insertions(+), 30 deletions(-) create mode 100644 .changeset/local-harmonyos-phone.md diff --git a/.changeset/local-harmonyos-phone.md b/.changeset/local-harmonyos-phone.md new file mode 100644 index 0000000000..6a54a7bb8c --- /dev/null +++ b/.changeset/local-harmonyos-phone.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/mobile": 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. diff --git a/docs/mobile.mdx b/docs/mobile.mdx index b2e9170ef7..9ffafd0923 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -12,9 +12,19 @@ phones connected to your machine. It is built on [agent-device](https://github.com/callstack/agent-device). Tests use the same `agent`, `screen`, and `expect` APIs as browser tests. -## Local HarmonyOS prototype +## Local HarmonyOS phone -This fork accepts `mobile({ platform: 'harmonyos' })` for a connected, unlocked phone with the target app already installed. Set `app.bundleId` to its bundle name. The [counter example](https://github.com/fryandev/e2e/tree/prototype/harmonyos-local/packages/mobile/examples/harmonyos) exercises app launch, ArkUI test IDs, button taps by role and name, and text assertions. +Connect an unlocked phone and check that DevEco's `hdc list targets` shows its serial. Sign and install the ArkUI app on the phone before running the suite. Add a target to your config: + +```ts +{ + name: 'harmony-phone', + engine: mobile({ platform: 'harmonyos' }), + app: { bundleId: 'com.example.e2ecounter' }, +} +``` + +With several phones connected, set `device` to one HDC serial or pass `--device ` to the run. Each target uses one worker. The counter example in `packages/mobile/examples/harmonyos` uses `app.open()`, finds an ArkUI button by role and name, taps it and checks the updated text by test ID. The engine also exposes screenshots. HAP installation, video recording, hosted devices and emulator provisioning are outside this target's supported operations. ## Set up diff --git a/docs/reference/mobile.mdx b/docs/reference/mobile.mdx index 0575bcd48c..e213fe866d 100644 --- a/docs/reference/mobile.mdx +++ b/docs/reference/mobile.mdx @@ -80,7 +80,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-`, with `-` for a `launch()` host | | [`snapshot`](#snapshot) | `'full' \| 'interactive'` | `'full'` | @@ -96,7 +96,7 @@ declaration. | --- | --- | | `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, else every option. | | `INVALID_CONFIG` | `settle` or `transition` is not a non-negative integer of milliseconds (`settle` may also be `false`). | @@ -112,7 +112,8 @@ readonly platform: MobilePlatform; mobile({ platform: 'android' }); ``` -- `'ios'` or `'android'`. Required. +- 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 diff --git a/packages/mobile/README.md b/packages/mobile/README.md index 3916fe29b1..51e58c01f4 100644 --- a/packages/mobile/README.md +++ b/packages/mobile/README.md @@ -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 [ArkUI counter example](./examples/harmonyos/README.md) 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 diff --git a/packages/mobile/src/engine.ts b/packages/mobile/src/engine.ts index cfb3a8b18f..2fb1333ad5 100644 --- a/packages/mobile/src/engine.ts +++ b/packages/mobile/src/engine.ts @@ -37,7 +37,7 @@ export function buildEngine(surface: AgentDeviceSurface): MobileEngine { ...(surface.pool.size === undefined ? {} : { workers: surface.pool.size }), // `e2e run --device` names the device `prepare` binds; see DevicePool.prepare. ...(surface.pool.selectsDevice ? { selectsDevice: true } : {}), - launchArgumentValues: true, + launchArgumentValues: !harmony, prepare: (info) => surface.pool.prepare(info), finish: (info) => surface.pool.finish(info), doctor: (info) => surface.doctor(info), @@ -63,12 +63,13 @@ export function buildEngine(surface: AgentDeviceSurface): MobileEngine { // `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)), + ...(!harmony && { + back: (operation) => surface.back(operation, surface.inputBudget('back', operation)), + reset: (operation) => surface.reset(operation), + 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)), @@ -97,8 +98,8 @@ export function mobile(options: MobileOptions): MobileEngine { 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, @@ -127,8 +128,11 @@ const LOOPBACK_NOTES: Readonly> = { */ function validateApp(app: EngineAppDeclaration, { targetName }: EngineAppCheckInfo, platform: MobilePlatform): void { const where = `target "${targetName}"`; - if (platform === 'harmonyos' && app.appPath !== undefined) { - throw new ConfigurationError('INVALID_CONFIG', 'The local HarmonyOS target requires an installed app and app.bundleId.'); + 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( diff --git a/packages/mobile/src/options.ts b/packages/mobile/src/options.ts index bb4cc02a5c..74798fb63c 100644 --- a/packages/mobile/src/options.ts +++ b/packages/mobile/src/options.ts @@ -54,7 +54,8 @@ export interface MobileOptions { /** Platform the target's device runs. */ readonly platform: MobilePlatform; /** - * Device to use: a simulator or emulator by name, simulator UDID, or + * A HarmonyOS target accepts one HDC serial or phone name. Omit it when exactly one phone is connected. + * On iOS and Android, device to use: 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 diff --git a/packages/mobile/src/pool.ts b/packages/mobile/src/pool.ts index a5d211d811..da2d41be18 100644 --- a/packages/mobile/src/pool.ts +++ b/packages/mobile/src/pool.ts @@ -83,6 +83,22 @@ export function isDeviceList(device: unknown): device is readonly string[] { /** The source the `device` option names: a configured pool, the booted devices, or a provider's leases. */ function sourceFor(options: MobileOptions, createClient: ClientFactory, session: SessionNamer): DeviceSource { const { device } = options; + if (options.platform === 'harmonyos') { + if (device !== undefined && typeof device !== 'string') { + throw new ConfigurationError('INVALID_CONFIG', 'A HarmonyOS target drives one local phone. Set device to its HDC serial or name.'); + } + const selected = device === undefined ? undefined : namedDevice(device); + return { + size: 1, + fallback: [selected === undefined ? {} : { device: selected }], + async bind(info) { + const name = session(info, 0); + const client = createClient(name); + const phone = await harmonyPhone(client, info.device ?? selected, name, info.signal); + return [{ deviceId: phone.id }]; + }, + }; + } if (device === undefined) return new BootedDevices(options.platform, createClient, session); if (typeof device === 'string') return new ConfiguredDevices([namedDevice(device)]); if (isDeviceList(device)) { @@ -94,12 +110,26 @@ function sourceFor(options: MobileOptions, createClient: ClientFactory, session: } return new ConfiguredDevices(device.map(namedDevice)); } - if (options.platform === 'harmonyos') { - throw new ConfigurationError('INVALID_CONFIG', 'HarmonyOS requires a locally connected device.'); - } return new LeasedDevices(asDeviceProvider(device), { platform: options.platform }); } +/** Resolve the HDC serial before warm-up or direct worker initialization can open an app. */ +export async function harmonyPhone(client: AgentDeviceClient, selected: string | undefined, session: string, signal: AbortSignal) { + const inventory = await runCommand('devices', () => client.devices.list({ platform: 'harmonyos' }), signal); + const connected = inventory.filter((item) => item.platform === 'harmonyos' && item.kind === 'device' && item.target === 'mobile' && item.booted); + const byId = connected.find((item) => item.id === selected); + const matches = byId ? [byId] : connected.filter((item) => selected === undefined || item.name === selected); + if (matches.length !== 1) { + const reason = matches.length === 0 ? 'No connected HarmonyOS phone matches' : 'Multiple connected HarmonyOS phones match'; + throw new EngineError('ENGINE_FAILURE', `${reason} ${selected ?? 'this target'}. Check hdc list targets and select one HDC serial with --device.`, { retryable: false }); + } + const phone = matches[0]!; + if (phone.claimedBy && phone.claimedBy.session !== session) { + throw new EngineError('ENGINE_FAILURE', `HarmonyOS phone ${phone.id} is held by session "${phone.claimedBy.session}". Close that session before running this target.`, { retryable: false }); + } + return phone; +} + /** A device name from the `device` option; a blank one would select no device, and the daemon would refuse several booted ones as ambiguous. */ function namedDevice(device: unknown): string { if (typeof device !== 'string' || device.trim() === '') { @@ -156,9 +186,6 @@ class BootedDevices implements DeviceSource { ); } if (chosen.length === 0) { - if (this.platform === 'harmonyos') { - throw new EngineError('ENGINE_FAILURE', 'Connect a HarmonyOS phone and check hdc list targets.', { retryable: false }); - } info.log(`no booted ${this.platform} device; agent-device boots a shut-down one (iPhone over iPad over Apple TV on iOS, phone or tablet over TV on Android, then newest OS, then name)`); return [{}]; } @@ -336,7 +363,7 @@ export class DevicePool { */ async prepare(info: EnginePrepareInfo): Promise { if (info.slots === 0) return {}; - const source = info.device === undefined ? this.source : new ConfiguredDevices([namedDevice(info.device)]); + const source = info.device === undefined || this.options.platform === 'harmonyos' ? this.source : new ConfiguredDevices([namedDevice(info.device)]); const bindings = [...(await source.bind(info))]; // Only a device the pool found may move: a named device (the config's or `e2e run --device`'s) or a provider's lease is what the run asked for. const found = source instanceof BootedDevices ? source : undefined; diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index 615102868f..812783a966 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -70,7 +70,7 @@ import { maskPng } from './png.ts'; import { mobileDoctor } from './doctor.ts'; import { deviceLabel, pinnedApp, type SlotBinding } from './bindings.ts'; import { assertAppId } from './links.ts'; -import { bootRequest, DevicePool, deviceSelection, type DeviceSelection } from './pool.ts'; +import { bootRequest, DevicePool, deviceSelection, harmonyPhone, type DeviceSelection } from './pool.ts'; import { recordLease, travelledLease, type DeviceLease, type RecordingDeviceProvider } from './provider.ts'; import { invalidState, @@ -685,11 +685,7 @@ export class AgentDeviceSurface { ? undefined : { provider, lease, runId: info.runId, targetName: info.targetName, env: info.env }; if (this.options.platform === 'harmonyos') { - const devices = await this.command('devices', (client) => client.devices.list({ platform: 'harmonyos' }), info.signal); - const selected = binding?.deviceId ?? binding?.device; - const matches = devices.filter((item) => item.booted && (selected === undefined || item.id === selected || item.name === selected)); - if (matches.length !== 1) throw invalidState('Expected one connected HarmonyOS phone matching the device selection.'); - const phone = matches[0]!; + const phone = await harmonyPhone(this.client, binding?.deviceId ?? binding?.device, session, info.signal); this.device = { deviceId: phone.id }; this.bound = { session, deviceId: phone.id, deviceName: phone.name }; } else { @@ -1045,6 +1041,7 @@ export class AgentDeviceSurface { * with no data; a plain install replaces the binary and keeps its data. */ async installApp(appPath: string | undefined, options: InstallAppOptions, signal: AbortSignal): Promise { + if (this.options.platform === 'harmonyos') throw unsupported('device.installApp is unavailable on HarmonyOS. Install the signed app before the run and set app.bundleId.'); const build = appPath ?? this.app.appPath; if (build === undefined) throw invalidState("installApp needs a build: pass a path, or name one with the target's app.appPath"); const resolved = path.resolve(this.projectRoot, build); @@ -1086,6 +1083,7 @@ export class AgentDeviceSurface { * `app.open()` asks for an install instead of launching an app that is gone. */ async uninstallApp(app: string | undefined, signal: AbortSignal): Promise { + if (this.options.platform === 'harmonyos') throw unsupported('device.uninstallApp is unavailable on HarmonyOS. Install the signed app before the run and set app.bundleId.'); const target = this.appArgument('uninstallApp', app); const result = await this.command(`uninstall ${target}`, (client) => client.apps.uninstall({ ...this.selection(), app: target }), signal); // agent-device resolves display names too: compare the id it removed, not only the string the caller passed. diff --git a/packages/mobile/tests/unit/client-binding.test.ts b/packages/mobile/tests/unit/client-binding.test.ts index c9a1c85c95..9dd054cb4f 100644 --- a/packages/mobile/tests/unit/client-binding.test.ts +++ b/packages/mobile/tests/unit/client-binding.test.ts @@ -6,7 +6,7 @@ import { createFakeClient } from '../helpers/fake-client.ts'; const created = vi.hoisted(() => vi.fn()); vi.mock('agent-device', async (original) => ({ ...await original(), - createAgentDeviceClient: (config: unknown) => { created(config); return createFakeClient().client; }, + createAgentDeviceClient: (config: unknown) => { created(config); return createFakeClient({ 'devices.list': () => [] }).client; }, })); afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks(); }); @@ -38,3 +38,16 @@ it('carries a slot\'s kept session through the worker environment, and reads a b expect(decodeBindings(encodeBindings(kept))).toEqual(kept); expect(decodeBindings(JSON.stringify([{ deviceId: 'B', session: 7 }]))).toBeUndefined(); }); + +it('resolves HarmonyOS inventory on this host when an ambient remote daemon is configured', async () => { + vi.stubEnv('AGENT_DEVICE_DAEMON_BASE_URL', 'https://remote.example'); + const engine = mobile({ platform: 'harmonyos' }); + const preparation = engine.prepare!({ + runId: 'run', targetName: 'phone', projectRoot: '/project', app: {}, slots: 1, headed: false, + env: {}, signal: new AbortController().signal, log() {}, + }); + await expect(preparation).rejects.toThrow(/No connected HarmonyOS phone/); + expect(created).toHaveBeenCalledWith({ + session: 'e2e-phone-0', daemonBaseUrl: '', daemonAuthToken: '', daemonTransport: 'auto', + }); +}); diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index dad020ae67..74853b54f2 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -97,6 +97,76 @@ async function screenRootOf(h: Harness): Promise { return (await h.engine.observe!(operation())).root; } +describe('local HarmonyOS target', () => { + const phone = { id: 'HDC-A', name: 'Mate', platform: 'harmonyos', kind: 'device', target: 'mobile', booted: true }; + const other = { ...phone, id: 'HDC-B' }; + const info = { runId: 'run-1', targetName: 'phone', projectRoot: PROJECT_ROOT, slots: 3, env: {}, signal: new AbortController().signal, headed: false, log: () => undefined }; + + it('exposes the installed-app session, tap and screenshots', () => { + const engine = mobile({ platform: 'harmonyos' }); + expect(engine.workers).toBe(1); + expect(engine.actions).toEqual(['tap']); + expect(engine.pointerActions).toEqual(['tap']); + expect(engine.keyboard).toBeUndefined(); + expect(Object.keys(engine.session!)).toEqual(['restart']); + expect(Object.keys(engine.artifacts!)).toEqual(['screenshot']); + expect(() => engine.validateApp!({ bundleId: 'com.example.counter' }, info)).not.toThrow(); + for (const app of [{}, { appPath: 'signed.hap' }, { bundleId: 'counter', appPath: 'signed.hap' }]) { + expect(() => engine.validateApp!(app, info)).toThrowError(expect.objectContaining({ code: 'INVALID_CONFIG' })); + } + expect(() => mobile({ platform: 'harmonyos', device: ['HDC-A', 'HDC-B'] })).toThrow(/one local phone/); + }); + + it.each([ + { selection: undefined, inventory: [phone] }, + { selection: 'Mate', inventory: [phone] }, + { selection: 'HDC-A', inventory: [other, phone] }, + ])('resolves $selection to the HDC serial before warm-up and retains it for the worker', async ({ selection, inventory }) => { + const h = harness({ platform: 'harmonyos', device: selection, bundleId: 'com.example.counter' }); + h.fake.respond('devices.list', () => inventory); + const prepared = await h.prepare(info); + expect(prepared?.workers).toBe(1); + expect(h.fake.lastArgs('apps.open')).toEqual({ platform: 'harmonyos', serial: 'HDC-A', app: 'com.example.counter' }); + await boot(h, 'phone', 0, prepared?.env); + expect(h.surface.selection()).toEqual({ platform: 'harmonyos', serial: 'HDC-A' }); + expect(h.fake.methods()).toEqual(['devices.list', 'apps.open', 'devices.list']); + }); + + it('lets --device override the configured serial before opening an app', async () => { + const h = harness({ platform: 'harmonyos', device: phone.id }); + h.fake.respond('devices.list', () => [phone, other]); + await h.prepare({ ...info, device: other.id }); + expect(h.fake.lastArgs('apps.open')).toMatchObject({ serial: other.id }); + }); + + it.each([ + { inventory: [], error: /No connected/ }, + { inventory: [{ ...phone, kind: 'emulator' }], error: /No connected/ }, + { inventory: [{ ...phone, booted: false }], error: /No connected/ }, + { inventory: [phone, other], error: /Multiple connected/ }, + { inventory: [{ ...phone, claimedBy: { session: 'busy' } }], error: /held by session "busy"/ }, + ])('refuses an unusable inventory before any device action', async ({ inventory, error }) => { + const h = harness({ platform: 'harmonyos' }); + h.fake.respond('devices.list', () => inventory); + await expect(h.prepare(info)).rejects.toThrow(error); + await expect(boot(h)).rejects.toThrow(error); + expect(h.fake.methods()).toEqual(['devices.list', 'devices.list']); + }); + + it('refuses install, reinstall and uninstall before sending an app command', async () => { + const h = harness({ platform: 'harmonyos' }); + const signal = info.signal; + for (const call of [ + () => h.surface.installApp(undefined, {}, signal), + () => h.surface.installApp('signed.hap', { reinstall: true }, signal), + () => h.surface.uninstallApp('com.example.counter', signal), + ]) { + await expect(call()).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY', retryable: false }); + } + expect(h.fake.methods()).toEqual([]); + }); +}); + describe('manifest', () => { it('declares observation, actions, location, artifacts, the device fixture, and session hooks', () => { const pinned = harness().engine; From 4c9600676509aba99f0e9df0388e13e530b762fd Mon Sep 17 00:00:00 2001 From: fryandev <268098688+fryandev@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:38:44 +0800 Subject: [PATCH 3/8] docs(mobile): record reproducible HarmonyOS device verification --- packages/mobile/examples/harmonyos/README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/mobile/examples/harmonyos/README.md b/packages/mobile/examples/harmonyos/README.md index e8570ae688..1a0e975c11 100644 --- a/packages/mobile/examples/harmonyos/README.md +++ b/packages/mobile/examples/harmonyos/README.md @@ -21,11 +21,15 @@ pnpm install --frozen-lockfile pnpm --filter @e2e-dev/core run build pnpm --filter e2e run build pnpm --filter @e2e-dev/mobile run build -(cd packages/mobile/examples/harmonyos && node ../../../e2e/dist/cli/bin.js run) +cd packages/mobile/examples/harmonyos +node ../../../e2e/dist/cli/bin.js doctor +node ../../../e2e/dist/cli/bin.js run ``` [The test](./tests/counter.e2e.ts) launches the app, expects “计数:0”, taps the “加一” button, and expects “计数:1”. It needs no model or credentials. The runner writes its report to `.e2e/report.json` in the example directory. ## Verification -On November 24, 2026, the test passed on a physical Huawei Mate 70 Air running HarmonyOS 7 (API 26), with agent-device 0.21.41. This covers the local device and installed-app path. Cloud devices, HAP deployment, agent replay, emulator provisioning, and other HarmonyOS versions are outside this prototype's tested scope. +On November 24, 2026, [commit 7107dd86](https://github.com/fryandev/e2e/commit/7107dd8672cc6cc1dc325ac28b947ce827f80d89) passed the counter test on a physical Huawei Mate 70 Air running HarmonyOS 7 (API 26) with agent-device 0.21.42. The runner recorded four passing steps in 4.74 seconds: app launch, the initial text assertion, a button tap and the updated text assertion. + +On this setup, `e2e doctor` detected one connected phone and HDC 3.2.0f. A locked phone can still pass these checks. If launching the app reports that the screen is locked, unlock the phone and rerun the test. From d49931ec8cb70bc1d395f7a7879dee65f0cbbf21 Mon Sep 17 00:00:00 2001 From: fryandev <268098688+fryandev@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:29:44 +0800 Subject: [PATCH 4/8] docs(mobile): cover local HarmonyOS in the bundled setup guide --- .changeset/local-harmonyos-phone.md | 3 ++- plugins/e2e/skills/e2e/SKILL.md | 2 +- plugins/e2e/skills/e2e/references/setup.md | 5 +++++ skills/e2e/SKILL.md | 2 +- skills/e2e/references/setup.md | 5 +++++ 5 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.changeset/local-harmonyos-phone.md b/.changeset/local-harmonyos-phone.md index 6a54a7bb8c..b4132d9b20 100644 --- a/.changeset/local-harmonyos-phone.md +++ b/.changeset/local-harmonyos-phone.md @@ -1,5 +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. +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. diff --git a/plugins/e2e/skills/e2e/SKILL.md b/plugins/e2e/skills/e2e/SKILL.md index f493bc086e..517be4b2f2 100644 --- a/plugins/e2e/skills/e2e/SKILL.md +++ b/plugins/e2e/skills/e2e/SKILL.md @@ -8,7 +8,7 @@ description: Writes, runs, and debugs web, mobile, and desktop end-to-end tests e2e runs UI and API tests that mix agent instructions (`agent.act`, `agent.assert`, `agent.waitFor`, `agent.extract`) with exact actions and checks (`screen`, `app`, `browser`, `device`, `request`, `expect`). Engines: -`@e2e-dev/web` (browsers), `@e2e-dev/mobile` (iOS/Android), and +`@e2e-dev/web` (browsers), `@e2e-dev/mobile` (iOS, Android, and local HarmonyOS phones), and `@e2e-dev/desktop` (macOS prototype). ## Start here: pick the reference for the job diff --git a/plugins/e2e/skills/e2e/references/setup.md b/plugins/e2e/skills/e2e/references/setup.md index ea4d14cdd8..76f7ccf1f5 100644 --- a/plugins/e2e/skills/e2e/references/setup.md +++ b/plugins/e2e/skills/e2e/references/setup.md @@ -305,6 +305,11 @@ export default { } satisfies E2EConfig; ``` +- For an installed ArkUI app, use `mobile({ platform: 'harmonyos' })` + and set `app.bundleId`. Connect and unlock one phone, or select its HDC + serial with `--device` when several are connected. Use `app.open()`, tap + by role or test ID, and assert the updated text. Install the signed app + before the run. - `app.bundleId` is what `app.open()` launches fresh. `app.appPath` is the `.app` or `.apk` under test, but the engine installs nothing: a worker fixture with `auto: true` calls `device.installApp()` once per device. diff --git a/skills/e2e/SKILL.md b/skills/e2e/SKILL.md index ccd1789663..b9c13e95a6 100644 --- a/skills/e2e/SKILL.md +++ b/skills/e2e/SKILL.md @@ -19,7 +19,7 @@ metadata: e2e runs UI and API tests that mix agent instructions (`agent.act`, `agent.assert`, `agent.waitFor`, `agent.extract`) with exact actions and checks (`screen`, `app`, `browser`, `device`, `request`, `expect`). Engines: -`@e2e-dev/web` (browsers), `@e2e-dev/mobile` (iOS/Android), and +`@e2e-dev/web` (browsers), `@e2e-dev/mobile` (iOS, Android, and local HarmonyOS phones), and `@e2e-dev/desktop` (macOS prototype). ## Start here: pick the reference for the job diff --git a/skills/e2e/references/setup.md b/skills/e2e/references/setup.md index ea4d14cdd8..76f7ccf1f5 100644 --- a/skills/e2e/references/setup.md +++ b/skills/e2e/references/setup.md @@ -305,6 +305,11 @@ export default { } satisfies E2EConfig; ``` +- For an installed ArkUI app, use `mobile({ platform: 'harmonyos' })` + and set `app.bundleId`. Connect and unlock one phone, or select its HDC + serial with `--device` when several are connected. Use `app.open()`, tap + by role or test ID, and assert the updated text. Install the signed app + before the run. - `app.bundleId` is what `app.open()` launches fresh. `app.appPath` is the `.app` or `.apk` under test, but the engine installs nothing: a worker fixture with `auto: true` calls `device.installApp()` once per device. From eaf8805271fa9af14cdc3b8763e4a880ce710382 Mon Sep 17 00:00:00 2001 From: fryandev <268098688+fryandev@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:33:29 +0800 Subject: [PATCH 5/8] fix(mobile): use the resolved HDC serial in HarmonyOS doctor --- packages/mobile/src/doctor.ts | 18 ++++++++++++++---- packages/mobile/tests/unit/doctor.test.ts | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/packages/mobile/src/doctor.ts b/packages/mobile/src/doctor.ts index fa00daf74a..f03c16def3 100644 --- a/packages/mobile/src/doctor.ts +++ b/packages/mobile/src/doctor.ts @@ -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. */ @@ -42,9 +42,19 @@ export async function mobileDoctor(options: MobileOptions, createClient: ClientF const reported = new Set(); for (const name of devices) { info.log(`agent-device doctor${name === undefined ? '' : ` for "${name}"`}`); + let binding: Pick | undefined = name === undefined ? undefined : { device: name }; + if (options.platform === 'harmonyos') { + try { + const phone = await harmonyPhone(client, name, 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) { diff --git a/packages/mobile/tests/unit/doctor.test.ts b/packages/mobile/tests/unit/doctor.test.ts index 2a9ad62122..77d021f15c 100644 --- a/packages/mobile/tests/unit/doctor.test.ts +++ b/packages/mobile/tests/unit/doctor.test.ts @@ -75,6 +75,25 @@ describe('doctor', () => { ]); }); + it.each(['HDC-A', 'Phone A'])('resolves the selected HarmonyOS phone %s to its HDC serial', async (device) => { + const h = doctorHarness({ platform: 'harmonyos', device }); + const phone = { platform: 'harmonyos', kind: 'device', target: 'mobile', booted: true }; + h.fake.respond('devices.list', () => [ + { ...phone, id: 'HDC-B', name: 'Phone B' }, { ...phone, id: 'HDC-A', name: 'Phone A' }, + ]); + await h.engine.doctor!(info(h)); + expect(h.fake.lastArgs('command.doctor')).toMatchObject({ platform: 'harmonyos', serial: 'HDC-A' }); + expect(h.fake.lastArgs('command.doctor')).not.toHaveProperty('device'); + }); + + it('reports a missing HarmonyOS phone as a failed device check', async () => { + const h = doctorHarness({ platform: 'harmonyos', device: 'HDC-A' }); + h.fake.respond('devices.list', () => []); + expect(await h.engine.doctor!(info(h))).toEqual([ + { id: 'device', status: 'fail', message: expect.stringContaining('HDC-A') }, + ]); + }); + it('selects a device by UDID', async () => { const udid = '78D5CEB4-D3A1-48E2-9AFD-6F8A99A824DA'; const h = doctorHarness({ device: udid }); From 7df05172f3e904c5a642c58a969fd81cbf05d75b Mon Sep 17 00:00:00 2001 From: fryandev <268098688+fryandev@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:35:05 +0800 Subject: [PATCH 6/8] fix(mobile): normalize HDC screenshot bytes before masking or writing PNG --- packages/mobile/src/png.ts | 8 ++++++++ packages/mobile/src/surface.ts | 7 +++++-- packages/mobile/tests/unit/png.test.ts | 11 ++++++++++- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/packages/mobile/src/png.ts b/packages/mobile/src/png.ts index 184f5164d9..1a7deeada1 100644 --- a/packages/mobile/src/png.ts +++ b/packages/mobile/src/png.ts @@ -23,6 +23,14 @@ interface Rgba { readonly data: Uint8Array; } +/** HDC may write JPEG data even when the capture path ends in .png. */ +export function harmonyScreenshotPng(bytes: Uint8Array): Uint8Array { + if (bytes[0] === 0xff && bytes[1] === 0xd8) { + return new Transformer(bytes).pngSync({ filterType: FilterType.Adaptive }); + } + return bytes; +} + /** Paints each requested rectangle opaque black, rounding outward and clipping to the image. */ export function maskPng(bytes: Uint8Array, rects: readonly Rect[]): Uint8Array { if (rects.length === 0) return bytes; diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index 73cf8f831d..5b640732d5 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -70,7 +70,7 @@ import { } from './nodes.ts'; import { keyboardDragStart, keyboardShownIn, type KeyboardUnknown } from './keyboard.ts'; import { DEVICE_PERMISSIONS, type AgentDeviceClient, type ClientFactory, type DevicePermission, type LaunchPermissions, type MobileOptions, type MobilePlatform, type PermissionState } from './options.ts'; -import { maskPng } from './png.ts'; +import { harmonyScreenshotPng, maskPng } from './png.ts'; import { above, clipTo, dragToEdge, EDGE_DIRECTION, regionSignature } from './scroll-to.ts'; import { mobileDoctor } from './doctor.ts'; import { deviceLabel, deviceSelection, pinnedApp, type DeviceSelection, type SlotBinding } from './bindings.ts'; @@ -2076,7 +2076,10 @@ export class AgentDeviceSurface { - return this.captureScreenshot(signal, async (shot, file) => new Uint8Array(readFileSync(shot.path ?? file)), capture, budget); + return this.captureScreenshot(signal, async (shot, file) => { + const bytes = readFileSync(shot.path ?? file); + return this.options.platform === 'harmonyos' ? harmonyScreenshotPng(bytes) : new Uint8Array(bytes); + }, capture, budget); } /** diff --git a/packages/mobile/tests/unit/png.test.ts b/packages/mobile/tests/unit/png.test.ts index 8c2b512572..3fc35aff8b 100644 --- a/packages/mobile/tests/unit/png.test.ts +++ b/packages/mobile/tests/unit/png.test.ts @@ -1,6 +1,6 @@ import { FilterType, Transformer } from '@napi-rs/image'; import { describe, expect, it } from 'vitest'; -import { maskPng } from '../../src/png.ts'; +import { harmonyScreenshotPng, maskPng } from '../../src/png.ts'; import { decodePng, encodePng, rawPng, type DecodedPng } from '../helpers/png.ts'; function solid(width: number, height: number, channels: 3 | 4, value: number): DecodedPng { @@ -58,3 +58,12 @@ describe('screenshot masking', () => { expect([...masked.pixels.subarray(4, 8)]).toEqual([9, 9, 9, 255]); }); }); + +it('converts HDC JPEG captures to PNG and retains a native PNG', () => { + const png = encodePng(solid(4, 4, 4, 255)); + const jpeg = new Transformer(png).jpegSync(); + expect(harmonyScreenshotPng(png)).toBe(png); + const normalized = harmonyScreenshotPng(jpeg); + expect(Array.from(normalized.subarray(0, 8))).toEqual([137, 80, 78, 71, 13, 10, 26, 10]); + expect(decodePng(normalized)).toMatchObject({ width: 4, height: 4 }); +}); From 8f54dd0e832b8de9b2f724df165a53326a0a37b0 Mon Sep 17 00:00:00 2001 From: fryandev <268098688+fryandev@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:36:11 +0800 Subject: [PATCH 7/8] test(mobile): capture the HarmonyOS counter and record second-device verification --- packages/mobile/examples/harmonyos/README.md | 6 ++++-- packages/mobile/examples/harmonyos/tests/counter.e2e.ts | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/mobile/examples/harmonyos/README.md b/packages/mobile/examples/harmonyos/README.md index 1a0e975c11..1441e81370 100644 --- a/packages/mobile/examples/harmonyos/README.md +++ b/packages/mobile/examples/harmonyos/README.md @@ -10,7 +10,7 @@ Use a HarmonyOS stage-model phone project with bundle name `com.example.e2ecount devecocli create --app-name E2ECounter --bundle-name com.example.e2ecounter --api-level 26 ``` -Replace its `entry/src/main/ets/pages/Index.ets` with [Index.ets](./Index.ets), then sign and run it on the phone with DevEco Studio. Check that `hdc list targets` lists the phone. Use a single connected phone for the test below. +Replace its `entry/src/main/ets/pages/Index.ets` with [Index.ets](./Index.ets), then sign and run it on the phone with DevEco Studio. Check that `hdc list targets` lists the phone. With multiple phones connected, set the example’s `E2E_DEVICE` environment variable to the HDC serial of the phone running E2ECounter. ## Run from the fork @@ -26,10 +26,12 @@ node ../../../e2e/dist/cli/bin.js doctor node ../../../e2e/dist/cli/bin.js run ``` -[The test](./tests/counter.e2e.ts) launches the app, expects “计数:0”, taps the “加一” button, and expects “计数:1”. It needs no model or credentials. The runner writes its report to `.e2e/report.json` in the example directory. +[The test](./tests/counter.e2e.ts) launches the app, expects “计数:0”, taps the “加一” button, expects “计数:1”, and saves a screenshot named `counter-after-tap`. It needs no model or credentials. The runner writes its report to `.e2e/report.json` in the example directory. ## Verification On November 24, 2026, [commit 7107dd86](https://github.com/fryandev/e2e/commit/7107dd8672cc6cc1dc325ac28b947ce827f80d89) passed the counter test on a physical Huawei Mate 70 Air running HarmonyOS 7 (API 26) with agent-device 0.21.42. The runner recorded four passing steps in 4.74 seconds: app launch, the initial text assertion, a button tap and the updated text assertion. On this setup, `e2e doctor` detected one connected phone and HDC 3.2.0f. A locked phone can still pass these checks. If launching the app reports that the screen is locked, unlock the phone and rerun the test. + +On November 28, 2026, a local npm tarball built from [commit 7df05172](https://github.com/fryandev/e2e/commit/7df05172f3e904c5a642c58a969fd81cbf05d75b) passed on a second physical phone (ALT-AL10, API 26) with agent-device 0.21.44 and e2e 0.25.0. With two phones connected, `e2e doctor` selected the configured HDC serial. The counter passed all three runs with `--repeat-each 3`. Each run produced a 1080 × 2504 PNG after the tap. diff --git a/packages/mobile/examples/harmonyos/tests/counter.e2e.ts b/packages/mobile/examples/harmonyos/tests/counter.e2e.ts index 86f5d47a4f..9ab408fea1 100644 --- a/packages/mobile/examples/harmonyos/tests/counter.e2e.ts +++ b/packages/mobile/examples/harmonyos/tests/counter.e2e.ts @@ -7,4 +7,5 @@ test('increments the ArkUI counter', async ({ app, screen }) => { await expect(counter).toHaveText('计数:0'); await screen.getByRole('button', '加一').tap(); await expect(counter).toHaveText('计数:1'); + await app.screenshot('counter-after-tap'); }); From a621b2920b67331075d987fc51bd644161736517 Mon Sep 17 00:00:00 2001 From: fryandev <268098688+fryandev@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:29:49 +0800 Subject: [PATCH 8/8] fix(mobile): pin prepared HarmonyOS phones and verify engine screenshots --- docs/mobile.mdx | 61 ++++++++++++----- docs/reference/mobile.mdx | 2 +- packages/mobile/README.md | 6 +- packages/mobile/examples/harmonyos/Index.ets | 36 ---------- packages/mobile/examples/harmonyos/README.md | 37 ---------- .../mobile/examples/harmonyos/e2e.config.ts | 10 --- .../examples/harmonyos/tests/counter.e2e.ts | 11 --- packages/mobile/package.json | 2 +- packages/mobile/src/doctor.ts | 2 +- packages/mobile/src/engine.ts | 67 ++++++++++--------- packages/mobile/src/options.ts | 2 +- packages/mobile/src/pool.ts | 35 ++++++---- packages/mobile/src/surface.ts | 4 +- packages/mobile/tests/types/options.ts | 6 +- packages/mobile/tests/unit/engine.test.ts | 28 ++++++++ plugins/e2e/skills/e2e/references/setup.md | 4 +- skills/e2e/references/setup.md | 4 +- 17 files changed, 147 insertions(+), 170 deletions(-) delete mode 100644 packages/mobile/examples/harmonyos/Index.ets delete mode 100644 packages/mobile/examples/harmonyos/README.md delete mode 100644 packages/mobile/examples/harmonyos/e2e.config.ts delete mode 100644 packages/mobile/examples/harmonyos/tests/counter.e2e.ts diff --git a/docs/mobile.mdx b/docs/mobile.mdx index 3c8bdeacf9..ef2c729152 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -13,20 +13,6 @@ phones connected to your machine. It is built on [agent-device](https://github.com/callstack/agent-device). Tests use the same `agent`, `screen`, and `expect` APIs as browser tests. -## Local HarmonyOS phone - -Connect an unlocked phone and check that DevEco's `hdc list targets` shows its serial. Sign and install the ArkUI app on the phone before running the suite. Add a target to your config: - -```ts -{ - name: 'harmony-phone', - engine: mobile({ platform: 'harmonyos' }), - app: { bundleId: 'com.example.e2ecounter' }, -} -``` - -With several phones connected, set `device` to one HDC serial or pass `--device ` to the run. Each target uses one worker. The counter example in `packages/mobile/examples/harmonyos` uses `app.open()`, finds an ArkUI button by role and name, taps it and checks the updated text by test ID. The engine also exposes screenshots. HAP installation, video recording, hosted devices and emulator provisioning are outside this target's supported operations. - ## Set up Install Xcode with an iOS simulator runtime, or the Android SDK with an @@ -76,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 @@ -87,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: { @@ -573,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-` 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 @@ -630,6 +616,47 @@ with agent-device's message. second, and drops frames. +### 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 ` to the run. Each target uses one worker. For a counter +with a text node identified by `counterValue` and a button labelled “加一”: + +```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('计数:0'); + await screen.getByRole('button', '加一').tap(); + await expect(counter).toHaveText('计数:1'); + 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 diff --git a/docs/reference/mobile.mdx b/docs/reference/mobile.mdx index 07d8063750..f6ab7ebe0f 100644 --- a/docs/reference/mobile.mdx +++ b/docs/reference/mobile.mdx @@ -1466,7 +1466,7 @@ export interface DeviceSelection { | `DeviceSession.session` | `e2e--`, `e2e---` for a `launch()` host, or `-` 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). | +| `DeviceSelection` | The platform, then one of `device` (a name), `udid` (a simulator UDID), or `serial` (an Android or HDC serial). | ### Exported types diff --git a/packages/mobile/README.md b/packages/mobile/README.md index bc13c17359..4ea3224988 100644 --- a/packages/mobile/README.md +++ b/packages/mobile/README.md @@ -8,7 +8,7 @@ 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 [ArkUI counter example](./examples/harmonyos/README.md) to configure an installed app by bundle name and run it over HDC. +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 @@ -72,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 `-`, `e2e--` 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. | diff --git a/packages/mobile/examples/harmonyos/Index.ets b/packages/mobile/examples/harmonyos/Index.ets deleted file mode 100644 index ae1204bd8d..0000000000 --- a/packages/mobile/examples/harmonyos/Index.ets +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2026 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@Entry -@Component -struct Index { - @State count: number = 0; - - build() { - Column({ space: 20 }) { - Text(`计数:${this.count}`) - .id('counterValue') - .fontSize(32) - Button('加一') - .id('incrementButton') - .onClick(() => { - this.count += 1; - }) - } - .justifyContent(FlexAlign.Center) - .height('100%') - .width('100%') - } -} diff --git a/packages/mobile/examples/harmonyos/README.md b/packages/mobile/examples/harmonyos/README.md deleted file mode 100644 index 1441e81370..0000000000 --- a/packages/mobile/examples/harmonyos/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# ArkUI counter on a local HarmonyOS phone - -This prototype runs a deterministic test through the mobile engine against an installed ArkUI app. The test uses the public app, screen, and expect APIs. It requires a connected, unlocked phone, DevEco's hdc on PATH, and the repository's Node and pnpm toolchain. - -## Prepare the phone - -Use a HarmonyOS stage-model phone project with bundle name `com.example.e2ecounter`. For example, scaffold one outside this repository with DevEco CLI: - -```sh -devecocli create --app-name E2ECounter --bundle-name com.example.e2ecounter --api-level 26 -``` - -Replace its `entry/src/main/ets/pages/Index.ets` with [Index.ets](./Index.ets), then sign and run it on the phone with DevEco Studio. Check that `hdc list targets` lists the phone. With multiple phones connected, set the example’s `E2E_DEVICE` environment variable to the HDC serial of the phone running E2ECounter. - -## Run from the fork - -From the repository root: - -```sh -pnpm install --frozen-lockfile -pnpm --filter @e2e-dev/core run build -pnpm --filter e2e run build -pnpm --filter @e2e-dev/mobile run build -cd packages/mobile/examples/harmonyos -node ../../../e2e/dist/cli/bin.js doctor -node ../../../e2e/dist/cli/bin.js run -``` - -[The test](./tests/counter.e2e.ts) launches the app, expects “计数:0”, taps the “加一” button, expects “计数:1”, and saves a screenshot named `counter-after-tap`. It needs no model or credentials. The runner writes its report to `.e2e/report.json` in the example directory. - -## Verification - -On November 24, 2026, [commit 7107dd86](https://github.com/fryandev/e2e/commit/7107dd8672cc6cc1dc325ac28b947ce827f80d89) passed the counter test on a physical Huawei Mate 70 Air running HarmonyOS 7 (API 26) with agent-device 0.21.42. The runner recorded four passing steps in 4.74 seconds: app launch, the initial text assertion, a button tap and the updated text assertion. - -On this setup, `e2e doctor` detected one connected phone and HDC 3.2.0f. A locked phone can still pass these checks. If launching the app reports that the screen is locked, unlock the phone and rerun the test. - -On November 28, 2026, a local npm tarball built from [commit 7df05172](https://github.com/fryandev/e2e/commit/7df05172f3e904c5a642c58a969fd81cbf05d75b) passed on a second physical phone (ALT-AL10, API 26) with agent-device 0.21.44 and e2e 0.25.0. With two phones connected, `e2e doctor` selected the configured HDC serial. The counter passed all three runs with `--repeat-each 3`. Each run produced a 1080 × 2504 PNG after the tap. diff --git a/packages/mobile/examples/harmonyos/e2e.config.ts b/packages/mobile/examples/harmonyos/e2e.config.ts deleted file mode 100644 index 537df47f08..0000000000 --- a/packages/mobile/examples/harmonyos/e2e.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { mobile } from '@e2e-dev/mobile'; -import type { E2EConfig } from 'e2e'; - -export default { - targets: [{ - name: 'harmony-phone', - engine: mobile({ platform: 'harmonyos', device: process.env['E2E_DEVICE'] }), - app: { bundleId: 'com.example.e2ecounter' }, - }], -} satisfies E2EConfig; diff --git a/packages/mobile/examples/harmonyos/tests/counter.e2e.ts b/packages/mobile/examples/harmonyos/tests/counter.e2e.ts deleted file mode 100644 index 9ab408fea1..0000000000 --- a/packages/mobile/examples/harmonyos/tests/counter.e2e.ts +++ /dev/null @@ -1,11 +0,0 @@ -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('计数:0'); - await screen.getByRole('button', '加一').tap(); - await expect(counter).toHaveText('计数:1'); - await app.screenshot('counter-after-tap'); -}); diff --git a/packages/mobile/package.json b/packages/mobile/package.json index 7024fb0964..c7403a1212 100644 --- a/packages/mobile/package.json +++ b/packages/mobile/package.json @@ -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", diff --git a/packages/mobile/src/doctor.ts b/packages/mobile/src/doctor.ts index f03c16def3..31697524ba 100644 --- a/packages/mobile/src/doctor.ts +++ b/packages/mobile/src/doctor.ts @@ -45,7 +45,7 @@ export async function mobileDoctor(options: MobileOptions, createClient: ClientF let binding: Pick | undefined = name === undefined ? undefined : { device: name }; if (options.platform === 'harmonyos') { try { - const phone = await harmonyPhone(client, name, session, info.signal); + const phone = await harmonyPhone(client, binding, session, info.signal); binding = { deviceId: phone.id }; } catch (cause) { if (info.signal.aborted) throw cause; diff --git a/packages/mobile/src/engine.ts b/packages/mobile/src/engine.ts index 1eab69a199..ca8950937f 100644 --- a/packages/mobile/src/engine.ts +++ b/packages/mobile/src/engine.ts @@ -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'; @@ -27,9 +27,42 @@ const surfaces = new WeakMap(); export interface MobileEngine extends EngineHandle {} +type MobileCapabilities = Pick; + +function platformCapabilities(surface: AgentDeviceSurface): MobileCapabilities { + const session: NonNullable = { restart: (operation) => surface.restart(operation) }; + const artifacts: NonNullable = { + 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(surface: AgentDeviceSurface): MobileEngine { - const harmony = surface.options.platform === 'harmonyos'; const handle = defineEngine({ name: 'mobile', version: ownVersion(), @@ -38,9 +71,7 @@ export function buildEngine(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: !harmony, - launchArgumentValues: !harmony, + ...platformCapabilities(surface), prepare: (info) => surface.pool.prepare(info), finish: (info) => surface.pool.finish(info), doctor: (info) => surface.doctor(info), @@ -54,34 +85,8 @@ export function buildEngine(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: harmony ? ['tap'] : DEVICE_ACTIONS, performAt: (point, action, operation) => surface.performAt(point, action, operation, surface.inputBudget(action.kind, operation)), - pointerActions: harmony ? ['tap'] : DEVICE_POINTER_ACTIONS, - ...(!harmony && { 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: { - restart: (operation) => surface.restart(operation), - ...(!harmony && { - back: (operation) => surface.back(operation, surface.inputBudget('back', operation)), - reset: (operation) => surface.reset(operation), - 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)), - ...(!harmony && { - startVideo: (operation) => surface.startVideo(operation), - stopVideo: (operation) => surface.stopVideo(operation), - }), - }, fixtures: { device: (context) => createDeviceFixture(surface, context), }, diff --git a/packages/mobile/src/options.ts b/packages/mobile/src/options.ts index 4473c7bfcd..a1cd6d5f3c 100644 --- a/packages/mobile/src/options.ts +++ b/packages/mobile/src/options.ts @@ -83,7 +83,7 @@ export interface MobileOptions * held until run end. At run end, the engine closes its sessions and the * provider releases its leases. */ - readonly device?: string | readonly string[] | DeviceProvider | undefined; + readonly device?: string | (Platform extends 'harmonyos' ? never : readonly string[] | DeviceProvider) | undefined; /** * agent-device session name, before the worker slot: slot `n` drives its * device under `-`, `e2e--` by default. One run diff --git a/packages/mobile/src/pool.ts b/packages/mobile/src/pool.ts index 5838f58d9d..f2f12d22b1 100644 --- a/packages/mobile/src/pool.ts +++ b/packages/mobile/src/pool.ts @@ -58,17 +58,7 @@ function sourceFor(options: MobileOptions, createClient: ClientFactory, session: if (device !== undefined && typeof device !== 'string') { throw new ConfigurationError('INVALID_CONFIG', 'A HarmonyOS target drives one local phone. Set device to its HDC serial or name.'); } - const selected = device === undefined ? undefined : namedDevice(device); - return { - size: 1, - fallback: [selected === undefined ? {} : { device: selected }], - async bind(info) { - const name = session(info, 0); - const client = createClient(name); - const phone = await harmonyPhone(client, info.device ?? selected, name, info.signal); - return [{ deviceId: phone.id }]; - }, - }; + return new HarmonyPhones(device === undefined ? undefined : namedDevice(device), createClient, session); } if (device === undefined) return new BootedDevices(options.platform, createClient, session); if (typeof device === 'string') return new ConfiguredDevices([namedDevice(device)]); @@ -84,12 +74,29 @@ function sourceFor(options: MobileOptions, createClient: ClientFactory, session: return new LeasedDevices(asDeviceProvider(device), { platform: options.platform }); } +/** A single connected phone. Preparation records its serial for the worker. */ +class HarmonyPhones implements DeviceSource { + readonly size = 1; + readonly fallback: readonly SlotBinding[]; + + constructor(private readonly selected: string | undefined, private readonly createClient: ClientFactory, private readonly session: SessionNamer) { + this.fallback = [selected === undefined ? {} : { device: selected }]; + } + + async bind(info: EnginePrepareInfo): Promise { + const name = this.session(info, 0); + const phone = await harmonyPhone(this.createClient(name), { device: info.device ?? this.selected }, name, info.signal); + return [{ deviceId: phone.id }]; + } +} + /** Resolve the HDC serial before warm-up or direct worker initialization can open an app. */ -export async function harmonyPhone(client: AgentDeviceClient, selected: string | undefined, session: string, signal: AbortSignal) { +export async function harmonyPhone(client: AgentDeviceClient, binding: Pick | undefined, session: string, signal: AbortSignal) { + const selected = binding?.deviceId ?? binding?.device; const inventory = await runCommand('devices', () => client.devices.list({ platform: 'harmonyos' }), signal); const connected = inventory.filter((item) => item.platform === 'harmonyos' && item.kind === 'device' && item.target === 'mobile' && item.booted); const byId = connected.find((item) => item.id === selected); - const matches = byId ? [byId] : connected.filter((item) => selected === undefined || item.name === selected); + const matches = byId ? [byId] : connected.filter((item) => binding?.deviceId === undefined && (selected === undefined || item.name === selected)); if (matches.length !== 1) { const reason = matches.length === 0 ? 'No connected HarmonyOS phone matches' : 'Multiple connected HarmonyOS phones match'; throw new EngineError('ENGINE_FAILURE', `${reason} ${selected ?? 'this target'}. Check hdc list targets and select one HDC serial with --device.`, { retryable: false }); @@ -334,7 +341,7 @@ export class DevicePool { */ async prepare(info: EnginePrepareInfo): Promise { if (info.slots === 0) return {}; - const source = info.device === undefined || this.options.platform === 'harmonyos' ? this.source : new ConfiguredDevices([namedDevice(info.device)]); + const source = info.device === undefined || this.source instanceof HarmonyPhones ? this.source : new ConfiguredDevices([namedDevice(info.device)]); const bindings = [...(await source.bind(info))]; // Only a device the pool found may move: a named device (the config's or `e2e run --device`'s) or a provider's lease is what the run asked for. const found = source instanceof BootedDevices ? source : undefined; diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index 5b640732d5..54f1dec061 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -691,7 +691,7 @@ export class AgentDeviceSurface { if (this.options.platform !== 'ios') { - throw unsupported('device.clearKeychain resets an iOS simulator keychain; Android has none to reset'); + throw unsupported('device.clearKeychain requires an iOS simulator'); } await this.command( 'device.clearKeychain', diff --git a/packages/mobile/tests/types/options.ts b/packages/mobile/tests/types/options.ts index a48d99a432..39a70ccd66 100644 --- a/packages/mobile/tests/types/options.ts +++ b/packages/mobile/tests/types/options.ts @@ -19,7 +19,11 @@ const farm = { ({ platform: 'ios', device: farm }) satisfies MobileOptions; ({ id: 'lease-1', daemon: { baseUrl: 'http://10.0.0.7:4700' } }) satisfies DeviceLease; -({ platform: 'harmonyos' }) satisfies MobileOptions; +({ platform: 'harmonyos', device: 'HDC-A' }) satisfies MobileOptions<'harmonyos'>; +// @ts-expect-error HarmonyOS accepts one local phone per target. +({ platform: 'harmonyos', device: ['HDC-A'] }) satisfies MobileOptions<'harmonyos'>; +// @ts-expect-error a hosted provider cannot lease a local HarmonyOS target. +({ platform: 'harmonyos', device: farm }) satisfies MobileOptions<'harmonyos'>; // @ts-expect-error web belongs to the browser engine. ({ platform: 'web' }) satisfies MobileOptions; // @ts-expect-error the snapshot mode is full or interactive. diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index f5419b2a84..d8d74eac1a 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -11,6 +11,7 @@ import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { AppError, formatPinnedRef } from 'agent-device'; +import { Transformer } from '@napi-rs/image'; import { decodePng, encodePng } from '../helpers/png.ts'; import type { EngineFixtureContext, EngineSnapshot, FixtureOperations, LocatorExpression, OperationContext, SemanticNode } from '@e2e-dev/core/engine'; import { describeEngine } from '@e2e-dev/core/engine'; @@ -122,6 +123,7 @@ describe('local HarmonyOS target', () => { for (const app of [{}, { appPath: 'signed.hap' }, { bundleId: 'counter', appPath: 'signed.hap' }]) { expect(() => engine.validateApp!(app, info)).toThrowError(expect.objectContaining({ code: 'INVALID_CONFIG' })); } + // @ts-expect-error JavaScript callers can still supply an invalid pool. expect(() => mobile({ platform: 'harmonyos', device: ['HDC-A', 'HDC-B'] })).toThrow(/one local phone/); }); @@ -140,6 +142,32 @@ describe('local HarmonyOS target', () => { expect(h.fake.methods()).toEqual(['devices.list', 'apps.open', 'devices.list']); }); + it('fails when the prepared phone disconnects even if another phone has its serial as a name', async () => { + const h = harness({ platform: 'harmonyos', device: phone.id }); + h.fake.respond('devices.list', () => [phone]); + const prepared = await h.prepare(info); + h.fake.respond('devices.list', () => [{ ...other, name: phone.id }]); + await expect(boot(h, 'phone', 0, prepared?.env)).rejects.toThrow(/No connected HarmonyOS phone matches HDC-A/); + expect(h.fake.methods()).toEqual(['devices.list', 'apps.open', 'devices.list']); + }); + + it('saves HDC JPEG captures as PNG artifacts through the engine', async () => { + const h = harness({ platform: 'harmonyos', device: phone.id }); + h.fake.respond('devices.list', () => [phone]); + h.fake.respond('capture.snapshot', () => ({ nodes: [], text: '' })); + const jpeg = Transformer.fromRgbaPixels(new Uint8Array(16).fill(255), 2, 2).jpegSync(); + h.fake.respond('capture.screenshot', (args) => { + const file = (args as { path: string }).path; + writeFileSync(file, jpeg); + return { path: file, logicalWidth: 2, logicalHeight: 2 }; + }); + await openAttempt(h); + const file = await h.engine.artifacts!.screenshot('counter', operation()); + const bytes = readFileSync(path.join(artifactsDir, file)); + expect([...bytes.subarray(0, 8)]).toEqual([137, 80, 78, 71, 13, 10, 26, 10]); + expect(decodePng(bytes)).toMatchObject({ width: 2, height: 2 }); + }); + it('lets --device override the configured serial before opening an app', async () => { const h = harness({ platform: 'harmonyos', device: phone.id }); h.fake.respond('devices.list', () => [phone, other]); diff --git a/plugins/e2e/skills/e2e/references/setup.md b/plugins/e2e/skills/e2e/references/setup.md index 9557e0eed3..4c6edfdb80 100644 --- a/plugins/e2e/skills/e2e/references/setup.md +++ b/plugins/e2e/skills/e2e/references/setup.md @@ -281,8 +281,8 @@ provider packages, not the runner. `CI` switches CI defaults (topic `@e2e-dev/mobile` drives iOS simulators, Android emulators, and connected phones through [agent-device](https://github.com/callstack/agent-device); -it needs Xcode with a simulator runtime or the Android SDK with an emulator. -Run `npx e2e doctor` to check. Name a phone in `device` by the name +iOS needs Xcode, Android needs the Android SDK, and a local HarmonyOS phone needs HDC. +Run `npx e2e doctor` to check. Name an iOS or Android phone in `device` by the name `npx agent-device devices` lists, not its UDID or serial. On an iPhone, device settings (permissions, `clearState`, network, location, appearance, biometrics, keychain) and the clipboard are simulator-only. diff --git a/skills/e2e/references/setup.md b/skills/e2e/references/setup.md index 9557e0eed3..4c6edfdb80 100644 --- a/skills/e2e/references/setup.md +++ b/skills/e2e/references/setup.md @@ -281,8 +281,8 @@ provider packages, not the runner. `CI` switches CI defaults (topic `@e2e-dev/mobile` drives iOS simulators, Android emulators, and connected phones through [agent-device](https://github.com/callstack/agent-device); -it needs Xcode with a simulator runtime or the Android SDK with an emulator. -Run `npx e2e doctor` to check. Name a phone in `device` by the name +iOS needs Xcode, Android needs the Android SDK, and a local HarmonyOS phone needs HDC. +Run `npx e2e doctor` to check. Name an iOS or Android phone in `device` by the name `npx agent-device devices` lists, not its UDID or serial. On an iPhone, device settings (permissions, `clearState`, network, location, appearance, biometrics, keychain) and the clipboard are simulator-only.