# simulator

> 智能体用来启动、操控、读取和录制团队 iOS 模拟器、Apple Watch 模拟器和 Android 模拟器的命令。

Source: https://air.build/cn/docs/cli/simulator/

智能体通过 `simulator` 在运行时操作自己构建出来的 App：启动设备、安装并打开 App、读取屏幕内容、点按和输入、截屏、录屏、抓取日志，以及修改设备设置。每条命令只做一件事，并以 JSON 输出结果。

## 在哪里运行

|  | 云端团队 | Mac 团队 |
| --- | --- | --- |
| 设备 | 整个团队共享的远程设备：AirBuild 提供的每种机型（iPhone 和 iPad）各一台，每台 iPhone 配一块 Apple Watch，另有 Android 模拟器 | 团队自己在你 Mac 上的 iOS 模拟器（名为“AirBuild …”的设备），每台 iPhone 配一块 Apple Watch。它们会和你自己的设备一起出现在 Simulator.app 中，你可以在旁边观看 |
| 设备 id | 机型名称，例如 `iphone-18-pro-max`、`iphone-18-pro.watch` | `ios:<UDID>`、`ios:<UDID>.watch` |
| 默认设备 | 由平台决定；永远不会是 Android 设备，也无法更改 | App 中选定的那台，构建产物会装到它上面 |
| Android 命令（`clear-data`、`permissions`、`shell`、`logs --crashes`） | 支持 | 不支持 |
| 你自己的模拟器 | — | 永远不会被启动、安装或关闭 |

登录信息和服务地址来自智能体的环境，无需任何设置。两种团队的区别见 [选择智能体的运行位置](https://air.build/cn/docs/get-started/where-agents-run/)。

## 用法

```text
simulator <command> [arguments] [--simulator ID] [--then-describe-ui]
simulator --help
```

### 所有命令通用的选项

| 选项 | 取值 | 默认值 | 含义 |
| --- | --- | --- | --- |
| `--simulator ID` | `simulator list` 中的 id（字母、数字、`:` `.` `_` `-`，最多 128 个字符） | 默认设备 | 操控这台设备而不是默认设备。可以放在命令行的任意位置，也可以写成 `--simulator=ID`。 |
| `--then-describe-ui` | — | 关 | 仅用于 `tap`、`swipe`、`type`、`set-text`、`key`、`button`、`launch` 和 `open-url`。等待屏幕稳定后，在结果中加入 `after`：`changed`（这次操作是否改变了屏幕）以及新屏幕，格式与 `describe-ui --short` 相同。一次调用就完成操作、等待和读取。 |
| `-h`, `--help` | — | — | 打印完整帮助。 |

### 输出和退出码

结果以单行 JSON 写到 stdout，成功时总是包含 `"ok":true` 和设备 `id`。截屏、录屏、剪贴板和日志则直接输出原始字节或文本行。进度信息和错误写到 stderr。

| 退出码 | 含义 |
| --- | --- |
| `0` | 完成。 |
| `1` | 操作失败。错误以 `Error:` 开头，后面可能跟一行 `Hint:`。以下情况也会返回 1：`adjust` 只完成了一部分、`batch` 中某一步失败、`drag` 失败、有服务处于 `failed`。 |
| `2` | 命令行有误：未知命令、缺少值或值超出范围。会打印 `Usage: simulator <the command's usage>`。 |
| 任意 | `shell` 以设备上那条命令自己的退出码退出。 |
| `129`, `130`, `143` | `logs --follow` 被 SIGHUP（或父进程退出）、SIGINT 或 SIGTERM 结束。 |

## 云端团队的设备

- `simulator list` 列出每台设备的 id、机型、运行时、`platform`（`iOS`、`watchOS` 或 `Android`）、`state`，以及哪台是 `default`。不带 `--simulator` 的命令作用于默认设备。
- 多台设备可以同时运行。对某台设备执行其他命令前，先对它运行 `simulator start`。
- 团队中任何智能体运行 `start` 得到的都是同一台设备。尚未就绪的机型可能需要几分钟。
- 除默认设备外，任何设备连续十分钟无人观看或操控就会自动关闭。智能体的沙盒空闲关闭时，所有设备都会被释放。

### Apple Watch

每台 iPhone 都配有一块 Apple Watch，紧跟在它后面列出，id 为 `<iPhone id>.watch`，带有 `"platform":"watchOS"`，`companionOf` 指明它所配对的 iPhone。

- `simulator start --simulator <iPhone id>.watch` 会在 iPhone 未开机时先启动 iPhone，再启动手表。在 Mac 团队中，第一次启动时会用这台 Mac 上最新的 watchOS 创建手表。
- 其他命令操控手表的方式与操控 iPhone 相同。
- 手表没有主屏幕、App 切换器、锁定键和音量键，也不会旋转。请使用 `button digital-crown`（按下表冠相当于主屏幕）和 `button side-button`。
- 手表 App 要安装到手表本身：`simulator install PATH --simulator <iPhone id>.watch`。安装 iPhone App 不会把其手表 App 装到手表上。
- 关闭 iPhone 时，它的手表也会随之关闭。

### Android 模拟器

Android 设备以 `"platform":"Android"` 列出。默认设备永远不会是 Android 设备，所以务必传入 `--simulator ID`。常用命令在 Android 上的含义如下：

| 命令 | 在 Android 上 |
| --- | --- |
| `install` | 接受 `.apk`。 |
| `launch`、`terminate`、`uninstall`、`apps` | 接受或显示包名，例如 `com.example.app`。 |
| `button` | `back`、`home`、`app-switcher`（最近任务）、`power`、`volume-up`、`volume-down`。 |
| 选择器、`describe-ui` | 读取 Android 无障碍树。`--id` 是视图的 resource id。 |
| `logs` | logcat。 |
| `appearance`、`content-size`、`increase-contrast`、`pbpaste`、`pbcopy` | 修改模拟器自身的设置。`content-size` 对应字体缩放。 |
| `rotate` | 旋转模拟器。前台 App 允许时屏幕会跟着转；手机桌面保持竖屏。 |
| `add-media` | 照片和视频放入相机胶卷（`/sdcard/DCIM/Camera`）。联系人仅支持 Apple 设备。 |
| `foreground` | 在主屏幕上时，输出桌面启动器的包名。 |

Android 设备没有手表，以下命令仅用于 Apple 设备：`fold`、`displays`、`heal`、`services`、`slider`、`adjust`、`screenshot-3d`。`runbuild --platform android_beta` 构建 `.apk`（Android 项目目前为测试版）。见 [runbuild](https://air.build/cn/docs/cli/runbuild/)。

## 生命周期

| 命令 | 作用 |
| --- | --- |
| `list` | 列出每台设备：`id`、`model`、`runtime`、`platform`、`state`、`default`，手表还有 `companionOf`。不接受参数。 |
| `start [--timeout SECONDS]` | 启动设备（已在运行则直接返回），并等到它就绪。输出 `id`、`ready`、`url`、`simulator`、`model`、`runtime`。在 Mac 团队中，如果还没有设备会先创建一台。 |
| `shutdown [--timeout SECONDS]` | 只关闭这一台设备并等到它关机，团队的其他设备继续运行。设备已关闭时运行也没问题。等待期间如果有人再次启动它，就停止等待。输出 `{"ok":true,"simulator":"…"}`。 |
| `apps [--all]` | 以 JSON 数组列出已安装的 App。`--all` 还会列出 `apps` 默认不显示的那些。 |
| `install PATH` | 上传并安装 App：iOS 模拟器的 `.app` 文件夹或 `.ipa`，在 Android 上则是 `.apk`。输出 `installed` 和路径。同一台设备上的安装按顺序逐个进行。 |
| `launch BUNDLE_ID [--env KEY=VALUE]...` | 打开 App（在 Android 上是包名）。输出 `launched`。 |
| `terminate BUNDLE_ID` | 停止正在运行的 App。输出 `terminated`。 |
| `uninstall BUNDLE_ID` | 删除 App。输出 `uninstalled`。 |
| `foreground` | 前台的 App，以 `app` 输出。 |
| `open-url URL` | 在设备上打开 URL 或深层链接。输出 `opened`。 |
| `add-media PATH...` | 添加照片、视频和联系人（见下文）。 |
| `clear-data PACKAGE` | 仅限 Android。清除 App 数据，恢复到刚安装时的状态，并停止该 App。输出 `cleared`。 |
| `permissions PACKAGE [--grant NAME,...] [--revoke NAME,...]` | 仅限 Android。授予或撤销运行时权限，这样运行过程中就不会卡在权限对话框。输出 `package`、`granted`、`revoked`。 |
| `shell [--timeout SECONDS] COMMAND...` | 仅限 Android。在设备的 shell 中运行一条命令，例如 `pm path com.example.app`、`run-as com.example.app ls files` 或 `am broadcast …`。输出它的 stdout 和 stderr，并以它的退出码退出。 |

### 生命周期参数

| 参数 | 命令 | 取值 | 默认值 | 含义 |
| --- | --- | --- | --- | --- |
| `--timeout SECONDS` | `start`、`shutdown` | 整数，1–3600 | 180 | 等待设备就绪或关机的时长。 |
| `--all` | `apps` | — | 关 | 列出所有已安装的 App。 |
| `--env KEY=VALUE` | `launch` | 由字母、数字和 `_` 组成的名称（不能以数字开头），接 `=`，再接任意值。可重复多次。 | 无 | iOS：为这次启动设置环境变量。App 会在新进程中启动；已在运行的实例会先被关闭。 |
| `--grant NAME,...` | `permissions` | 逗号分隔的名称 | 无 | 要授予的权限。只会授予 App 清单中申请了的权限。 |
| `--revoke NAME,...` | `permissions` | 逗号分隔的名称 | 无 | 要撤销的权限。撤销会停止 App。 |
| `--timeout SECONDS` | `shell` | 整数，1–600 | 60 | 超过这个时间，设备上的命令会被终止。 |

权限名称：`camera`、`microphone`、`location`、`background-location`、`contacts`、`calendar`、`photos`、`notifications`、`phone`、`bluetooth`、`activity`，或完整的 `android.permission.*` 名称。`permissions` 至少需要一个 `--grant` 或 `--revoke`。

**构建之后。** `runbuild` 从不安装 App。先用 `simulator terminate BUNDLE_ID` 停止正在运行的实例，否则旧进程会一直留着；然后运行 `simulator install PATH` 和 `simulator launch BUNDLE_ID`。

**App Clip。** App Clip 通过环境变量 `_XCAppClipURL` 获得调用 URL，而不是通过 NSUserActivity，所以它的 DEBUG 构建需要读取这个变量，并像处理一次调用那样进行路由。由于 `?` 和 `&` 对 shell 有特殊含义，请给这一对键值加引号：

```bash
simulator launch com.example.app.Clip --env '_XCAppClipURL=https://appclip.apple.com/id?p=com.example.app.Clip'
```

### add-media

`add-media PATH...` 把文件添加到设备的照片和通讯录中，每个文件保留自己的名称：

| 类型 | 扩展名 |
| --- | --- |
| 照片 | `.jpg`、`.jpeg`、`.png`、`.heic`、`.heif`、`.gif`、`.tif`、`.tiff`、`.bmp`、`.webp` |
| 视频 | `.mov`、`.mp4`、`.m4v` |
| 联系人 | `.vcf`（仅限 Apple 设备） |

所有路径都会在第一次上传前检查，所以只要有一处拼写错误，就什么也不会添加。

### 生命周期错误

| 消息 | 怎么办 |
| --- | --- |
| `Error: the <model> Simulator is <state>; run simulator start and wait for readiness.` | 运行消息中给出的 `simulator start`（需要时会带上 `--simulator ID`），然后重新执行命令。 |
| `Error: the Simulator did not become ready within Ns.` | 再次运行 `start`，或加大 `--timeout`。 |
| `Error: the Simulator did not shut down within Ns.` | 再次运行 `shutdown`，或加大 `--timeout`。 |
| `Error: app does not exist: PATH` | 检查 `runbuild` 输出的路径。 |
| `Error: install directories must be iOS .app bundles.` | 传入 `.app` 文件夹，而不是其他文件夹。 |
| `Error: install files must end in .ipa or .apk.` | 传入 `.app`、`.ipa` 或 `.apk`。 |
| `Error: <bundle id> opened without its environment variables: this Simulator can't pass them to an app yet.` | App 打开了，但没有带上 `--env`。运行 `simulator shutdown`，再运行 `simulator start`，换一台最新的设备。 |
| `Error: media file does not exist: PATH` / `Error: not a media file (…): PATH` / `Error: media file is empty: PATH` | 修正路径或文件类型。没有添加任何文件。 |
| `Error: --timeout must be an integer from 1 to 600 seconds.` | `shell --timeout` 的取值为 1–600。 |
| `Error: this Simulator's gateway is too old for simulator <command>. Run simulator shutdown, then simulator start, to get a current one.` | 按提示操作，然后重试。 |

## 设置

| 命令 | 取值 | 作用 |
| --- | --- | --- |
| `appearance light` / `appearance dark` / `appearance` | `light`、`dark` | 设置浅色或深色模式。不带值时，以 `appearance` 输出当前值。 |
| `content-size [CATEGORY]` | 见下文 | 设置文字大小。不带值时，以 `contentSize` 输出当前值。 |
| `increase-contrast enabled` / `increase-contrast disabled` / `increase-contrast` | `enabled`、`disabled` | 打开或关闭“增强对比度”。不带值时，以 `increaseContrast` 输出当前值。 |
| `rotate ORIENTATION` | `portrait`、`landscape-left`、`landscape-right`、`portrait-upside-down` | 把设备转到指定的绝对方向，所以重复执行不会再有变化。 |
| `fold POSITION` | `closed`（0）、`half`（130）、`open`（180），或 0–180 | 调整折叠屏设备（iPhone Duo）的铰链角度。单屏设备会忽略。输出 `degrees`。 |
| `displays` | — | 设备的各块屏幕：`screenId`、尺寸，以及哪块是 `active`。 |
| `heal` | — | 从 Xcode 的 Device Hub 夺回设备输入（见下文）。输出 `reclaimed`。 |
| `services` / `services enable ITEM...` / `services disable ITEM...` | 见下文 | 列出或修改设备的后台服务。 |

读取时也可能返回 `unsupported` 或 `unknown`。

文字大小类别，从小到大：`extra-small`、`small`、`medium`、`large`、`extra-large`、`extra-extra-large`、`extra-extra-extra-large`、`accessibility-medium`、`accessibility-large`、`accessibility-extra-large`、`accessibility-extra-extra-large`、`accessibility-extra-extra-extra-large`。

### rotate 和 fold

`rotate` 返回 `orientation` 和 `screen`：旋转后屏幕显示的方向。如果前台 App 不支持旋转，`screen` 会和你要求的不同（主屏幕保持原样，但设备已经转过去了，下一个支持旋转的 App 会跟着转）。展开的 iPhone Duo 内屏安装时转了四分之一圈：竖着拿时读作 `landscape-left`，截屏里的界面也是转过来的。坐标始终使用 `simulator screen` 报告的竖屏坐标系。

`fold` 在设备收到事件后立即返回，稍后才切换屏幕。截屏、`screen`、`describe-ui`、选择器和录屏都跟随当前活动屏幕，可能需要最多三秒才能跟上：操作另一块屏幕之前，先用 `displays` 确认。`tap` 和 `swipe` 作用于活动屏幕，除非用 `--display SCREEN_ID` 指定另一块。

### heal

打开 Xcode 27 时，iOS 27 模拟器可能不再接收触摸、按键和按钮，而所有命令仍然返回 ok。这样的设备会以 `input_shadowed` 拒绝输入，并提示 `run simulator heal`。`heal` 通过重启 SpringBoard 来修复，这会结束所有正在运行的 App，所以之后要重新启动你的 App。在未受影响的设备上，它输出 `"reclaimed":false`，不做任何改动。

### services

模拟器启动时会关闭 App 很少用到的服务（Siri、Spotlight 索引、iCloud、遥测、照片分析、信息、家人控制、HomeKit 等）。`simulator services` 按类别和功能列出这些服务。

| ITEM | 含义 |
| --- | --- |
| `all` | 所有服务。 |
| `slim` | 新设备启动时关闭的那些。 |
| 类别或功能 id | 与 `services` 列出的一致，例如 `siri`、`search`、`icloud`。 |
| launchd 标签 | 单个服务。 |

多个项目用空格或逗号分隔。处于 `pending` 的服务要等设备下次启动时才会启动；在云端团队中，再次启动的设备是一台全新的设备，所以它暂时保持关闭。在 Mac 团队中，运行 `simulator shutdown`，再运行 `simulator start`。有服务处于 `failed` 时，命令会在输出结果后以 1 退出。未知 id 会失败，并提示运行 `simulator services`。

## 剪贴板

| 命令 | 作用 |
| --- | --- |
| `pbpaste` | 原样输出设备剪贴板的内容，不额外添加换行，方便用管道传递。 |
| `pbcopy [TEXT]` | 把设备剪贴板设为 TEXT。传 `-` 或不传 TEXT 时，原样读取 stdin，包括末尾的换行。 |

`type` 只能发送美式键盘布局的 ASCII 字符。要输入其他字符，用 `pbcopy` 放到剪贴板再粘贴，或者使用 `set-text`。

## 密码

```text
simulator fill NAME --field LABEL [--type]
```

`fill` 把团队密码簿中的一个值填入当前获得焦点的输入框，所以要先点按输入框。`password-book list` 会列出条目名称（见 [password-book](https://air.build/cn/docs/cli/password-book/)）。

| 参数 | 取值 | 默认值 | 含义 |
| --- | --- | --- | --- |
| `NAME` | 条目名称 | 必填 | 密码簿条目。 |
| `--field LABEL` | 字段标签 | 必填 | 条目中的哪个字段，例如 `Username` 或 `Password`。 |
| `--type` | — | 关 | 始终以按键方式输入（仅限可打印 ASCII）。适用于 ⌘V 不起作用的地方，例如 Flutter 文本框。 |

默认情况下，值会先放到设备剪贴板，读回确认已写入，再用 ⌘V 粘贴，然后清空剪贴板。任何字符都可以。如果剪贴板没有接收这个值，可打印 ASCII 的值会改为键入，其他值则失败。键入的文本会经过输入框的自动大写和智能标点处理；安全输入框两者都没有。

值永远不会被打印出来。结果中只包含条目、字段和方式：

```json
{"ok":true,"id":"…","filled":{"name":"Test account","field":"Password","method":"pasted"}}
```

`method` 为 `pasted` 或 `typed`。登录时请使用 `fill`，不要把密码通过管道传给 `type`。

| 消息 | 怎么办 |
| --- | --- |
| `Error: --type can only type printable ASCII, and this value has other characters; fill it without --type.` | 去掉 `--type` 再运行。 |
| `Error: the device clipboard did not take the value, so there is nothing to paste. Try again; if it keeps failing, report it.` | 再试一次。 |
| `Error: the value may still be on the device clipboard. Empty it with: simulator pbcopy ''` | 运行 `simulator pbcopy ''`。 |

## 截取

| 命令 | 作用 |
| --- | --- |
| `screenshot [OUTPUT] [--upright]` | 保存截屏。 |
| `screenshot-3d [OUTPUT] [--rotation X,Y,Z] [--size WxH] [--background COLOR]` | 按折叠屏设备当前的姿态，把它画在 3D 模型上。`--background` 为 `transparent` 或 `#RRGGBB`。 |
| `screen` | 屏幕坐标系，`tap`、`swipe` 和 `describe-ui` 都使用它。 |
| `record [--timeout SECONDS]` | 开始录屏。 |
| `record-status` | 录屏状态：`recording`、`finished`、`failed` 或 `null`。 |
| `record-stop [OUTPUT]` | 停止录屏并下载 MP4。 |
| `logs [--lines COUNT] [--app ID] [--level LEVEL] [--crashes]` / `logs --follow [--duration SECONDS] …` | 读取设备日志。`--lines` 和 `--follow` 不能同时使用。 |

### screenshot

OUTPUT 以 `.png` 结尾或没有扩展名时保存为 PNG；以 `.jpg` 或 `.jpeg` 结尾时保存为 JPEG。传 `-`，或不传 OUTPUT 且 stdout 接了管道时，PNG 写到 stdout。保存为文件时输出 `{"ok":true,"id":"…","output":"/absolute/path.png"}`。

`--upright` 会旋转图片，让其中的界面是正的（横屏 App、展开的 iPhone Duo）。它只用于查看：坐标、frame 和点按仍以普通截屏为准，所以要选取点位时请截一张普通截屏。

### screenshot-3d

只有折叠屏设备（iPhone Duo）有 3D 模型。它会把设备画成当前报告的铰链角度，亮着的屏幕用实时画面绘制，画布为 1024×1024 透明背景。普通的 `screenshot` 只显示一块屏幕，看不出折叠状态。

| 参数 | 取值 | 默认值 | 含义 |
| --- | --- | --- | --- |
| `--rotation X,Y,Z` | 角度 | — | 旋转模型。 |
| `--size WxH` | 像素 | `1024x1024` | 画布尺寸。 |
| `--background` | `transparent` 或 `#RRGGBB` | 透明 | 画布填充。 |

输出方式与 `screenshot` 相同。保存为文件时还会输出 `foldable`、`hingeDegrees` 和 `litPanel`。

### 录屏

每台设备同时只能有一个录屏，按实时录制：静止的画面也会占用实际时长。每个录屏在超时后都会自动停止并自行完成封装。

| 参数 | 命令 | 取值 | 默认值 | 含义 |
| --- | --- | --- | --- | --- |
| `--timeout SECONDS` | `record` | 整数，1–3600 | 180 | 自动停止时间。 |
| `OUTPUT` | `record-stop` | 文件路径，或 `-` | 接管道时为 stdout | MP4 的去向。 |

超时自动停止后仍可运行 `record-stop`。保存为文件时输出 `output` 和 `recording`。在下一次录屏开始前，文件都可以下载。

### logs

| 参数 | 取值 | 默认值 | 含义 |
| --- | --- | --- | --- |
| `--lines COUNT` | 1 或更大 | 120 | 输出这么多行。不能与 `--follow` 同用。 |
| `--follow`, `-f` | — | 关 | 持续输出日志，直到被停止。 |
| `--duration SECONDS` | 1–3600 | 不限 | 仅与 `--follow` 同用：到时间后停止并以 0 退出。 |
| `--app ID` | Bundle id 或包名 | 全部 | 只保留一个 App 的日志。iOS 上包括该 App 及其扩展；Android 上包括该 App 及其崩溃信息，跨重启有效。 |
| `--level LEVEL` | iOS：`debug`、`info`、`warn`、`error`、`fatal`。Android 另有 `verbose`。 | 全部 | 只保留该级别及以上的日志。 |
| `--crashes` | — | 关 | 仅限 Android：只读取崩溃缓冲区。 |

- iOS 日志是实时的，不是历史记录：`--lines` 收集的是设备在接下来几秒内写出的内容，所以要先开始读取，再执行操作。
- 在 iOS 上，`--app` 和 `--level` 在设备端过滤，所以跟踪单个 App 时不会像跟踪全部日志那样丢行。重新安装 App 会结束带过滤的跟踪，需要重新开始。
- 跟踪在收到 SIGTERM、SIGINT 或 SIGHUP 时结束（所以 `timeout 60 simulator logs --follow` 可用），父进程退出或读取端关闭 stdout 时也会结束。
- 在云端团队中，设备写日志的速度超过传输速度时，多出的行会被丢弃，并在该处插入一行 `simkit: dropped N log line(s) here`。
- 尽量使用有时限的形式 `--follow --duration 60`，不再需要的跟踪请及时停止：正在运行的跟踪会让设备一直处于占用状态。

### 截取错误

| 消息 | 怎么办 |
| --- | --- |
| `Error: refusing to write image bytes to a terminal; pass an output path or pipe stdout.` | 指定 OUTPUT，或把 stdout 接到管道。`record-stop` 输出视频字节时同理。 |
| `Error: screenshot output must end in .png, .jpg or .jpeg: PATH` | 修改文件名。 |
| `Error: this Simulator's gateway is too old to save a <format> screenshot. …` / `… too old for simulator screenshot-3d. …` | 运行 `simulator shutdown`，再运行 `simulator start`。 |
| `Error: --timeout must be an integer from 1 to 3600 seconds.` | 修正 `record --timeout`。 |
| `Error: --duration must be an integer from 1 to 3600 seconds.` | 修正 `logs --duration`。 |
| `Error: this Simulator's gateway cannot filter logs yet (--app, --level, --crashes). …` | 不带这些参数运行 `simulator logs`，自己过滤日志行。 |
| `Error: the Team Simulator log stream ended unexpectedly (curl N).` | 重新开始跟踪。 |

## UI 自动化

### 读取屏幕

| 命令 | 作用 |
| --- | --- |
| `describe-ui` | 屏幕的无障碍树，包含 frame、id 和 `nodeId`。有几十 KB。 |
| `describe-ui --short` | 用名称描述屏幕，只有几百字节：`tap`（可以按的东西）、`fill`（文本框及其内容）、`adjust`（滑块、选择器）、`disabled`、`text`（显示的文字），以及 `keyboard` 是否弹出。 |
| `describe-ui --x X --y Y` | 某个点上的元素。两个值都要给。不能与 `--short` 同用。 |
| `find SELECTOR` | 所有可用的匹配项（最佳的排在前面）以及 `excluded`，不会触碰设备。 |

用 `--short` 了解当前所在位置，需要 frame 或 id 时再读完整的树。选择器读取的是同一棵树，不会从像素中识别文字。前台 App 忙碌、没有返回无障碍数据时，读取会在 2 秒和 4 秒后各重试一次，仍然失败则提示稍等再试；在此期间截屏仍然可用。

### 选择器

`tap`、`find`、`wait-visible`、`wait-hidden`、`slider`、`adjust` 和 `set-text` 可以用选择器代替坐标：

| 参数 | 含义 |
| --- | --- |
| `--text TEXT` | 元素可见标签或值的一部分，不区分大小写。 |
| `--id ID` | 完全一致的 accessibilityIdentifier（在 Android 上是视图的 resource id）。 |
| `--value VALUE` | 仅匹配元素值的一部分，不区分大小写。 |
| `--role ROLE` | 完全一致的平台角色，例如 `AXSlider`。 |
| `--exact` | `--text` 和 `--value` 必须完全相等，而不是包含。需要与其中之一同用。 |
| `--strict` | 有多个可用元素匹配时直接失败，而不是排序选择。 |
| `--node-id NODE` | `describe-ui` 或 `find` 给出的不透明 `nodeId`，精确指向那个元素。 |

给出的每个过滤条件都必须匹配。有多个元素匹配时，按以下顺序选出最佳的：文字完全匹配优先于部分匹配，标签匹配优先于值匹配，可交互元素（按钮、输入框、开关、单元格）优先于静态文字，然后是更小的元素，最后按从上到下、从左到右。隐藏的、在屏幕外的或没有 frame 的匹配项不会被使用；它们会连同原因列在 `excluded` 下。每个元素都带有 `enabled`。

即使元素的值已经改变，`--node-id` 也只作用于那一个元素。它永远不会退回到按标签或旧坐标查找：控件被重建或 App 被重启后会以 `stale_node` 失败，这时需要重新读取。它的有效期很短，也不同于 `--id`。

始终无法解析的选择器会这样失败，并列出被跳过的候选项：

```text
Error: no usable element matching text="Sign in" within 10.0s (matched but skipped: 1 disabled)
```

### 等待

| 命令 | 作用 |
| --- | --- |
| `wait-visible SELECTOR [--timeout SECONDS]` | 等到出现匹配的元素。像 `tap` 一样输出该元素。 |
| `wait-hidden SELECTOR [--timeout SECONDS]` | 等到不再有匹配的元素。输出 `elapsedMs`。 |
| `wait-idle [--timeout SECONDS] [--stable SECONDS]` | 等到 UI 树连续 `--stable` 秒没有变化。输出 `elapsedMs`。 |

`--timeout` 默认 10 秒，最多 600；`--stable` 默认 0.5，最多 10。对这些等待而言，禁用的元素也算存在。在执行有动画或需要加载的操作后、读取结果前，使用 `wait-idle`；仅有加载指示器在转并不会改变树。

### 触摸

| 命令 | 作用 |
| --- | --- |
| `tap X Y [--duration SECONDS] [--display SCREEN_ID]` | 点按某个点。`--duration` 使其成为长按。 |
| `tap SELECTOR [--timeout SECONDS] [--duration SECONDS]` | 等待一个已启用的匹配元素出现并静止，然后点按其中心。 |
| `swipe X1 Y1 X2 Y2 [--duration SECONDS] [--display SCREEN_ID]` | 从一个点快速滑到另一个点。 |
| `drag X1 Y1 X2 Y2 [--duration SECONDS] [--steps COUNT]` | 单指沿直线移动后松开，不带惯性：用于重新排序、面板和自定义滑块。 |
| `scroll-to TARGET [options]` | 滚动直到屏幕外的元素出现，但不点按它。 |
| `slider SELECTOR --percent 0..100` | 设置标准水平滑块，并读回其值。 |
| `adjust STEPS SELECTOR` | 逐步调整 `describe-ui` 标为 `adjustable` 的控件（步进器、选择器、时间滚轮）。 |

坐标使用 `simulator screen` 报告的坐标系。`--display SCREEN_ID` 把 `tap` 或 `swipe` 发送到另一块屏幕（`displays` 中的整数），使用那块屏幕自己的坐标。

`tap SELECTOR` 默认等待 10 秒，最多 600；等待期间会跳过禁用的匹配项，直到它变为启用。它输出 `element`、`point`、`exact` 和 `matchCount`；大于 1 表示选择器有歧义，是排序选出的结果。

`drag` 的 `--duration` 为 0.05–60 秒（默认 0.6），`--steps` 为 2–1000（默认 30）。

`slider` 的值与目标相差 3 以内即视为成功；检查失败时滑块可能已经移动。不接受 `--timeout`。

`adjust` 的 STEPS 是带符号的数，例如 `+3` 或 `-2`，不能为 0；每一步的大小由控件决定。它的选择器总是严格匹配。结果包含 `completedActions` 以及 `before` 和 `after` 元素；只完成一部分时会输出结果并以 1 退出。

#### scroll-to

目标为 `--text TEXT`、`--id ID` 或 `--node-id NODE`。

| 参数 | 取值 | 默认值 | 含义 |
| --- | --- | --- | --- |
| `--exact` | — | 关 | `--text` 必须完全相等。 |
| `--direction` | `down`、`up`、`left`、`right` | `down` | 内容所在的方向。 |
| `--within-id ID` / `--within-text TEXT` | — | 整个屏幕 | 屏幕上有多个滚动区域时要使用的那个。它必须是唯一可见的。 |
| `--within-exact` | — | 关 | `--within-text` 必须完全相等。 |
| `--timeout SECONDS` | 最多 25 | 20 | 一次查找的时长。 |
| `--max-scrolls COUNT` | 1–100 | 25 | 最多拖动次数。 |

每次拖动后都会重新读取屏幕，所以延迟加载的内容也能加载出来；当内容不再变化、达到 `--max-scrolls` 或到达 `--timeout` 时停止。目标已可见时无需拖动。结果包含 `scrolls` 和 `elapsedMs`。要找得更久，就再运行一次：它会从列表当前的位置继续。它不会点按；`tap` 也不会滚动。

### 文字和按键

| 命令 | 作用 |
| --- | --- |
| `set-text TEXT SELECTOR [--paste] [--timeout SECONDS]` | 让文本框的内容恰好为 TEXT：找到它、聚焦、替换原有内容并读回确认（`verified: true`）。支持任何语言和表情符号，无论前台是哪种键盘。`-` 从 stdin 读取文字。 |
| `type TEXT` / `type --file PATH` / `type -` | 向当前焦点发送按键。 |
| `key CODE [--modifier M]...` | 按下一个键码，例如 `KeyV`。 |
| `button BUTTON [--duration SECONDS]` | 按下硬件按钮。 |
| `input JSON` | 发送一个原始输入事件。`-` 从 stdin 读取。 |

`set-text` 输出 `method`、`verified` 和输入框的 `value`。`--paste` 以粘贴方式输入；`--timeout` 最多 20 秒。

`type` 在按下第一个键前会检查整段文字，并保留其中的空白。键盘是美式布局 ASCII，其他字符会报错。前台如果是输入法（中文或日文键盘），按键会被转换成别的内容；输入文字请使用 `set-text`。`--file` 和 `-` 适合难以加引号的文字。

`--modifier` 接受 `shift`、`control`（`ctrl`）、`option`（`alt`、`opt`）或 `command`（`cmd`、`meta`）；多个修饰键就重复使用。

`button` 名称：Android 上为 `back`、`home`、`app-switcher`、`power`、`volume-up`、`volume-down`；Apple Watch 上为 `digital-crown` 和 `side-button`。

`input` 接受一个带 `type` 的事件对象：

| `type` | 字段 |
| --- | --- |
| `tap` | `x`、`y`，可选 `duration`、`display` |
| `swipe` | `startX`、`startY`、`endX`、`endY`，可选 `duration`、`display` |
| `type` | `text` |
| `key` | `code`、`modifiers`（数组） |
| `button` | `button`，可选 `duration` |

```bash
simulator input '{"type":"key","code":"KeyV","modifiers":["command"]}'
```

### batch

`batch FILE` 在一次请求中按顺序执行 1–1000 个步骤，对于已知流程可以省去每条命令的往返时间。`-` 从 stdin 读取 JSON 数组。

```json
[{"action":"tap","selector":{"id":"next","strict":true}},
 {"action":"wait-visible","selector":{"id":"title"},"timeoutMs":5000},
 {"action":"input","event":{"type":"type","text":"Hello!"}},
 {"action":"slider","selector":{"id":"volume"},"percent":75}]
```

| `action` | 字段 |
| --- | --- |
| `tap`、`find`、`wait-visible`、`wait-hidden` | `selector`（`text`、`id`、`value`、`role`、`exact`、`strict` 或 `nodeId`），可选 `timeoutMs` |
| `slider` | `selector`、`percent` |
| `adjust` | `selector`、`steps` |
| `drag` | `start` 和 `end`（形如 `{x,y}`）、`duration`、`steps` |
| `input` | `event`，格式同 `simulator input` |
| `sleep` | `ms`，最多 60000 |

每个带选择器的步骤都会读取新的树。batch 在第一次失败处停止，不会撤销之前的步骤；结果列出每一步的结果和从零开始计数的 `failedStep`，命令以 1 退出。一次请求必须在 30 秒内开始响应，所以一个 batch 中等待和休眠的总时长要远低于这个值，否则请拆分。

### UI 自动化错误

| 消息 | 怎么办 |
| --- | --- |
| `Error: no usable element matching … within Ns` | 重新读取屏幕（`describe-ui --short`），修正选择器，或等待更久。 |
| `stale_node` | 从 `describe-ui` 或 `find` 读取新的 `nodeId`。 |
| `input_shadowed` | 运行 `simulator heal`，然后重新启动 App。 |
| Hint: the app in front returned no accessibility data …（提示：前台 App 未返回辅助功能数据……） | App 正忙。等几秒再试。 |
| `Error: set-text --timeout is at most 20 seconds: …` | 使用 20 或更小的值。 |
| `Error: scroll-to --timeout is at most 25 seconds: …` | 使用 25 或更小的值，并再次运行 `scroll-to` 继续查找。 |
| `Error: unknown --modifier M; use shift, control (ctrl), option (alt, opt) or command (cmd, meta).` | 使用其中之一。 |
| `Error: a batch is a JSON array of 1 to 1000 {"action": …} steps.` | 修正 batch 文件。 |
| `Error: batch file not found: PATH` / `Error: text file not found: PATH` | 修正路径。 |
| `Error: invalid input event JSON.` | 传入一个带 `type` 的 JSON 对象。 |
| `Error: --then-describe-ui goes with tap, swipe, type, set-text, key, button, launch and open-url.` | 去掉该选项，或在命令之后运行 `describe-ui --short`。 |
| `Error: this Simulator's gateway is too old for describe-ui --short; run describe-ui.` | 使用 `describe-ui`，或用 `shutdown` 和 `start` 重启设备。 |
| `Error: the Team Simulator gateway did not answer within N seconds.` | 操作可能已经执行了。重试前先查看（`screenshot`、`describe-ui`）。 |

## 示例

在默认设备上安装并打开新构建，同时查看它打开后的屏幕：

```bash
simulator terminate com.example.app
simulator install /path/to/Example.app
simulator launch com.example.app --then-describe-ui
```

把密码簿中的值填入密码框，然后提交：

```bash
simulator tap --text "Password"           # focus the field first
simulator fill "Staging login" --field Password
simulator tap --text "Continue" --exact --then-describe-ui
```

操控 Android 模拟器（从 `simulator list` 中取 `platform` 为 `Android` 的 id）：

```bash
simulator start --simulator ANDROID_ID
simulator install app-debug.apk --simulator ANDROID_ID
simulator permissions com.example.app --grant camera --simulator ANDROID_ID
simulator launch com.example.app --simulator ANDROID_ID
simulator logs --app com.example.app --crashes --simulator ANDROID_ID
```

截一张深色模式的截屏，然后恢复设置：

```bash
simulator appearance            # prints the current value, e.g. light
simulator appearance dark
simulator screenshot /tmp/dark.png
simulator appearance light
```
