# simulator

> Agent 用來啟動、操作、讀取和擷取團隊 iOS 模擬器、Apple Watch 模擬器與 Android 模擬器的指令。

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

`simulator` 是 Agent 在執行期間操作自己建置的 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`） | 支援 | 不支援 |
| 你自己的模擬器 | — | 絕不會被啟動、安裝或關閉 |

登入資訊與服務位址來自 Agent 的環境，不需要任何設定。兩種團隊的說明請參閱[選擇 Agent 的執行位置](https://air.build/tw/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:`。以下情況也會回傳此代碼：`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`。
- 團隊中任何 Agent 執行 `start` 都會取得同一台裝置。尚未就緒的型號可能需要幾分鐘。
- 預設裝置以外的裝置，若十分鐘內無人觀看或操作，會自動關閉。當 Agent 的沙箱閒置並關閉時，所有裝置都會被釋放。

### 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` 是 View 的資源 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 專案目前為 Beta）。請參閱 [runbuild](https://air.build/tw/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` 預設略過的 App。 |
| `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/tw/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）。這是給閱讀用的：座標、框架和點按位置仍以一般截圖為準，所以要選取點位時請擷取一般截圖。

### 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` | 畫面的無障礙樹狀結構，包含框架、ID 和 `nodeId`。大小約數十 KB。 |
| `describe-ui --short` | 以名稱呈現畫面，只有幾百個位元組：`tap`（可按下的項目）、`fill`（文字欄位及其內容）、`adjust`（滑桿、選擇器）、`disabled`、`text`（顯示的文字），以及 `keyboard` 是否已顯示。 |
| `describe-ui --x X --y Y` | 某個點上的元素。兩者都要指定。不能與 `--short` 同時使用。 |
| `find SELECTOR` | 列出所有可用的符合項目（最佳者在前）及 `excluded`，不會操作裝置。 |

想知道目前在哪個畫面時用 `--short`，需要框架或 ID 時再讀取完整樹狀結構。選擇器讀取的是同一棵樹；不會從像素辨識文字。當前景 App 忙碌而未回傳無障礙資料時，讀取會在 2 秒和 4 秒後重試，之後才失敗並提示你稍候再試；這段期間截圖仍可使用。

### 選擇器

`tap`、`find`、`wait-visible`、`wait-hidden`、`slider`、`adjust` 和 `set-text` 可以用選擇器取代座標：

| 旗標 | 說明 |
| --- | --- |
| `--text TEXT` | 元素可見標籤或值的一部分，不分大小寫。 |
| `--id ID` | 完全相符的 accessibilityIdentifier（在 Android 上為 View 的資源 ID）。 |
| `--value VALUE` | 僅比對元素值的一部分，不分大小寫。 |
| `--role ROLE` | 完全相符的平台角色，例如 `AXSlider`。 |
| `--exact` | `--text` 和 `--value` 必須完全相等，而非包含。需搭配其中之一。 |
| `--strict` | 有多個可用元素符合時直接失敗，而不排序挑選。 |
| `--node-id NODE` | 來自 `describe-ui` 或 `find` 的不透明 `nodeId`，精確指定該元素。 |

指定的每個條件都必須符合。有多個元素符合時，最佳者依序為：完全相符的文字優先於部分相符、標籤相符優先於值相符、互動元素（按鈕、欄位、開關、儲存格）優先於靜態文字，接著是較小的元素，再依由上到下、由左到右排序。隱藏、在畫面外或沒有框架的符合項目不會被使用；它們會連同原因列在 `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；每一步的大小由控制項決定。它的選擇器一律為 strict。結果包含 `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
```
