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

# 移动端

> iOS 和 Android 的移动端引擎选项与 device 测试夹具。

`@e2e-dev/mobile` 是用于 iOS 模拟器、Android 模拟器和已连接手机的引擎，通过 [agent-device](https://github.com/callstack/agent-device) 驱动。它提供 `device` 测试夹具。`agent`、`app`、`screen` 和 `expect` 的用法与其他环境相同；本页介绍设备测试目标特有的功能。

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

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

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

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

- 从 `@e2e-dev/mobile` 导入 `test`，为 `device` 提供类型。在同时运行于网页端的测试套件中声明 `requires: ['device']`。
- 在 `e2e init` 中选择 **Mobile (iOS/Android)**，添加此包及“设置”应用示例。iOS 需要 Xcode 和模拟器；Android 需要 Android SDK 和模拟器。
- 此包包含兼容版本的 `agent-device`，无需单独安装。

## 参考

### 引擎

`mobile(options)` 为一个平台创建引擎。为每个被测平台创建一个引擎，并在包含平台特定标签或操作的测试上使用 `platforms: ['ios']` 或 `platforms: ['android']`。

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

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

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

`mobile()` 接受 `MobileOptions`，指定引擎操作哪些设备以及如何操作。被测应用由测试目标的 `app` 指定，不是引擎选项；参阅[被测应用](#the-app-under-test)。

| 选项 | 类型 | 默认值 |
| --- | --- | --- |
| [`platform`](#platform) | `'ios' \| 'android'` | 必填 |
| [`device`](#device-option) | `string \| readonly string[] \| DeviceProvider` | 所有已启动的设备 |
| [`session`](#session) | `string` | `e2e-<target name>` |
| [`snapshot`](#snapshot) | `'full' \| 'interactive'` | `'full'` |
| [`settle`](#settle) | `number \| false` | `150` |
| [`transition`](#transition) | `number` | `500` |
| [`videoTouches`](#videotouches) | `boolean` | `true` |

每个可选值也都接受 `undefined`，因此直接从 `process.env` 读取的值无需条件展开。以下各条目展示相应成员的声明。

| 抛出错误 | 发生条件 |
| --- | --- |
| `INVALID_CONFIG` | `device` 列表为空、`device` 名称为空白，或列表项为空白或非字符串。 |
| `INVALID_CONFIG` | `device` 值既不是字符串或列表，也不是有效的提供方：提供方没有非空 `name`、没有 `acquire()` 或 `release()`，或其 `record` 不是函数。 |
| `INVALID_CONFIG` | 缺少 `platform`，或其值不是 `'ios'` 或 `'android'`；匹配区分大小写。 |
| `INVALID_CONFIG` | 提供的 `snapshot` 值不是 `'full'` 或 `'interactive'`，或提供的 `videoTouches` 值不是布尔值。 |
| `INVALID_CONFIG` | 传入 `mobile()` 不接受的选项，例如 `mobile({ app })` 和其他旧的应用选项。如果疑似拼写错误，消息会指出最接近的已知选项，否则列出所有选项。 |
| `INVALID_CONFIG` | `settle` 或 `transition` 不是以毫秒为单位的非负整数（`settle` 也可以为 `false`）。 |

#### `platform`

```ts
/** Platform the target's device runs. */
readonly platform: MobilePlatform;
```

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

- `'ios'` 或 `'android'`。必填。

#### `device` 选项

```ts
/**
 * 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
 * files across every device at once. Omitted, the pool is every booted device
 * of the platform at `prepare` that no other agent-device session holds, as
 * many as the run has slots. A paired iPhone or iPad that is reachable (USB or network) counts as booted and
 * joins the pool. With none booted, agent-device boots a shut-down one: on
 * iOS an iPhone over an iPad over an Apple TV, on Android a phone or tablet
 * over a TV, then the newest OS, then name order (a stopped Android emulator
 * reports no OS version, so the name decides). With every booted one held,
 * `prepare` fails. A `DeviceProvider` leases hosted devices
 * instead: one per worker slot at `prepare`, each driven through the daemon
 * and client configuration the lease names. A replacement worker resumes a
 * healthy agent-device session on the same lease. Forced worker shutdown
 * can close the session. `device.closeApp()` ends the agent-device session,
 * allowing another session to take the device. If agent-device has not
 * confirmed a recording stop, the engine resets the recording before the
 * next attempt. This reset also ends the session. The provider lease stays
 * 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;
```

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

- 只要每个 `device` 条目指定不同的设备，两个工作进程就不会操作同一台设备。
- 未设置 `device` 时，会跳过其他工具通过自己的 agent-device 会话占用的已启动模拟器。没有被占用的已启动设备仍会加入设备池，例如你正在手动使用的设备：请明确指定设备，避免运行使用它。
- [托管设备](https://e2e.com/docs/zh/mobile#hosted-devices)介绍了 `DeviceProvider` 契约和提供方示例。

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

const iphones = mobile({
  platform: 'ios',
  device: ['iPhone 17', 'iPhone 17 Pro'],
});

export default {
  targets: [{ name: 'ios', engine: iphones, app: { bundleId: 'com.example.app' } }],
  workers: 2,
} satisfies E2EConfig;
```

#### `session`

```ts
/**
 * agent-device session name, before the worker slot: slot `n` drives its
 * device under `<session>-<n>`, `e2e-<target name>-<n>` by default. One run
 * per session at a time: concurrent runs on the same session interleave
 * taps.
 */
readonly session?: string | undefined;
```

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

#### `snapshot`

```ts
/**
 * What an observation captures. `full` (default) includes static text, so
 * judgments can read values; `interactive` keeps only actionable nodes and
 * is cheaper on screens with long lists.
 */
readonly snapshot?: 'full' | 'interactive' | undefined;
```

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

#### `settle`

```ts
/**
 * How long the UI must hold still after a tap, fill, screen scroll, or
 * back before the agent observes again, in milliseconds; `false` skips the
 * wait. The wait keeps that observation off a transition frame; the runner's
 * own polling (`expect`, actions waiting for their node) covers the rest,
 * so a short window suffices. Default 150.
 * Every frame of a running animation changes the tree, so a 150 ms
 * window still catches a transition in flight; raise it for slow devices
 * or apps that settle in stages, or lower it to 0 to keep only the first
 * re-observation. A test's steps do not settle, except `device.back()`:
 * `expect` verifies their outcome, and `transition` covers a control that is
 * still arriving.
 */
readonly settle?: number | false | undefined;
```

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

#### `transition`

```ts
/**
 * Wait before acting on a control that just appeared or moved, in
 * milliseconds. Default 500. Accessibility bounds cannot tell a sliding
 * control from a landed one (iOS reports the final frame at once, Android
 * the frame in flight), so the control is found again in a fresh snapshot
 * once the wait is over and acted on where it landed. Unmoved controls are
 * acted on immediately only when keyboard visibility is unchanged. Opening
 * or closing the keyboard also uses the remaining budget. Screen swipes in
 * tests wait out the remaining budget before scrolling. Raise it for slower
 * transitions.
 */
readonly transition?: number | undefined;
```

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

如果控件在等待期间变化，操作会在自身超时范围内重新查找控件，再执行操作。

[`device`](#device) 上的 `back`、`home`、`alert`、`dismissKeyboard`、`setOrientation` 和 `fold` 会改变屏幕，因此在此预算中与点击一样计为操作。随它们打开的屏幕一起出现的控件，会等待该预算耗尽后才接受下一次操作。

`fill` 和 `clear` 会在输入前重新读取字段。字段缺失、安全状态变化或捕获不完整时，会在修改前返回 `NODE_STALE`，然后在重新观察后重试。非输入测试目标返回 `UNSUPPORTED_CAPABILITY`。iOS 的 `other` 是平台未分类元素的类型；当它包含值或仅包含文本时，可以向其中输入，因为自绘字段（Compose Multiplatform、Flutter）可能以这种形式呈现。

#### `videoTouches`

```ts
/**
 * Whether a video recording draws agent-device's touch indicator where a
 * test tapped. Default `true`. `false` records the plain screen, and skips
 * the pass that draws the indicator once the recording stops: on a hosted
 * daemon such as Expo Simulators' that pass can outlast the attempt's
 * `cleanupTimeout`.
 */
readonly videoTouches?: boolean | undefined;
```

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

#### 被测应用

应用由测试目标的 `app` 指定：`bundleId`、`appPath`、`launchArguments`、`permissions`、`identity` 和 `environment` 的说明见[被测应用](https://e2e.com/docs/zh/reference/config#the-app-under-test)。

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

- 设备测试目标需要 `app.bundleId` 或 `app.appPath`。
- `app.open()` 重新启动测试目标的应用。尝试本身不会自动启动任何内容，因此测试会从上一个测试留下的应用状态开始。
- 测试目标声明 [`app.linkBase`](https://e2e.com/docs/zh/reference/config#linkbase) 时，`app.open(path)` 会将路径作为链接在应用中打开；否则 `app.open` 不接受路径，链接通过 [`device.openLink`](#openlink) 打开。
- `app.appPath` 是测试套件使用的构建产物。引擎不会自动安装任何内容：由测试套件在指定位置调用 [`device.installApp()`](#installapp) 安装。设备提供方会将其安装到租用的设备上。
- 未设置 `bundleId` 时，已安装的 bundle ID 或包名会成为 `app.open()` 启动的应用标识。
- 如果构建路径每次运行都会变化（例如包含版本号），声明 `identity`，让录制内容在重命名后仍然有效。

| 抛出错误 | 发生条件 |
| --- | --- |
| `INVALID_CONFIG` | 加载配置时：既没有 `app.bundleId` 也没有 `app.appPath`；设置了 `app.url`（尚不支持）；`bundleId` 中包含链接（测试通过 `device.openLink` 打开链接）；权限名称未知。 |
| `UNSUPPORTED_CAPABILITY` | 对未设置 `app.bundleId` 的测试目标，在安装构建产物前调用 `app.open()`、`app.restart()` 或 `app.clearState()`。 |

#### 启动参数和权限

每次重新启动指定应用时，都会应用 `app.launchArguments` 和 `app.permissions`，包括 `app.open()`、`app.restart()` 和 `app.clearState()`；后者会在清除数据时重置权限。

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

- iOS 将参数交给应用进程（`ProcessInfo.processInfo.arguments`）。Android 将其追加到 `am start`，因此 `['--ez', 'e2e', 'true']` 是一个布尔类型的 intent extra。
- 每项权限为 `grant`、`deny` 或 `reset`。在 iOS 上，`deny` 会记录拒绝，应用会直接收到拒绝结果，不显示提示；在 Android 上，它会撤销权限，应用再次请求时系统会重新询问。
- 权限在应用启动前按名称设置，不会先打开应用，因为 iOS 会终止权限发生变化的运行中应用，Android 会终止权限被撤销的应用。
- 预热不会传入启动参数，也不会更改权限。
- [`device.openApp(app, { relaunch: true, launchArguments, permissions })`](#openapp) 对任意应用的单次启动执行相同操作。

| 抛出错误 | 发生条件 |
| --- | --- |
| `INVALID_CONFIG` | `app.permissions` 中的权限名称不属于 `DevicePermission`（疑似拼写错误时指出最接近的名称），或状态不是 `grant`、`deny` 或 `reset`。在执行任何设备命令前失败。 |
| `INVALID_ARGUMENT` | `device.openApp` 中出现相同情况。 |

#### 启动和准备

设备在 `prepare` 中启动，每次运行一次，且在运行计时开始之前完成，因此 CI 中的冷启动不会计入 `launchTimeout`。

- [`device`](#device-option) 指定 `prepare` 使用哪些设备，以及引擎声明多少个工作进程。
- 在 iOS 上，`prepare` 通过 agent-device 的 `prepare ios-runner` 在每台设备上启动自动化运行器，让首次启动开销在第一个测试之前完成。
- 随后，在两个平台上，它都会在每台设备上打开一次测试目标的 `app.bundleId`。由测试套件自行安装的构建产物会在首次 `app.open()` 时启动；每次测试调用该方法时都会重新启动应用。
- 设备无法启动，或运行器繁忙、卡死或超过看门狗时限时，运行会在 `prepare` 阶段结束。
- 运行器因其他原因未启动时，会记录日志并留待第一次尝试处理，此时不会打开该设备上的应用。

每台设备会输出一行日志，记录各准备步骤的耗时，包括失败的步骤。冷启动的 iOS 模拟器示例：

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

- `boot` 是设备启动耗时，已启动的设备也需要几秒钟。
- `iOS runner` 是自动化运行器的启动耗时，仅限 iOS。
- `open <app>` 将应用置于前台，在冷启动设备上会启动应用。如果按上述规则跳过打开操作，则不显示此项。

普通的应用打开失败会单独记录一行日志，运行继续。该行会在设备耗时行之前输出，耗时行仍列出失败的 `open <app>` 步骤：

```text
ℹ E93FA5E5-1592-43C7-9149-F1B5FE0AD5F5: dev.e2e.not.installed did not open (open dev.e2e.not.installed failed: Simulator device failed to launch dev.e2e.not.installed. Hint: The app bundle is not installed on this simulator. Run install before open.); the first attempt opens it
```

<Note>
当步骤停止等待或运行被中断时，等待中的点击、双击、聚焦、选中或取消选中操作会被取消。这也包括用于关闭键盘提示的点击。

已经发送到设备的输入仍可能完成。其他命令可能在调用方超时后继续执行；下一次尝试会等待它们完成。
</Note>

#### 能力

| 契约成员 | 设备上的行为 |
| --- | --- |
| `observe` | 带矩形边界的无障碍树。元素类型按[角色](#roles)中的列表映射；`Switch` 或 `CheckBox`，以及 Android `RadioButton`，携带设备报告的 `checked` 状态；`SecureTextField` 或被 Android UIAutomator 标记为 `password` 的字段是安全的 `textbox`。iOS 字段保留与标签相同的值（无标签字段以其文本命名）；Android 将文本视图标签重复作为值的情况会被去除。无障碍标识符（iOS）或资源 ID（Android）是节点的 `testId`。Android 节点优先使用应用设置的内容描述命名（React Native 的 `accessibilityLabel`），否则使用文本；它的 `text` 是显示的内容，因此带标签的文本视图或已填写字段会用标签响应 `getByLabel`，用文本响应 `getByText`。字段提示是其 `placeholder` 属性，无论当前是否显示。Compose Multiplatform 在 iOS 上不报告占位符：空字段会将绘制的文本追加到标签中（`Name, Ada Lovelace`），其下有一个 `StaticText` 子节点，因此该文本被视为字段的 `placeholder`，子节点则省略。空字段没有值：Android 会标记正在显示的提示，XCTest 会将空 iOS 字段的占位符报告为值，因此值与占位符去除首尾空白后相同的 iOS 字段会被视为空，即使输入的文本恰好与占位符一致也是如此。有一项 Android 行为来自 agent-device，而非平台本身：`rect` 和所有坐标点都是屏幕物理像素；它报告的显示密度尚未应用。Android 的状态栏和导航栏、沿屏幕边缘占据全宽的 `com.android.systemui` 窗口，以及 agent-device 在该边缘区域单独报告的窄状态图标（时钟、信号、电池）会被省略；通知栏、系统对话框，以及两侧留有边距的悬浮通知或其他弹出层会保留。按需提供像素，并将每个安全节点的边界区域涂黑。 |
| `perform` | 支持 `tap`、`doubleTap`、`longPress`、`fill`、`clear`、`hover`、`check`、`uncheck`、`press`（`Enter`、`Space` 或单个字符）、`swipe`、`dragTo`，以及可编辑字段上的 `focus`。点击 `switch` 或 `checkbox` 时会落在最内层的控件上，因为 UIKit 将设置行报告为一个带标签的开关，真正的切换控件是其子节点。`check` 和 `uncheck` 需要 `checked` 状态。两个平台上的开关都会报告此状态，原生 Android `CheckBox` 也是如此；React Native 复选框或单选按钮只有在应用设置 `accessibilityState.checked` 时才会报告。没有状态的控件会产生 `UNSUPPORTED_CAPABILITY`，请改为点击。`doubleTap` 是两次按下，在 iOS 上间隔 284 至 285 ms（agent-device 的 XCTest 点击节奏）：agent-device 自己的双击手势在 React Native `Pressable` 上只会被接收为一次按下。时间窗口为 300 ms 或更短的检测器可能会将这两次按下视为两次单击。`longPress` 默认按住一秒，除非测试传入 `duration`；这超过了 React Native `Pressable` 的 500 ms `delayLongPress`，以及应用设置的更长阈值。agent-device 自己的默认按住时间较短，会被这些控件识别为点击。未声明 `selectOption`、`setInputFiles`、`scrollIntoView` 和 `secondaryTap`，也未声明 `tapModifiers`，因此带 `modifiers` 的 `tap` 或 `doubleTap` 会产生 `UNSUPPORTED_CAPABILITY`。如果节点已被新快照替换，操作会重新查找节点，而不会操作其他元素。 |
| `performAt` | 支持在屏幕坐标点执行 `tap`、`doubleTap`、`longPress` 和 `swipeTo`，因此 `screen.tapAt`、`screen.doubleTapAt`、`tap({ position })`、`screen.swipe({ from, to })` 以及智能体的 `tap_at` 能操作树中未列出的控件。不支持在坐标点执行 `hover`、`secondaryTap` 或 `dragTo`：触控在没有节点时不提供这些操作，因此 `hover_at` 需要已列出的控件。 |
| `keyboard` | 向聚焦字段执行 `type` 和 `press`，对应智能体不带测试目标的 `type` 和 `press`，以及 `type_at` 和 `press_at` 的回退操作；还支持 `dismiss`，对应智能体的 `dismiss_keyboard`。 |
| `locate` | 支持所有 `screen` 查询。文本和标签查询返回最内层匹配项，因为设备会沿树向上重复它们（React Native 输入框由宿主视图和内部字段组成，两者都有标签）。在 Android 上，当屏幕没有节点匹配完整 ID 时，字符串或 RegExp 测试 ID 查询也会匹配去掉 `<package>:id/` 前缀的资源 ID，适用于框架 `android` 之外的所有包。`screen.locator('id=…')` 是 agent-device 选择器，接受完整 ID。 |
| `validateApp` | 需要 `app.bundleId` 或 `app.appPath`，暂不接受 `app.url`，并提示如何从该平台的设备访问本机。具备任一项的测试目标就是 `native-app` 测试目标，因此 `requires: ['native-app']` 会选择设备测试目标。 |
| `session` | 支持 `back`、`restart`、`reset` 和 `openLink`；设置了 `app.linkBase` 的测试目标通过后者实现 `app.open(path)`。没有 `open`：不带路径的 `app.open()` 由 `restart` 实现，即重新启动指定应用；智能体的 `navigate` 动词不可用，`device.openLink(url)` 可打开深度链接或网页链接。 |
| `artifacts` | 脱敏截图位于 `screenshots/NNN-<label>.png` 下；无法脱敏的截图会失败，而不是写入。当尝试的[视频模式](https://e2e.com/docs/zh/reference/config#video)要求录制时，视频保存为 `video/video.mp4`，或使用设备提供方自己的录像。 |
| `location` | `<bundle id> / <screen title>`，即回放缓存的锚点。标题在 iOS 上来自导航栏，在 Android 上来自工具栏。 |
| `state` | 未声明。不支持 `test.setup` 和 `session:`。 |

### 设备

`device` 测试夹具提供确定性的设备管理。测试直接调用它来准备或断言设备状态。

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

| 成员 | 返回值 |
| --- | --- |
| [`unstable_raw`](#unstable_raw) | `DeviceSession` |
| [`locator`](#locator) | `Locator` |
| [`setNetwork`](#setnetwork) | `Promise<void>` |
| [`setAirplaneMode`](#setairplanemode) | `Promise<void>` |
| [`setPermission`](#setpermission) | `Promise<void>` |
| [`setLocation`](#setlocation) | `Promise<void>` |
| [`clearLocation`](#clearlocation) | `Promise<void>` |
| [`setAppearance`](#setappearance) | `Promise<void>` |
| [`setOrientation`](#setorientation) | `Promise<void>` |
| [`fold`](#fold) | `Promise<void>` |
| [`setBiometrics`](#setbiometrics) | `Promise<void>` |
| [`enrollBiometrics`](#enrollbiometrics) | `Promise<void>` |
| [`installApp`](#installapp) | `Promise<InstalledApp>` |
| [`openApp`](#openapp) | `Promise<void>` |
| [`openLink`](#openlink) | `Promise<void>` |
| [`closeApp`](#closeapp) | `Promise<void>` |
| [`clearKeychain`](#clearkeychain) | `Promise<void>` |
| [`foregroundApp`](#foregroundapp) | `Promise<ForegroundApp>` |
| [`home`](#home) | `Promise<void>` |
| [`back`](#back) | `Promise<void>` |
| [`alert`](#alert) | `Promise<void>` |
| [`dismissKeyboard`](#dismisskeyboard) | `Promise<void>` |
| [`clipboard`](#clipboard) | `Promise<string>` |
| [`setClipboard`](#setclipboard) | `Promise<void>` |

每个异步方法都会记录为名为 `device.<method>` 的步骤，受 `config.actionTimeout` 限制。`back`、`home`、`alert`、`dismissKeyboard`、`setOrientation` 和 `fold` 在 [`transition`](#transition) 预算中计为操作。以下各条目展示相应成员的声明；它们使用的类型见[类型](#device-fixture)。

| 抛出错误 | 发生条件 |
| --- | --- |
| `APP_NOT_OPEN` | 会话丢失。 |
| `ACTION_FAILED` | 超过 `actionTimeout`。 |
| `UNSUPPORTED_CAPABILITY` | 平台无法执行该命令。 |
| `ENGINE_FAILURE` | 其他情况，附带 agent-device 的消息。设备自身报告的超时（启动、运行器连接）会保留其文本和提示。繁忙或卡死的 iOS 自动化运行器会指出自身及恢复方法（参阅[故障排查](https://e2e.com/docs/zh/mobile#troubleshooting)）。 |

#### `unstable_raw`

```ts
/**
 * The raw driver session this test drives, for what the methods here do
 * not cover. Calls through `client` bypass e2e: they are not steps, so the
 * report and trace leave them out, the agent's cache does not replay them,
 * their arguments reach the driver unredacted, and nothing waits for the
 * screen to settle after one. Unstable: it may change or go away in any
 * release.
 */
readonly unstable_raw: DeviceSession;
```

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

`client` 的类型为 `DeviceSessionClient`，由 `@e2e-dev/mobile` 导出。其操作不稳定，可能在任意版本中变化。工作进程释放会话后，读取 `unstable_raw` 或 `client` 会抛出 `INVALID_STATE`。

#### `locator`

```ts
/**
 * A locator from an agent-device selector (`'id=SW_VERSION_SPECIFIER'`,
 * `'role=text label="26.2"'`), for nodes the closed `screen` query
 * vocabulary cannot name. Same polling and strictness as any locator.
 */
locator(selector: string): Locator;
```

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

选择器术语及其规则来自 agent-device，与 `agent-device find ... list` 使用的规则相同：

- 术语：`id`、`role`、`text`、`label`、`value`、`appname`、`windowtitle`，以及标志 `visible`、`hidden`、`editable`、`selected`、`focused`、`enabled`、`hittable`。
- `role` 接受 agent-device 的类型，即 `agent-device snapshot` 输出的角色：`button`、`text`、`text-field`、`navigation-bar`、`scroll-area`、`switch`、`image`。它不是 `getByRole` 的角色（`textbox`）。
- 文本术语会在合并空白字符后进行不区分大小写的比较。
- `visible` 表示节点可被点击或拥有非空边框；`hidden` 与之相反。
- `text` 读取第一个非空的标签、值或标识符。

<Note>
对匹配多个节点的选择器执行操作会失败，而 agent-device 操作会跳过存在歧义的 `||` 分支。
</Note>

#### `setNetwork`

```ts
/**
 * Switches an Android device's Wi-Fi. Cellular data stays on, so an
 * emulator hands the app over to its cellular link; `setAirplaneMode(true)`
 * cuts both. On iOS `offline` is `UNSUPPORTED_CAPABILITY`, since a
 * simulator shares the Mac's network and simctl can only repaint its status
 * bar; `online` sends nothing there, so a cleanup hook shared with Android
 * passes.
 */
setNetwork(state: 'online' | 'offline'): Promise<void>;
```

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

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | 在 iOS 上使用 `offline`。 |

#### `setAirplaneMode`

```ts
/**
 * Switches an Android device's airplane mode, Wi-Fi and cellular together;
 * Android 11 or newer. On iOS, as for `setNetwork`, `true` is
 * `UNSUPPORTED_CAPABILITY` and `false` sends nothing.
 */
setAirplaneMode(enabled: boolean): Promise<void>;
```

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

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | 在 iOS 上使用 `true`。 |

#### `setPermission`

```ts
/**
 * Grants, denies, or resets one permission for the pinned app, which need
 * not be running. A change terminates a running app on iOS, a revoke one
 * on Android, so it goes before the `app.open()` a test starts with.
 */
setPermission(permission: DevicePermission, state: PermissionState): Promise<void>;
```

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

- `permission` 是 [`DevicePermission`](#device-fixture)；`state` 为 `grant`、`deny` 或 `reset`。

| 抛出错误 | 发生条件 |
| --- | --- |
| `INVALID_ARGUMENT` | 权限名称不属于 `DevicePermission`（疑似拼写错误时指出最接近的名称），或状态不是 `grant`、`deny` 或 `reset`。在执行任何设备命令前失败。 |

#### `setLocation`

```ts
/** Sets the simulated location, switching location services on first on Android. */
setLocation(coordinates: { latitude: number; longitude: number }): Promise<void>;
```

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

#### `clearLocation`

```ts
/** Turns simulated location off; on Android that is location services off, until the next `setLocation`. */
clearLocation(): Promise<void>;
```

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

#### `setAppearance`

```ts
/** Sets the system appearance. */
setAppearance(mode: 'light' | 'dark'): Promise<void>;
```

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

#### `setOrientation`

```ts
/** Rotates the device. */
setOrientation(orientation: DeviceOrientation): Promise<void>;
```

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

- `'portrait'`、`'portrait-upside-down'`、`'landscape-left'` 或 `'landscape-right'`。

#### `fold`

```ts
/**
 * Puts a foldable simulator or emulator in a hinge pose. On the iPhone Duo
 * it resolves once agent-device reads the angle back from CoreDevice at
 * that pose, typically 10 to 16 seconds later; `closed` lights the outer
 * display, `half-open` (a 130° book) and `open` light the inner one. On a
 * foldable Android emulator it sets the emulator console posture and
 * resolves once the guest commits the matching device state, within a few
 * seconds; `half-open` is the profile's own angle there (90° on the Pixel
 * folds), and a fold to the cover display dismisses the lock screen it
 * raises. Either way the app window changes size, so the next observation
 * reads a new screen. Any device without a hinge is `UNSUPPORTED_CAPABILITY`.
 */
fold(pose: FoldPose): Promise<void>;
```

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

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | 设备没有铰链。 |

#### `setBiometrics`

```ts
/**
 * Simulates one biometric attempt on the open app. `faceid` and `touchid`
 * work on an iOS simulator; `fingerprint` works on an Android emulator and
 * on a phone that exposes `cmd fingerprint`. Any other pair is
 * `UNSUPPORTED_CAPABILITY`. An Android app's prompt reads the touch
 * only once the device has a screen lock and an enrolled fingerprint,
 * which `enrollBiometrics` cannot set up.
 */
setBiometrics(sensor: BiometricSensor, result: 'match' | 'nonmatch'): Promise<void>;
```

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

- `sensor` 为 `'faceid'`、`'touchid'` 或 `'fingerprint'`。

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | 在 iOS 上使用 `fingerprint`，在 Android 或 iOS 真机上使用 `faceid` 或 `touchid`，或在没有 `cmd fingerprint` 的 Android 手机上使用 `fingerprint`。 |

#### `enrollBiometrics`

```ts
/**
 * Enrolls or unenrolls the simulator's Face ID or Touch ID. On Android or a
 * physical iOS device it is `UNSUPPORTED_CAPABILITY`.
 */
enrollBiometrics(sensor: 'faceid' | 'touchid', enrolled: boolean): Promise<void>;
```

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

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | 在 Android 或 iOS 真机上进行任何调用。 |

#### `installApp`

```ts
/**
 * Installs a build (an iOS `.app` bundle or an Android `.apk`, resolved
 * against the project root) on the device; without a path, the target's
 * `app.appPath`. The engine installs nothing on its own, so a suite that runs
 * against a build calls this once per device, in a fixture or a test.
 * `reinstall: true` removes the app first so it starts with no data; a
 * plain install replaces the binary and keeps its data. Resolves to the
 * identity to `openApp` it by, which becomes the app `app.open()` launches
 * when the target's build is installed and no `app.bundleId` is pinned.
 */
installApp(appPath?: string, options?: InstallAppOptions): Promise<InstalledApp>;
```

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

- 用它安装本次运行的构建产物，或升级路径中的另一个构建产物。
- 解析出的 ID 是 agent-device 从构建产物读取的 bundle ID 或包名，否则为传入的 `app`。

| 抛出错误 | 发生条件 |
| --- | --- |
| `APP_NOT_OPEN` | 未传入路径且测试目标没有 `app.appPath`；或设置了 `reinstall: true`，但未传入 `app` 且未指定应用（没有 `app.bundleId`，构建产物尚未安装）。 |
| `ENGINE_FAILURE` | agent-device 未报告 ID，且未传入 `app`；此时会失败，不会将文件路径当作 ID。参阅[故障排查](https://e2e.com/docs/zh/mobile#troubleshooting)。 |

#### `openApp`

```ts
/**
 * Brings an app to the foreground by bundle id, package, or display name;
 * `relaunch` restarts it fresh. `launchArguments` and `permissions` apply
 * to this launch alone; the target's configured ones apply to a `relaunch`
 * of the pinned app, and to no foreground-only open. A link is
 * `INVALID_ARGUMENT` (`file:`, `data:`, `javascript:`, `view-source:`,
 * `blob:`, and `filesystem:` are `POLICY_DENIED`): `openLink` opens one.
 */
openApp(app: string, options?: OpenAppOptions): Promise<void>;
```

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

- 链接会在发送给设备前被拒绝，因为 agent-device 会将任何 `scheme:rest` 字符串作为 URL 打开。

| 抛出错误 | 发生条件 |
| --- | --- |
| `POLICY_DENIED` | `file:`、`data:`、`javascript:`、`view-source:`、`blob:` 或 `filesystem:` 链接。 |
| `INVALID_ARGUMENT` | 其他任何链接，消息会提示使用 `openLink`；或权限名称或状态无效（参阅[启动参数和权限](#launch-arguments-and-permissions)）。 |

#### `openLink`

```ts
/**
 * Opens a deep link (`myapp://orders/42`) or a web link (`https://...`)
 * into `app` (default: the pinned app), which the session observes
 * afterwards. iOS launches the app for a web link and then opens the URL;
 * a web link the app does not claim goes to Safari, and the next
 * observation brings the app back. Android starts the link on that
 * package. Without an app, Android lets the OS route the link; iOS needs
 * one (`INVALID_ARGUMENT` without). `file:`, `data:`, `javascript:`,
 * `view-source:`, `blob:`, and `filesystem:` links are `POLICY_DENIED`.
 */
openLink(url: string, options?: { app?: string }): Promise<void>;
```

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

- 用于免密链接登录和深度链接路由。
- 未指定应用时，Android 会将链接路由到经过验证的应用链接所属应用或浏览器，会话会跟随接收链接的包。
- 设备链接可以使用任意应用的自定义协议，因此规则会拒绝下列协议，而非像网页端那样只允许 http(s)。
- 报告显示链接时会去掉 userinfo（`user:password@` 或 `token@`）、查询参数和片段，因为这些部分可能携带登录信息或免密链接令牌。无法解析的字符串显示为 `<link>`，绝不会原样显示。
- 回放缓存以链接到达的位置为锚点；参阅[设备上的回放缓存](#replay-cache-on-a-device)。

| 抛出错误 | 发生条件 |
| --- | --- |
| `POLICY_DENIED` | `file:`、`data:`、`javascript:`、`view-source:`、`blob:` 或 `filesystem:` 链接。 |
| `INVALID_ARGUMENT` | 在 iOS 上未指定应用：未绑定应用的打开操作不会留下可观察的应用会话。 |
| `INVALID_ARGUMENT` | 字符串无法解析为绝对 URL。消息不会包含输入中的任何部分，因为其查询参数、路径或 userinfo 可能携带免密链接令牌。 |

#### `closeApp`

```ts
/**
 * Terminates the session's app and ends the session, so the next
 * `openApp` launches it fresh. Until then the screen is unobservable and
 * `foregroundApp` is `APP_NOT_OPEN`.
 */
closeApp(): Promise<void>;
```

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

- 下次 `openApp` 之前进行屏幕查询也会产生 `APP_NOT_OPEN`。

#### `clearKeychain`

```ts
/**
 * Resets the simulator's keychain, every app's, since simctl has no
 * per-app reset: what `app.clearState()` leaves behind (a session token, a
 * Firebase sign-in). iOS simulator only; Android is
 * `UNSUPPORTED_CAPABILITY`. Launch the app afterwards to see it signed out.
 */
clearKeychain(): Promise<void>;
```

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

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | 在 Android 上调用，在执行任何设备命令前失败。 |

#### `foregroundApp`

```ts
/**
 * The app the session is on. iOS answers from the session, not the
 * device, so it names the app the session opened even after `home()`;
 * Android reads the device's foreground activity. `APP_NOT_OPEN` once
 * `closeApp` ended the session.
 */
foregroundApp(): Promise<ForegroundApp>;
```

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

- 在 iOS 上，agent-device 的 `appstate` 不提供设备级别的结果。

| 抛出错误 | 发生条件 |
| --- | --- |
| `APP_NOT_OPEN` | `closeApp` 已结束会话。 |

#### `home`

```ts
/** Sends the device to its home screen. */
home(): Promise<void>;
```

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

#### `back`

```ts
/** Navigates back once (in-app back). */
back(): Promise<void>;
```

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

#### `alert`

```ts
/** Accepts or dismisses the visible system alert. */
alert(action: 'accept' | 'dismiss'): Promise<void>;
```

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

#### `dismissKeyboard`

```ts
/**
 * Dismisses the soft keyboard: the keyboard's own dismiss key where it has
 * one (Android, iPad), else the way a user does it on an iPhone, a short
 * drag that a scroll view turns into a dismissal, horizontal first and
 * vertical second, stopping as soon as the keyboard is gone. Each drag
 * starts at the point nearest the centre of the screen that no control in
 * the captured accessibility tree covers, inside a scroll view when the
 * screen has one, to avoid pressing a button or toggling a checkbox. A
 * control the tree leaves out, such as pressable text, can still be hit.
 * The simulator's "Speed up your typing" tip goes through its Continue
 * button first. A screen with no clear point
 * above the keyboard, or a keyboard that outlives both drags, fails with
 * `UNSUPPORTED_CAPABILITY`; the message names the alternatives (the app's
 * own Done or close control, or pressing Enter on the field).
 */
dismissKeyboard(): Promise<void>;
```

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

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | 键盘上方的每个点（屏幕有滚动视图时，在滚动视图内）都落在控件上，或两次拖动后键盘仍未消失。 |

#### `clipboard`

```ts
/** Reads the clipboard. */
clipboard(): Promise<string>;
```

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

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | Android 构建没有用于剪贴板服务的 shell 命令。 |

#### `setClipboard`

```ts
/** Writes the clipboard. */
setClipboard(text: string): Promise<void>;
```

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

| 抛出错误 | 发生条件 |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | Android 构建没有用于剪贴板服务的 shell 命令。 |

### 智能体工具

`@e2e-dev/mobile/tools` 中的 `mobileTools(...engines)` 将设备工具添加到智能体的 `tools`。

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

- 至少传入一个引擎。在一次调用中传入所有设备引擎；工具会使用当前尝试的引擎。

| 工具 | 回放 | 用途 |
| --- | --- | --- |
| `open_app` | 缺口 | 按 ID 将应用置于前台，可选择重新启动。未指定 ID 时返回测试目标的应用。与 `device.openApp` 一样，拒绝链接。 |
| `swipe` | 缺口 | 在两个以逻辑像素表示的点之间自由滑动。 |
| `alert` | 缺口 | 接受或关闭系统警报；优先使用已列出的按钮，因为其点击可以回放。 |

| 抛出错误 | 发生条件 |
| --- | --- |
| `INVALID_STATE` | 引擎不是由 `mobile()` 返回的。在配置中，这会导致加载以 `CONFIG_LOAD_FAILED` 失败，其消息包含此错误。 |

工具在内置智能体步骤中失败时，会将 `Tool "<name>" failed: <message>` 作为调用结果返回给模型；步骤继续执行。当 `open_app` 未指定应用、测试目标没有 `app.bundleId`，且尚未安装其 `app.appPath` 构建产物时（既没有 `device.installApp()`，也没有设备提供方安装），它会以 `INVALID_STATE` 失败；指定未安装的应用或链接时，以 `INVALID_ARGUMENT` 失败；链接使用禁止的协议时，以 `POLICY_DENIED` 失败。没有设备尝试在运行，或同一工作进程中运行多个设备尝试时，任何工具都会以 `INVALID_STATE` 失败。

语法动词无需工具包。引擎声明的操作为智能体提供：

- `tap`、`double_tap`、`long_press`、`hover`、`type`、`press`、`check`、`scroll`、`drag`、按 `text` 执行的 `scroll_to`（翻动列表，直到包含该文本的行被绘制）、`back` 和 `dismiss_keyboard`。
- 像素工具 `screenshot`、`tap_at`、`hover_at`（仅限已列出的控件）、`drag_at`（仅限两个不同的已列出控件之间）、`type_at` 和 `press_at`。坐标操作可以点击无障碍树中不存在的控件。
- `type_secret`，仅填入步骤声明的机密值。

设备上不支持 `right_click`、`select`、按节点 ID 执行的 `scroll_to`、`upload` 或 `navigate`，也不提供 `select_at`。

<Note>
对于引擎无法证明已完成遮罩的像素，会以 `MASKING_UNPROVEN` 拒绝提供。无障碍捕获失败仍会停止观察。设备截图的遮罩依赖该次捕获中的安全字段边界，因此缺少这些边界时，引擎无法证明回退截图是安全的。
</Note>

#### `unstable_deviceSession`

`@e2e-dev/mobile/tools` 中的 `unstable_deviceSession(...engines)` 将当前尝试的 `DeviceSession` 提供给自定义工具，与测试通过 [`device.unstable_raw`](#unstable_raw) 读取的是同一个对象。其 `client` 绑定到引擎的守护进程、租约和每个工作进程的会话，用于 e2e 尚未封装的能力。其 `client` 的类型为 `DeviceSessionClient`。以下示例假设当前驱动支持 `settings.update`。

```ts

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

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

- 与 `mobileTools` 一样，传入配置声明的所有设备引擎。在尝试之外调用会抛出 `INVALID_STATE`。
- 将 `selection` 展开到调用中，即使会话尚未打开应用，也能操作该工作进程的设备，与引擎自身的调用相同。
- 客户端调用不算步骤：报告显示工具调用，不显示客户端具体执行了什么；缓存回放会实时执行 `mutates: true` 的工具。
- 与 `unstable_raw` 一样，客户端调用会跳过 e2e 的保护措施。工具返回的快照或截图不会脱敏或添加遮罩，即使已经填入机密值也是如此；调用后不会等待屏幕稳定；调用会改变设备状态的工具必须声明 `mutates: true`。
- 与 `unstable_raw` 一样，它可能在任意版本中变化。

## 角色

设备上的 `getByRole` 匹配每种元素类型映射到的角色。未列出的类型保留其自身名称，并转换为小写短横线形式（`picker-wheel`），因此只有该名称本身就是 `getByRole` 角色时才会匹配（`group`、`table`）。平台报告为可编辑的节点是 `textbox`，除非它已映射为 `combobox`。

| 角色 | iOS | Android |
| --- | --- | --- |
| `button` | `Button` | `Button`、`ImageButton`、`MaterialButton` |
| `link` | `Link` | |
| `textbox` | `TextField`、`SearchField`、`TextView`、`SecureTextField` | `EditText`、`AutoCompleteTextView`、`TextInputEditText`、`SearchView` |
| `combobox` | | `Spinner` |
| `switch` | `Switch`、`Toggle` | `Switch`、`SwitchCompat`、`SwitchMaterial`、`ToggleButton` |
| `checkbox` | `CheckBox` | `CheckBox`、`MaterialCheckBox` |
| `radio` | `RadioButton` | `RadioButton` |
| `radiogroup` | `RadioGroup` | `RadioGroup` |
| `slider` | `Slider` | `SeekBar`、`Slider` |
| `spinbutton` | `Stepper` | `NumberPicker` |
| `progressbar` | `ProgressIndicator` | `ProgressBar` |
| `status` | `ActivityIndicator` | |
| `image` | `Image`、`ImageView` | `ImageView` |
| `heading` | `Heading`、`Header` | 标记为标题的视图 |
| `list` | | `RecyclerView`、`ListView`、`AbsListView`（React Native 的 `FlatList`）、`GridView` |
| `listitem` | `Cell`、`ListItem`、`TableCell`、`CollectionCell` | |
| `row` | `TableRow` | |
| `tablist` | `TabBar`、`TabGroup`、`SegmentedControl` | `TabLayout`、`TabWidget`、`BottomNavigationView` |
| `tab` | `Tab`、`TabBarItem`、`TabBarButton`，以及 `TabBar` 或 `SegmentedControl` 中的 `Button` | `TabLayout$TabView`、`BottomNavigationItemView` |
| `menu` | `Menu` | |
| `menubar` | `MenuBar` | |
| `menuitem` | `MenuItem`、`MenuBarItem`、`MenuButton` | |
| `toolbar` | `Toolbar` | `Toolbar` |
| `alert` | `Alert` | |
| `dialog` | `Dialog`、`Sheet`、`ActionSheet` | |
| `navigation` | `NavigationBar` | |
| `group` | | `ScrollView`、`ViewGroup`、`View`、`ComposeView`、`ViewFactoryHolder`、`CardView`，以及其他任何 `*Layout` |

对于平台没有对应类型的角色，React Native 在 iOS 上将其写入无障碍值（`checkbox, unchecked`），在 Android 上写入角色描述（`Tab List`）。带有以下描述之一的节点会用该角色替代其类型映射的角色：`alert`、`checkbox`、`combo box`、`menu`、`menu bar`、`menu item`、`progress bar`、`radio button`、`radio group`、`scroll bar`、`spin button`、`switch`、`tab`、`tab list`、`timer` 和 `tool bar`。`scroll bar` 和 `timer` 产生的 `scrollbar` 和 `timer` 角色不是 `getByRole` 角色。在 iOS 上，只有 `Other` 携带此类描述，角色后面的状态词设置 `checked` 和 `expanded`；只有这些词之后的内容才是节点的值。

iOS 的 `StaticText` 和 `Text` 以及 Android 的 `TextView` 对应 `text`，Android 的 `WebView` 对应 `document`。两者都不是 `getByRole` 角色：使用 `getByText` 查找文本。

## 可见性

当平台报告设备节点位于屏幕外，或软键盘覆盖其中心时，节点被视为隐藏。因此，`toBeVisible()`、`scrollUntilVisible` 和 `getByRole` 会将键盘下方的字段与滚出视野的字段同等对待。键盘自身的按键、建议栏和底栏保持可见，聚焦字段也保持可见。

- 键盘区域是 agent-device 测得的边框。如果捕获中没有边框，该区域从树中的键盘顶部延伸到屏幕底部。
- 如果容器的中心位于键盘下方，但其某个子节点显示在键盘上方，该容器仍保持可见。
- 被其他视图遮挡的节点，例如被键盘顶起的页脚下方的节点，不会被视为隐藏。agent-device 发现遮挡时，点击会以 `ACTION_FAILED` 失败，消息会指出遮挡物。点击键盘下方的节点也会如此失败。关闭遮挡物，或滚动测试目标使其不再被遮挡。

## 视频录制清理

等待中的 agent-device 屏幕录制停止操作会与后续调用方和尝试清理共享。取消某个调用方的等待不会重复停止操作，也不会丢弃其最终完成结果。如果设备停止录制失败，清理阶段可以重试。被取消的调用方仍会报告取消。

提供方录像停止失败后，仍由其工作进程负责。引擎会在尝试结束时、该工作进程开始下一次尝试前，以及工作进程释放期间重试停止。等待中的停止操作会共享。每次重试都使用原始尝试的视频目录。

只有在提供方确认停止后，下一次尝试才会开始。停止等待失败或被取消会阻止该尝试启动。已确认的停止操作不会因返回的产物无效而重复执行。在替换工作进程时，仅提供方停止失败不会导致健康的 agent-device 会话关闭。

重试恢复的录像不会加入报告：文件可能留在原始尝试的视频目录中，返回的 URL 则会被丢弃。必须录制的视频如果首次停止失败，仍会被记为清理失败。

这些录制句柄不会在工作进程退出后保留。运行结束时，引擎关闭 agent-device 会话，提供方释放租约。提供方必须在释放租约时清理所有剩余的外部录制。关闭 agent-device 会话无法保证任意云端录制停止。提供方停止回调失败不能确认录制已停止。

## 设备上的回放缓存

回放缓存以设备报告的 [`location`](#capabilities) 为锚点，即 `<bundle id> / <screen title>`。在 `com.apple.Preferences / General` 上记录的步骤，只有当“设置”再次位于“通用”页面时才会回放。

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

- `open_app` 等会修改状态的项目工具调用会结束回放。
- 声明 `app.bundleId` 并先调用 `app.open()`，让步骤从同一屏幕开始。
- 通过 `device` 测试夹具在步骤之间切换应用，不要在单个步骤内部切换。
- 在 [`device.openLink`](#openlink) 之后记录的步骤，会在链接再次到达相同屏幕时回放。

## 类型

### 引擎选项

每个 `MobileOptions` 成员及其 JSDoc 都在相应的[引擎](#engine)条目中声明。

```ts
/** A permission's state: held, refused, or not asked for yet, so the OS asks again. */
export type PermissionState = 'grant' | 'deny' | 'reset';

/** Permissions an app holds when it launches, by name. */
export type LaunchPermissions = Readonly<Partial<Record<DevicePermission, PermissionState>>>;
```

### 设备测试夹具

每个 `Device` 成员及其 JSDoc 都在相应的[设备](#device)条目中声明。

```ts
/** How `device.openApp` launches an app. */
export interface OpenAppOptions {
  /** Terminate the app first, so it starts fresh; without it a running app is brought forward as it is. */
  readonly relaunch?: boolean;
  /**
   * Arguments this launch hands the app: its process arguments on iOS,
   * `am start` arguments on Android. Replaces the target's `app.launchArguments`
   * for a relaunch of the pinned app.
   */
  readonly launchArguments?: readonly string[];
  /**
   * Permissions the app holds before this launch, each granted, denied, or
   * reset. Replaces the target's `app.permissions` for a relaunch of the
   * pinned app.
   */
  readonly permissions?: LaunchPermissions;
}

/** Permissions agent-device can grant, deny, or reset on an app. */
export type DevicePermission =
  | 'camera'
  | 'microphone'
  | 'photos'
  | 'contacts'
  | 'notifications'
  | 'calendar'
  | 'location'
  | 'reminders'
  | 'motion'
  | 'siri'
  | 'media-library';

/** Orientations `setOrientation` accepts. */
export type DeviceOrientation = 'portrait' | 'portrait-upside-down' | 'landscape-left' | 'landscape-right';

/** Hinge poses `device.fold` accepts: `closed` lights the outer display, `half-open` and `open` the inner one. */
export type FoldPose = 'closed' | 'half-open' | 'open';

/** How `device.installApp` installs a build. */
export interface InstallAppOptions {
  /**
   * Bundle id or package of the build. `reinstall` needs one: agent-device
   * removes that app before installing. Defaults to the pinned app.
   */
  readonly app?: string;
  /** Remove the installed app first so the build starts with no data. */
  readonly reinstall?: boolean;
}

/** What an install put on the device, as agent-device identified it. */
export interface InstalledApp {
  /** The bundle id or package to open the app by. */
  readonly app: string;
  readonly bundleId?: string;
}

/** The app in the foreground, as `foregroundApp` reports it. */
export interface ForegroundApp {
  readonly name: string;
  readonly bundleId?: string;
}

/** Sensors `setBiometrics` simulates. */
export type BiometricSensor = 'faceid' | 'touchid' | 'fingerprint';

/** The raw driver session behind `device`; see `Device.unstable_raw`. */
export interface DeviceSession {
  readonly platform: MobilePlatform;
  /** The raw driver session name: `e2e-<target>-<worker slot>`, or `<session>-<worker slot>` with the `session` option. */
  readonly session: string;
  /** The device id: a simulator UDID or an Android serial. */
  readonly deviceId: string;
  readonly deviceName: string;
  /** The device selection the engine passes commands; spread it into a call that can run before `app.open()`. */
  readonly selection: DeviceSelection;
  /** The raw driver client, bound to this session. */
  readonly client: DeviceSessionClient;
}

/** The fields agent-device commands select a device by: the platform, then one of a name, a simulator UDID, or an Android serial. */
export interface DeviceSelection {
  readonly platform: MobilePlatform;
  readonly device?: string;
  readonly udid?: string;
  readonly serial?: string;
}
```

### 导出类型

`MobileOptions`、`MobilePlatform`、`DevicePermission`、`LaunchPermissions`、`PermissionState`、`DeviceClientConfig`、`DeviceConnection`、`DeviceDaemon`、`DeviceProvider`、`DeviceLease`、`DeviceReleaseContext`、`DeviceRequest`、`Device`、`DeviceSession`、`DeviceSessionClient`、`DeviceSelection`、`DeviceOrientation`、`BiometricSensor`、`ForegroundApp`、`FoldPose`、`InstallAppOptions`、`InstalledApp` 和 `OpenAppOptions` 由 `@e2e-dev/mobile` 导出。运行时导出包括 `mobile`，以及带有 `device` 测试夹具类型的 `test`、`describe`、`beforeEach`、`afterEach`、`beforeAll` 和 `afterAll`；`mobileTools` 来自 `@e2e-dev/mobile/tools`。

## 相关内容

[移动端](https://e2e.com/docs/zh/mobile)指南介绍配置、托管设备和故障排查。跨平台生命周期方法位于 [`app`](https://e2e.com/docs/zh/reference/app)。
