--- url: /advanced/bdd-style-scripts-with-gherkin.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # BDD-style scripts with Gherkin > This feature is available starting in Midscene 1.10. > > BDD-related capabilities are still in Beta. The API may change in future releases. Gherkin is a plain-text syntax for describing behavior examples. It is commonly used in BDD (Behavior-Driven Development) workflows. A BDD scenario usually contains three kinds of steps: `Given` describes the precondition, `When` describes the user action, and `Then` describes the expected result. For example, when you need to test adding a todo item, you can write the case as the following Gherkin script. ```gherkin Scenario: Add a todo item Given the todo page is open When I add a todo item named "Buy milk" Then the todo list should contain "Buy milk" ``` Longer GUI cases can also be written in one `Scenario`. You can organize the steps by business phase, and each phase can use a group of `Given`, `When`, and `Then`. ```gherkin Scenario: Place an order with a saved address Given the shopping cart contains "Midscene Mug" When I open the cart page Then the cart should show "Midscene Mug" And the subtotal should be visible Given the checkout page is open When I choose the saved shipping address Then the shipping address section should show the selected address Given the payment section is visible When I choose the saved credit card and submit the order Then the order confirmation page should be displayed And the confirmation page should show an order number ``` This style is useful when one business scenario naturally contains several UI phases, such as cart review, shipping selection, payment, and final confirmation. In AI-driven GUI automation, Gherkin is a natural fit for describing operation cases. It keeps the readability of natural language while providing a stable step structure. This structure also helps models generate more consistent cases. See the official [Cucumber Gherkin reference](https://cucumber.io/docs/gherkin/reference) for the full Gherkin syntax. ## Supported rules Midscene supports only a subset of Gherkin. This subset is designed around a single `Scenario`, and is suitable for describing a complete GUI operation flow. ### Step mapping - `Given`: calls `aiAct`, and prepares the precondition. - `When`: calls `aiAct`, and performs the user action. - `Then`: calls `aiAssert`, and verifies the page result. - `And`, `But`: reuse the previous primary keyword. For example, an `And` after `Then` also calls `aiAssert`. Keyword matching is case-insensitive. Therefore, `AND`, `and`, and `And` are all recognized. ### Scenario limits Only one `Scenario:` is supported each time. If the input contains multiple `Scenario:` blocks, Midscene throws an error. You can also omit `Scenario:` and write the steps directly. ```gherkin Given the todo page is open When I add a todo item named "Buy milk" Then the todo list should contain "Buy milk" ``` ### Notes Midscene splits each Gherkin step into an independent `aiAct` or `aiAssert` call. Each step should be complete, and should clearly describe the target, the action, and the expected result. Do not depend on omitted information or vague references from previous steps. For example, do not write only "click it" or "check the result". Instead, write the target to click and the result to check. The following example cannot run correctly. The steps are isolated from each other, so later steps do not know what "it" and "the result" refer to. ```gherkin Given the todo page is open When I add a todo item named "Buy milk" And click it Then check the result ``` Write it this way instead. ```gherkin Given the todo page is open When I add a todo item named "Buy milk" And I click the "Buy milk" todo item Then the "Buy milk" todo item should be marked as completed ``` ### Not supported The following Gherkin features are not supported: - `Feature` - `Background` - `Scenario Outline` or `Scenario Template` - `Examples` - `Rule` - data tables - doc strings - variable replacement, placeholder expansion, or template syntax - multiple `Scenario:` blocks in the same input Midscene does not extend Gherkin into a scripting language. It only reads `Scenario` and step keywords, then passes each step to the Agent. Loops, conditions, variable replacement, and batch generation should happen before calling Midscene. If you need reusable templates, implement a Gherkin generator in your project. The generator should output the final plain-text `Scenario`, then pass it to `runGherkinScenario`. ## Use in JavaScript In JavaScript or TypeScript scripts, call `agent.runGherkinScenario()` directly. It receives a Gherkin text string and executes the steps in order. The following example uses the Playwright fixture to get an Agent. ```ts import { test } from '@midscene/web/playwright'; test('add a todo item', async ({ page, agentForPage }) => { await page.goto('http://localhost:3000/todos'); const agent = await agentForPage(page); await agent.runGherkinScenario(` Scenario: Add a todo item Given the todo page is open When I add a todo item named "Buy milk" Then the todo list should contain "Buy milk" And the todo count should be 1 `); }); ``` The second argument accepts runtime options. For example, you can provide temporary context for this run. ```ts await agent.runGherkinScenario( ` Scenario: Add a todo item Given the todo page is open When I add a todo item named "Buy milk" Then the todo list should contain "Buy milk" `, { context: 'This is a todo demo app. Use the input box and the add button on the page.', }, ); ``` ## Use in YAML Use the `runGherkinScenario` step in a YAML flow. The value should be a block string containing one scenario. ```yaml web: url: http://localhost:3000/todos tasks: - name: Add a todo item flow: - runGherkinScenario: | Scenario: Add a todo item Given the todo page is open When I add a todo item named "Buy milk" Then the todo list should contain "Buy milk" And the todo count should be 1 ``` During YAML execution, Midscene runs the scenario step by step. `Given` and `When` steps call `aiAct`, while `Then` and the following `And` step call `aiAssert`. ## Remarks `runGherkinScenario` disables cache inside the scenario. This means that after `Given` and `When` are mapped to `aiAct`, they do not use the `aiAct` planning cache. This makes each Gherkin step interpreted from the current page state, and avoids incorrect behavior caused by reusing stale steps. --- url: /android-world-benchmark-report.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Midscene AndroidWorld Benchmark Report This is Midscene's test report for the AndroidWorld benchmark. In this run, Midscene achieved **Pass\@1 93.10%**, **Pass\@2 95.69%**, and **Pass\@3 97.41%**. :::info About AndroidWorld [AndroidWorld](https://github.com/google-research/android_world) is an Android agent benchmark from Google Research. It runs on a live Android emulator and evaluates agents on 116 programmatic tasks across 20 real-world Android apps, with task initialization and validation handled by the benchmark. ::: ## Run Configuration | Field | Value | | --------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | Model Name | `Gemini-3.5-Flash` | | Midscene version | `1.9.5` | | DeepThink | on | | `MIDSCENE_REPLANNING_CYCLE_LIMIT` | 120 | | AndroidWorld setup | Stability fixes were applied to the AndroidWorld project to reduce flaky benchmark runs. See examples below. | | Validation notes | A small number of AndroidWorld validators were aligned with the task intent. The affected cases are listed below. | ## Stability Improvements The following changes did not change the task intent. They made benchmark execution more stable by reducing browser rendering races, stale accessibility reads, and setup timing issues. | Change | Affected cases | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Force canvas pixels to flush after drawing, then use thicker rounded strokes so target colors remain stable in the final canvas pixels. | `BrowserDraw` | | Retry reading the `Success!` text from the accessibility tree after browser tasks finish. | `BrowserMaze`
`BrowserMultiply`
`BrowserDraw` | | Before SMS tasks start, prepare the required incoming messages and contacts; now verify those messages are visible in the inbox and those contacts are visible in Contacts before the agent runs. | `SimpleSmsReplyMostRecent`
`SimpleSmsSendReceivedAddress` | | Wait for Pro Expense to create its database tables before validators write test data. | `ExpenseAddMultiple`
`ExpenseAddMultipleFromGallery`
`ExpenseAddMultipleFromMarkor`
`ExpenseAddSingle`
`ExpenseDeleteDuplicates`
`ExpenseDeleteDuplicates2`
`ExpenseDeleteMultiple`
`ExpenseDeleteMultiple2`
`ExpenseDeleteSingle` | | Preload OsmAnd offline map files into the app data directory and wait for OsmAnd to extract its built-in basemap before map tasks run. | `OsmAndFavorite`
`OsmAndMarker`
`OsmAndTrack` | ## Validation Condition Updates The following AndroidWorld validation checks were changed on the `main` branch used for this benchmark: | Change | Affected cases | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Calendar "after start time" now validates against an event one minute after the boundary, avoiding ambiguity across models about whether `after` includes the boundary time. | `SimpleCalendarFirstEventAfterStartTime` | | Expense notes imported from Markor accept the extra `Reimbursable.` suffix that Markor can include; note comparison ignores that suffix and terminal period differences. | `ExpenseAddMultipleFromMarkor` | | Markor merged notes accept either single-newline or blank-line separation, and also accept Markor's default `.md` extension when it is auto-added. | `MarkorMergeNotes` | | Recipe quantity fields allow omitted units while still rejecting wrong amounts or incompatible units. | `RecipeAddSingleRecipe`
`RecipeAddMultipleRecipes`
`RecipeAddMultipleRecipesFromMarkor`
`RecipeAddMultipleRecipesFromMarkor2`
`RecipeAddMultipleRecipesFromImage`
`NotesRecipeIngredientCount` | | Minimum brightness is validated against Android's actual minimum setting value, `0`, instead of `1`. | `SystemBrightnessMin`
`SystemBrightnessMinVerify` | ## Report Files Detailed reports are listed below for reference. Round 1 (115 reports · 108 PASS · 7 FAIL) | # | Task | Status | Report | | --- | ------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | AudioRecorderRecordAudio | PASS | report | | 2 | AudioRecorderRecordAudioWithFileName | PASS | report | | 3 | BrowserDraw | PASS | report | | 4 | BrowserMaze | PASS | report | | 5 | BrowserMultiply | PASS | report | | 6 | CameraTakePhoto | PASS | report | | 7 | CameraTakeVideo | PASS | report | | 8 | ClockStopWatchPausedVerify | PASS | report | | 9 | ClockStopWatchRunning | PASS | report | | 10 | ClockTimerEntry | PASS | report | | 11 | ContactsAddContact | PASS | report | | 12 | ContactsNewContactDraft | PASS | report | | 13 | ExpenseAddMultiple | PASS | report | | 14 | ExpenseAddMultipleFromGallery | PASS | report | | 15 | ExpenseAddMultipleFromMarkor | FAIL | report | | 16 | ExpenseAddSingle | PASS | report | | 17 | ExpenseDeleteDuplicates | PASS | report | | 18 | ExpenseDeleteDuplicates2 | PASS | report | | 19 | ExpenseDeleteMultiple | PASS | report | | 20 | ExpenseDeleteMultiple2 | PASS | report | | 21 | ExpenseDeleteSingle | PASS | report | | 22 | FilesDeleteFile | PASS | report | | 23 | FilesMoveFile | PASS | report | | 24 | MarkorAddNoteHeader | PASS | report | | 25 | MarkorChangeNoteContent | PASS | report | | 26 | MarkorCreateFolder | PASS | report | | 27 | MarkorCreateNote | PASS | report | | 28 | MarkorCreateNoteAndSms | PASS | report | | 29 | MarkorCreateNoteFromClipboard | PASS | report | | 30 | MarkorDeleteAllNotes | PASS | report | | 31 | MarkorDeleteNewestNote | PASS | report | | 32 | MarkorDeleteNote | PASS | report | | 33 | MarkorEditNote | PASS | report | | 34 | MarkorMergeNotes | PASS | report | | 35 | MarkorMoveNote | PASS | report | | 36 | MarkorTranscribeReceipt | PASS | report | | 37 | MarkorTranscribeVideo | FAIL | report | | 38 | OpenAppTaskEval | PASS | report | | 39 | OsmAndFavorite | PASS | report | | 40 | OsmAndMarker | FAIL | report | | 42 | RecipeAddMultipleRecipes | PASS | report | | 43 | RecipeAddMultipleRecipesFromImage | FAIL | report | | 44 | RecipeAddMultipleRecipesFromMarkor | PASS | report | | 45 | RecipeAddMultipleRecipesFromMarkor2 | PASS | report | | 46 | RecipeAddSingleRecipe | PASS | report | | 47 | RecipeDeleteDuplicateRecipes | PASS | report | | 48 | RecipeDeleteDuplicateRecipes2 | FAIL | report | | 49 | RecipeDeleteDuplicateRecipes3 | FAIL | report | | 50 | RecipeDeleteMultipleRecipes | PASS | report | | 51 | RecipeDeleteMultipleRecipesWithConstraint | PASS | report | | 52 | RecipeDeleteMultipleRecipesWithNoise | PASS | report | | 53 | RecipeDeleteSingleRecipe | PASS | report | | 54 | RecipeDeleteSingleWithRecipeWithNoise | PASS | report | | 55 | RetroCreatePlaylist | PASS | report | | 56 | RetroPlayingQueue | PASS | report | | 57 | RetroPlaylistDuration | PASS | report | | 58 | RetroSavePlaylist | PASS | report | | 59 | SaveCopyOfReceiptTaskEval | PASS | report | | 60 | SimpleCalendarAddOneEvent | PASS | report | | 61 | SimpleCalendarAddOneEventInTwoWeeks | PASS | report | | 62 | SimpleCalendarAddOneEventRelativeDay | PASS | report | | 63 | SimpleCalendarAddOneEventTomorrow | PASS | report | | 64 | SimpleCalendarAddRepeatingEvent | PASS | report | | 65 | SimpleCalendarDeleteEvents | PASS | report | | 66 | SimpleCalendarDeleteEventsOnRelativeDay | PASS | report | | 67 | SimpleCalendarDeleteOneEvent | PASS | report | | 68 | SimpleDrawProCreateDrawing | PASS | report | | 69 | SimpleSmsReply | PASS | report | | 70 | SimpleSmsReplyMostRecent | PASS | report | | 71 | SimpleSmsResend | PASS | report | | 72 | SimpleSmsSend | PASS | report | | 73 | SimpleSmsSendClipboardContent | PASS | report | | 74 | SimpleSmsSendReceivedAddress | PASS | report | | 75 | SystemBluetoothTurnOff | PASS | report | | 76 | SystemBluetoothTurnOffVerify | PASS | report | | 77 | SystemBluetoothTurnOn | PASS | report | | 78 | SystemBluetoothTurnOnVerify | PASS | report | | 79 | SystemBrightnessMax | PASS | report | | 80 | SystemBrightnessMaxVerify | PASS | report | | 81 | SystemBrightnessMin | PASS | report | | 82 | SystemBrightnessMinVerify | PASS | report | | 83 | SystemCopyToClipboard | FAIL | report | | 84 | SystemWifiTurnOff | PASS | report | | 85 | SystemWifiTurnOffVerify | PASS | report | | 86 | SystemWifiTurnOn | PASS | report | | 87 | SystemWifiTurnOnVerify | PASS | report | | 88 | TurnOffWifiAndTurnOnBluetooth | PASS | report | | 89 | TurnOnWifiAndOpenApp | PASS | report | | 90 | VlcCreatePlaylist | PASS | report | | 91 | VlcCreateTwoPlaylists | PASS | report | | 92 | NotesIsTodo | PASS | report | | 93 | NotesMeetingAttendeeCount | PASS | report | | 94 | NotesRecipeIngredientCount | PASS | report | | 95 | NotesTodoItemCount | PASS | report | | 96 | SimpleCalendarAnyEventsOnDate | PASS | report | | 97 | SimpleCalendarEventOnDateAtTime | PASS | report | | 98 | SimpleCalendarEventsInNextWeek | PASS | report | | 99 | SimpleCalendarEventsInTimeRange | PASS | report | | 100 | SimpleCalendarEventsOnDate | PASS | report | | 101 | SimpleCalendarFirstEventAfterStartTime | PASS | report | | 102 | SimpleCalendarLocationOfEvent | PASS | report | | 103 | SimpleCalendarNextEvent | PASS | report | | 104 | SimpleCalendarNextMeetingWithPerson | PASS | report | | 105 | SportsTrackerActivitiesCountForWeek | PASS | report | | 106 | SportsTrackerActivitiesOnDate | PASS | report | | 107 | SportsTrackerActivityDuration | PASS | report | | 108 | SportsTrackerLongestDistanceActivity | PASS | report | | 109 | SportsTrackerTotalDistanceForCategoryOverInterval | PASS | report | | 110 | SportsTrackerTotalDurationForCategoryThisWeek | PASS | report | | 111 | TasksCompletedTasksForDate | PASS | report | | 112 | TasksDueNextWeek | PASS | report | | 113 | TasksDueOnDate | PASS | report | | 114 | TasksHighPriorityTasks | PASS | report | | 115 | TasksHighPriorityTasksDueOnDate | PASS | report | | 116 | TasksIncompleteTasksOnDate | PASS | report | Round 2 (7 reports · 3 PASS · 4 FAIL) | # | Task | Status | Report | | -- | --------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 37 | MarkorTranscribeVideo | FAIL | report | | 40 | OsmAndMarker | FAIL | report | | 41 | OsmAndTrack | PASS | report | | 43 | RecipeAddMultipleRecipesFromImage | PASS | report | | 48 | RecipeDeleteDuplicateRecipes2 | FAIL | report | | 49 | RecipeDeleteDuplicateRecipes3 | FAIL | report | | 83 | SystemCopyToClipboard | PASS | report | Round 3 (5 reports · 2 PASS · 3 FAIL) | # | Task | Status | Report | | -- | ----------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 15 | ExpenseAddMultipleFromMarkor | PASS | report | | 37 | MarkorTranscribeVideo | FAIL | report | | 40 | OsmAndMarker | PASS | report | | 48 | RecipeDeleteDuplicateRecipes2 | FAIL | report | | 49 | RecipeDeleteDuplicateRecipes3 | FAIL | report | --- url: /app-control-bench-report.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Midscene AppControlBench Benchmark Report This is Midscene's benchmark report for AppControlBench. In this evaluation, each model ran the same set of 60 tasks, with the following results: | Model | Completion | Time / run | Cost / run | Task outcomes | | --- | --- | --- | --- | --- | | Doubao Seed 2.1 Turbo | 98% | 52s | $0.0099/¥0.0670 | Pass@1: 96.67% · Pass: 58 · Partial: 1 · Fail: 1 | | Qwen3.7 Plus | 97% | 54s | $0.0097/¥0.0657 | Pass@1: 93.33% · Pass: 56 · Partial: 4 · Fail: 0 | | DeepSeek V4 Flash Vision Exp | 90% | 1m 26s | $0.0045/¥0.0308 | Pass@1: 86.67% · Pass: 52 · Partial: 4 · Fail: 4 | > Note: Doubao Seed 2.1 Turbo costs use [Volcengine's official pricing](https://ark.volcengine.com/region:cn-beijing/model/detail?name=doubao-seed-2-1-turbo): CNY ¥3 / M input tokens, ¥0.6 / M cached input tokens, and ¥15 / M output tokens. Other model costs use OpenRouter pricing. USD values use ¥6.8 per $1. **The results show that the Midscene + GUI vision approach is highly competitive in both cost and pass rate.** ![Cases completed per dollar by model and tool combination, comparing Midscene with agent-device iOS baselines; higher is better](/images/benchmarks/app-control-bench-cost-efficiency-en.png) ![Pass at one on the same 60 cases by Midscene model, higher is better](/images/benchmarks/app-control-bench-pass-at-1-en.png) :::info About AppControlBench [AppControlBench](https://github.com/software-mansion/app-control-bench) evaluates how well an Agent can operate real iOS apps in isolated Simulator runs. The final screenshot is graded against a task-specific solved-screen description. Each run covers 30 Bluesky tasks and 30 Element iOS tasks. ::: ## Run configuration | Field | Value | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Test date | 2026-08-25 to 2026-08-27 | | Model Name | Doubao Seed 2.1 Turbo, Qwen3.7 Plus, DeepSeek V4 Flash Vision Exp | | Midscene version | `1.12.0` | | DeepThink | off | | Device | iOS Simulator | | Bluesky version | `1.122.0` | | Element iOS version | `1.11.40` | | Number of tasks | 60 per model | | AppControlBench project | The Midscene adapter delegated Agent execution to `@midscene/ios` while AppControlBench retained task reset, Simulator lifecycle, final screenshot capture, and grading. | | Evaluation rules | The original target states and judge rules were retained; the action intent for 1 case was calibrated. | ## Case Intent Calibration For this evaluation, the action-route description of 1 case was calibrated against the actual UI of the pinned Element iOS version. The calibration only removes a stale or unavailable UI-entry description; it does not change the final target state or judge rules of the case. | Case | Before | After | Reason for change | | ------------ | ----------------------------------------------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `element-07` | Open the "Project Phoenix" room and open its room-options menu (the '...' in the header). | Open the "Project Phoenix" room info/options screen. | The pinned Element iOS version does not provide a header `...`; only the action route was calibrated, while the target state and judge rules remain unchanged. | ## Report files Doubao Seed 2.1 Turbo · Pass@1 96.67% · 58 PASS · 1 PARTIAL · 1 FAIL | # | Task | Status | Model Cost | Report | | --- | --- | --- | --- | --- | | 1 | bsky-01 | PASS | $0.0038/¥0.0259 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-1-bsky-01__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 2 | bsky-02 | PASS | $0.0038/¥0.0259 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-2-bsky-02__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 3 | bsky-03 | PASS | $0.0079/¥0.0537 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-3-bsky-03__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 4 | bsky-04 | PASS | $0.0060/¥0.0405 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-4-bsky-04__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 5 | bsky-05 | PASS | $0.0039/¥0.0263 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-5-bsky-05__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 6 | bsky-06 | PASS | $0.0040/¥0.0272 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-6-bsky-06__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 7 | bsky-07 | PASS | $0.0039/¥0.0268 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-7-bsky-07__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 8 | bsky-08 | PASS | $0.0130/¥0.0884 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-8-bsky-08__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 9 | bsky-09 | PASS | $0.0081/¥0.0552 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-9-bsky-09__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 10 | bsky-10 | PASS | $0.0060/¥0.0410 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-10-bsky-10__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 11 | bsky-11 | PASS | $0.0038/¥0.0256 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-11-bsky-11__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 12 | bsky-12 | PASS | $0.0038/¥0.0258 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-12-bsky-12__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 13 | bsky-13 | PASS | $0.0038/¥0.0259 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-13-bsky-13__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 14 | bsky-14 | PASS | $0.0104/¥0.0704 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-14-bsky-14__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 15 | bsky-15 | PASS | $0.0104/¥0.0706 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-15-bsky-15__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 16 | bsky-16 | PASS | $0.0240/¥0.1631 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-16-bsky-16__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 17 | bsky-17 | PASS | $0.0059/¥0.0399 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-17-bsky-17__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 18 | bsky-18 | PASS | $0.0038/¥0.0255 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-18-bsky-18__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 19 | bsky-19 | PASS | $0.0080/¥0.0545 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-19-bsky-19__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 20 | bsky-20 | PASS | $0.0080/¥0.0547 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-20-bsky-20__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 21 | bsky-21 | PASS | $0.0059/¥0.0399 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-21-bsky-21__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 22 | bsky-22 | PASS | $0.0037/¥0.0254 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-22-bsky-22__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 23 | bsky-23 | PASS | $0.0058/¥0.0394 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-23-bsky-23__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 24 | bsky-24 | PASS | $0.0082/¥0.0554 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-24-bsky-24__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 25 | bsky-25 | FAIL | $0.0079/¥0.0535 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-25-bsky-25__group-0-39e22f33-4039-4891-854c-009333ade66f-Fail.html) | | 26 | bsky-26 | PASS | $0.0152/¥0.1030 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-26-bsky-26__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 27 | bsky-27 | PASS | $0.0174/¥0.1183 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-27-bsky-27__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 28 | bsky-28 | PASS | $0.0080/¥0.0542 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-28-bsky-28__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 29 | bsky-29 | PASS | $0.0080/¥0.0541 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-29-bsky-29__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 30 | bsky-30 | PASS | $0.0106/¥0.0723 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-30-bsky-30__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 31 | element-01 | PASS | $0.0037/¥0.0252 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-31-element-01__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 32 | element-02 | PASS | $0.0038/¥0.0259 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-32-element-02__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 33 | element-03 | PASS | $0.0101/¥0.0686 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-33-element-03__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 34 | element-04 | PASS | $0.0057/¥0.0390 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-34-element-04__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 35 | element-05 | PASS | $0.0066/¥0.0447 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-35-element-05__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 36 | element-06 | PARTIAL | $0.0988/¥0.6720 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-36-element-06__group-0-39e22f33-4039-4891-854c-009333ade66f-Partial.html) | | 37 | element-07 | PASS | $0.0059/¥0.0400 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-37-element-07__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 38 | element-08 | PASS | $0.0103/¥0.0700 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-38-element-08__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 39 | element-09 | PASS | $0.0040/¥0.0275 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-39-element-09__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 40 | element-10 | PASS | $0.0187/¥0.1272 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-40-element-10__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 41 | element-11 | PASS | $0.0068/¥0.0460 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-41-element-11__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 42 | element-12 | PASS | $0.0059/¥0.0404 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-42-element-12__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 43 | element-13 | PASS | $0.0106/¥0.0724 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-43-element-13__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 44 | element-14 | PASS | $0.0060/¥0.0410 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-44-element-14__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 45 | element-15 | PASS | $0.0081/¥0.0554 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-45-element-15__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 46 | element-16 | PASS | $0.0083/¥0.0567 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-46-element-16__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 47 | element-17 | PASS | $0.0080/¥0.0543 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-47-element-17__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 48 | element-18 | PASS | $0.0105/¥0.0714 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-48-element-18__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 49 | element-19 | PASS | $0.0182/¥0.1240 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-49-element-19__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 50 | element-20 | PASS | $0.0038/¥0.0256 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-50-element-20__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 51 | element-21 | PASS | $0.0119/¥0.0810 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-51-element-21__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 52 | element-22 | PASS | $0.0156/¥0.1062 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-52-element-22__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 53 | element-23 | PASS | $0.0081/¥0.0550 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-53-element-23__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 54 | element-24 | PASS | $0.0129/¥0.0880 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-54-element-24__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 55 | element-25 | PASS | $0.0059/¥0.0404 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-55-element-25__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 56 | element-26 | PASS | $0.0038/¥0.0257 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-56-element-26__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 57 | element-27 | PASS | $0.0160/¥0.1087 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-57-element-27__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 58 | element-28 | PASS | $0.0100/¥0.0683 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-58-element-28__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 59 | element-29 | PASS | $0.0102/¥0.0693 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-59-element-29__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | | 60 | element-30 | PASS | $0.0100/¥0.0680 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/doubao-20260825/Task-60-element-30__group-0-39e22f33-4039-4891-854c-009333ade66f-Pass.html) | Qwen3.7 Plus · Pass@1 93.33% · 56 PASS · 4 PARTIAL · 0 FAIL | # | Task | Status | Model Cost | Report | | --- | --- | --- | --- | --- | | 1 | bsky-01 | PASS | $0.0073/¥0.0497 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-1-bsky-01__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 2 | bsky-02 | PASS | $0.0074/¥0.0501 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-2-bsky-02__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 3 | bsky-03 | PASS | $0.0108/¥0.0736 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-3-bsky-03__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 4 | bsky-04 | PASS | $0.0092/¥0.0624 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-4-bsky-04__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 5 | bsky-05 | PASS | $0.0053/¥0.0362 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-5-bsky-05__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 6 | bsky-06 | PASS | $0.0075/¥0.0507 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-6-bsky-06__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 7 | bsky-07 | PASS | $0.0075/¥0.0507 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-7-bsky-07__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 8 | bsky-08 | PASS | $0.0170/¥0.1155 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-8-bsky-08__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 9 | bsky-09 | PASS | $0.0110/¥0.0746 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-9-bsky-09__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 10 | bsky-10 | PASS | $0.0111/¥0.0756 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-10-bsky-10__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 11 | bsky-11 | PASS | $0.0053/¥0.0360 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-11-bsky-11__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 12 | bsky-12 | PASS | $0.0053/¥0.0357 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-12-bsky-12__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 13 | bsky-13 | PASS | $0.0054/¥0.0365 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-13-bsky-13__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 14 | bsky-14 | PASS | $0.0086/¥0.0585 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-14-bsky-14__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 15 | bsky-15 | PASS | $0.0107/¥0.0724 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-15-bsky-15__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 16 | bsky-16 | PARTIAL | $0.0196/¥0.1332 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-16-bsky-16__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Partial.html) | | 17 | bsky-17 | PASS | $0.0050/¥0.0342 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-17-bsky-17__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 18 | bsky-18 | PASS | $0.0033/¥0.0224 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-18-bsky-18__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 19 | bsky-19 | PASS | $0.0067/¥0.0457 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-19-bsky-19__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 20 | bsky-20 | PASS | $0.0068/¥0.0460 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-20-bsky-20__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 21 | bsky-21 | PASS | $0.0049/¥0.0335 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-21-bsky-21__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 22 | bsky-22 | PASS | $0.0032/¥0.0219 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-22-bsky-22__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 23 | bsky-23 | PASS | $0.0050/¥0.0340 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-23-bsky-23__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 24 | bsky-24 | PASS | $0.0069/¥0.0469 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-24-bsky-24__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 25 | bsky-25 | PARTIAL | $0.0068/¥0.0463 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-25-bsky-25__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Partial.html) | | 26 | bsky-26 | PASS | $0.0125/¥0.0849 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-26-bsky-26__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 27 | bsky-27 | PASS | $0.0145/¥0.0988 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-27-bsky-27__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 28 | bsky-28 | PASS | $0.0068/¥0.0461 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-28-bsky-28__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 29 | bsky-29 | PASS | $0.0068/¥0.0462 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-29-bsky-29__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 30 | bsky-30 | PASS | $0.0171/¥0.1160 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-30-bsky-30__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 31 | element-01 | PASS | $0.0052/¥0.0356 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-31-element-01__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 32 | element-02 | PASS | $0.0032/¥0.0214 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-32-element-02__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 33 | element-03 | PASS | $0.0087/¥0.0593 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-33-element-03__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 34 | element-04 | PASS | $0.0048/¥0.0326 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-34-element-04__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 35 | element-05 | PASS | $0.0107/¥0.0727 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-35-element-05__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 36 | element-06 | PARTIAL | $0.0640/¥0.4355 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-36-element-06__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Partial.html) | | 37 | element-07 | PASS | $0.0088/¥0.0600 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-37-element-07__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 38 | element-08 | PASS | $0.0086/¥0.0582 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-38-element-08__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 39 | element-09 | PASS | $0.0032/¥0.0217 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-39-element-09__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 40 | element-10 | PASS | $0.0234/¥0.1593 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-40-element-10__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 41 | element-11 | PASS | $0.0050/¥0.0341 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-41-element-11__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 42 | element-12 | PASS | $0.0050/¥0.0338 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-42-element-12__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 43 | element-13 | PASS | $0.0070/¥0.0474 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-43-element-13__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 44 | element-14 | PASS | $0.0051/¥0.0345 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-44-element-14__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 45 | element-15 | PASS | $0.0068/¥0.0461 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-45-element-15__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 46 | element-16 | PARTIAL | $0.0346/¥0.2352 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-46-element-16__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Partial.html) | | 47 | element-17 | PASS | $0.0206/¥0.1403 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-47-element-17__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 48 | element-18 | PASS | $0.0112/¥0.0761 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-48-element-18__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 49 | element-19 | PASS | $0.0108/¥0.0738 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-49-element-19__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 50 | element-20 | PASS | $0.0032/¥0.0219 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-50-element-20__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 51 | element-21 | PASS | $0.0033/¥0.0222 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-51-element-21__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 52 | element-22 | PASS | $0.0128/¥0.0872 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-52-element-22__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 53 | element-23 | PASS | $0.0069/¥0.0466 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-53-element-23__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 54 | element-24 | PASS | $0.0109/¥0.0739 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-54-element-24__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 55 | element-25 | PASS | $0.0050/¥0.0341 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-55-element-25__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 56 | element-26 | PASS | $0.0033/¥0.0224 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-56-element-26__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 57 | element-27 | PASS | $0.0051/¥0.0344 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-57-element-27__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 58 | element-28 | PASS | $0.0106/¥0.0723 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-58-element-28__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 59 | element-29 | PASS | $0.0087/¥0.0588 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-59-element-29__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | | 60 | element-30 | PASS | $0.0087/¥0.0590 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/qwen-20260825/Task-60-element-30__group-0-2f618b11-f26d-4aeb-b861-02f7ee9795fd-Pass.html) | DeepSeek V4 Flash Vision Exp · Pass@1 86.67% · 52 PASS · 4 PARTIAL · 4 FAIL | # | Task | Status | Model Cost | Report | | --- | --- | --- | --- | --- | | 1 | bsky-01 | PASS | $0.0005/¥0.0035 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-1-bsky-01__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 2 | bsky-02 | PASS | $0.0005/¥0.0035 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-2-bsky-02__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 3 | bsky-03 | PASS | $0.0015/¥0.0100 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-3-bsky-03__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 4 | bsky-04 | PASS | $0.0009/¥0.0062 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-4-bsky-04__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 5 | bsky-05 | PASS | $0.0005/¥0.0037 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-5-bsky-05__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 6 | bsky-06 | PASS | $0.0021/¥0.0144 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-6-bsky-06__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 7 | bsky-07 | PASS | $0.0010/¥0.0066 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-7-bsky-07__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 8 | bsky-08 | PASS | $0.0019/¥0.0128 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-8-bsky-08__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 9 | bsky-09 | FAIL | $0.0155/¥0.1055 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-9-bsky-09__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Fail.html) | | 10 | bsky-10 | PASS | $0.0018/¥0.0121 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-10-bsky-10__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 11 | bsky-11 | PASS | $0.0011/¥0.0077 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-11-bsky-11__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 12 | bsky-12 | PASS | $0.0011/¥0.0073 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-12-bsky-12__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 13 | bsky-13 | PASS | $0.0012/¥0.0082 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-13-bsky-13__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 14 | bsky-14 | PASS | $0.0029/¥0.0200 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-14-bsky-14__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 15 | bsky-15 | PASS | $0.0012/¥0.0081 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-15-bsky-15__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 16 | bsky-16 | PARTIAL | $0.0160/¥0.1085 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-16-bsky-16__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Partial.html) | | 17 | bsky-17 | PASS | $0.0017/¥0.0114 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-17-bsky-17__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 18 | bsky-18 | PASS | $0.0011/¥0.0078 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-18-bsky-18__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 19 | bsky-19 | PASS | $0.0025/¥0.0168 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-19-bsky-19__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 20 | bsky-20 | PASS | $0.0022/¥0.0152 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-20-bsky-20__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 21 | bsky-21 | PASS | $0.0023/¥0.0156 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-21-bsky-21__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 22 | bsky-22 | PASS | $0.0011/¥0.0074 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-22-bsky-22__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 23 | bsky-23 | PASS | $0.0017/¥0.0119 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-23-bsky-23__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 24 | bsky-24 | PARTIAL | $0.0072/¥0.0493 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-24-bsky-24__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Partial.html) | | 25 | bsky-25 | PASS | $0.0029/¥0.0199 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-25-bsky-25__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 26 | bsky-26 | PASS | $0.0025/¥0.0171 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-26-bsky-26__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 27 | bsky-27 | PASS | $0.0034/¥0.0231 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-27-bsky-27__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 28 | bsky-28 | PASS | $0.0023/¥0.0157 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-28-bsky-28__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 29 | bsky-29 | PASS | $0.0023/¥0.0159 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-29-bsky-29__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 30 | bsky-30 | FAIL | $0.0290/¥0.1970 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-30-bsky-30__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Fail.html) | | 31 | element-01 | PASS | $0.0010/¥0.0069 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-31-element-01__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 32 | element-02 | PASS | $0.0010/¥0.0071 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-32-element-02__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 33 | element-03 | PASS | $0.0030/¥0.0201 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-33-element-03__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 34 | element-04 | PASS | $0.0038/¥0.0256 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-34-element-04__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 35 | element-05 | PASS | $0.0018/¥0.0122 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-35-element-05__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 36 | element-06 | FAIL | $0.0232/¥0.1575 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-36-element-06__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Fail.html) | | 37 | element-07 | PASS | $0.0019/¥0.0127 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-37-element-07__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 38 | element-08 | PASS | $0.0028/¥0.0193 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-38-element-08__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 39 | element-09 | PASS | $0.0011/¥0.0077 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-39-element-09__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 40 | element-10 | PASS | $0.0024/¥0.0161 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-40-element-10__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 41 | element-11 | PASS | $0.0019/¥0.0131 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-41-element-11__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 42 | element-12 | PASS | $0.0019/¥0.0130 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-42-element-12__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 43 | element-13 | PASS | $0.0026/¥0.0176 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-43-element-13__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 44 | element-14 | PASS | $0.0020/¥0.0139 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-44-element-14__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 45 | element-15 | PASS | $0.0010/¥0.0067 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-45-element-15__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 46 | element-16 | PARTIAL | $0.0549/¥0.3734 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-46-element-16__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Partial.html) | | 47 | element-17 | PASS | $0.0026/¥0.0178 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-47-element-17__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 48 | element-18 | PASS | $0.0027/¥0.0182 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-48-element-18__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 49 | element-19 | PARTIAL | $0.0106/¥0.0723 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-49-element-19__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Partial.html) | | 50 | element-20 | PASS | $0.0011/¥0.0075 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-50-element-20__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 51 | element-21 | FAIL | $0.0236/¥0.1604 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-51-element-21__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Fail.html) | | 52 | element-22 | PASS | $0.0024/¥0.0160 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-52-element-22__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 53 | element-23 | PASS | $0.0014/¥0.0094 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-53-element-23__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 54 | element-24 | PASS | $0.0020/¥0.0138 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-54-element-24__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 55 | element-25 | PASS | $0.0009/¥0.0059 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-55-element-25__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 56 | element-26 | PASS | $0.0006/¥0.0039 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-56-element-26__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 57 | element-27 | PASS | $0.0010/¥0.0065 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-57-element-27__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 58 | element-28 | PASS | $0.0016/¥0.0107 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-58-element-28__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 59 | element-29 | PASS | $0.0016/¥0.0107 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-59-element-29__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | | 60 | element-30 | PASS | $0.0016/¥0.0107 | [report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/AppControlBench/deepseek-20260825/Task-60-element-30__group-0-7d8b44f7-2b52-4211-a922-746938a7509a-Pass.html) | --- url: /automate-with-scripts-in-yaml.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Automate with scripts in YAML :::info Compatibility remains; migrate to Midscene Test for new work “Legacy YAML” specifically means the YAML automation protocol provided by `@midscene/cli`: a workflow uses top-level `tasks`, each task contains `flow`, platform and Agent runtime configuration commonly lives in YAML, and execution uses the `midscene` command or YAML batch configuration with fields such as `files`, `setup`, and `concurrent`. The legacy path is now in maintenance mode. Existing projects remain compatible and necessary issues will be fixed, but it will not receive new syntax, capabilities, configuration fields, or CLI options. Existing cases, batch configuration, directory layout, and the `midscene` command can remain unchanged. Upgraded versions execute them through the shared kernel and generate the new Test report page. Use Midscene Test for new projects, new cases, and future capability development. Run legacy files and YAML batch configuration with `midscene`; run native `cases/steps` files and TypeScript project configuration with `midscene-test`. The two formats may live in separate directories in one repository, but a file or command invocation must not mix them. Start with [Midscene Test overview](/midscene-test/overview.md), then follow [Migrate to Midscene Test](/migrate-to-midscene-test.md) to convert fields and switch commands. ::: In most cases, developers write automation scripts just to perform some smoke tests, like checking for the appearance of certain content or verifying that a key user path is accessible. In such situations, maintaining a large test project is unnecessary. Midscene offers a way to perform automation using `.yaml` files, which helps you focus on the script itself rather than the testing framework. This allows any team member to write automation scripts without needing to learn any API. Here is an example. By reading its content, you should be able to understand how it works. ```yaml page: url: https://www.bing.com tasks: - name: Search for weather flow: - ai: Search for "today's weather" - sleep: 3000 - name: Check results flow: - aiAssert: The results show weather information ``` :::info Sample Project You can find a sample project that uses YAML scripts for automation here: - [Web](https://github.com/web-infra-dev/midscene-example/tree/main/yaml-scripts-demo) - [Android](https://github.com/web-infra-dev/midscene-example/tree/main/android/yaml-scripts-demo) - [Computer (Mac/Windows/Linux)](https://github.com/web-infra-dev/midscene-example/tree/main/computer/yaml-scripts-demo) ::: ## Set up API keys for model The following example uses `qwen3.7-plus` through Alibaba Cloud: ```bash export MIDSCENE_MODEL_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1" export MIDSCENE_MODEL_API_KEY="your-api-key" export MIDSCENE_MODEL_NAME="qwen3.7-plus" export MIDSCENE_MODEL_FAMILY="qwen3" ``` Replace `your-api-key` with your API Key. > To use another model, such as Doubao, GLM, Gemini, or GPT-5, see [Use a model API key](/model-api-setup.md). For all configuration options, see [Model configuration](/model-config.md). To execute YAML workflows from the command line, install the Midscene CLI. See [YAML script runner](/yaml-script-runner.md) for installation guidance, `.env` usage, and details on the `midscene` runner. ## Script file structure Script files use YAML format to describe automation tasks. It defines the target to be manipulated (like a webpage or an Android app) and the series of steps to perform. A standard `.yaml` script file includes a `page`, `browser`, `web`, `android`, `ios`, `harmony`, or `computer` section to configure the environment, an optional `agent` section to configure AI agent behavior, and a `tasks` section to define the automation tasks. ```yaml page: url: https://www.bing.com # The tasks section defines the series of steps to be executed tasks: - name: Search for weather flow: - ai: Search for "today's weather" - sleep: 3000 - aiAssert: The results show weather information ``` Use `page:` for a page-level Agent. Use `browser:` when one Agent should manage a browser and its active page. `web:` remains supported as a compatibility entry; `web.mode: browser` maps to BrowserAgent and plain `web:` maps to PageAgent. Do not combine `page`, `browser`, `web`, or the deprecated `target` in the same script. ### The `agent` part The `agent` section configures AI agent behavior and test report options. All fields are optional. ```yaml # AI agent configuration agent: # Test identifier, used for reporting and cache identification, optional testId: # Report group name, optional groupName: # Report group description, optional groupDescription: # Whether to generate test reports, optional, defaults to true generateReport: # Whether to automatically print report messages, optional, defaults to true autoPrintReportMsg: # Custom report file name, optional reportFileName: # Maximum AI replanning cycle limit, optional, defaults to 20 (40 for UI-TARS model) replanningCycleLimit: # Additional AI guidance, optional. default is the shared fallback. aiContexts: default: aiAct: aiQuery: # Cache configuration, optional cache: # Cache strategy, optional, values: 'read-only' | 'read-write' | 'write-only' strategy: # Cache ID, required id: ``` :::info Agent Configuration Notes - **Applicable environments**: Web, iOS, and Android environments all support `agent` configuration - **testId priority**: CLI parameter > YAML agent.testId > filename - **aiContexts**: Provides additional AI guidance such as business facts, rules, constraints, or output requirements. If `default` is configured, it is used only when neither the current call nor the matching API has its own context. A per-call `context` overrides the API value, which overrides `default`; these values are not automatically merged. Empty strings explicitly clear inherited user context. For guidance on writing and supplying context, see [Provide application knowledge to a GUI Agent](/provide-application-knowledge-to-gui-agent.md). - **aiActContext / aiActionContext**: Deprecated compatibility fields for `aiContexts.aiAct`; both remain supported. Resolution uses `aiContexts.aiAct ?? aiActContext ?? aiActionContext`; an empty string takes precedence over lower-priority aliases. Use `aiContexts.aiAct` in new YAML scripts. - **Cache configuration**: For detailed usage, refer to the [Caching documentation](/caching.md) ::: #### Usage example ```yaml # agent configuration, applies to all environments agent: testId: "checkout-test" groupName: "E2E Test Suite" groupDescription: "Complete checkout flow testing" generateReport: true autoPrintReportMsg: false reportFileName: "checkout-report" replanningCycleLimit: 30 aiContexts: default: "Prices are displayed in USD." aiAct: "If any popup appears, click agree. If login page appears, skip it." cache: id: "checkout-cache" strategy: "read-write" # iOS environment configuration ios: launch: https://www.bing.com wdaPort: 8100 # Or Android environment configuration android: deviceId: s4ey59 launch: https://www.bing.com tasks: - name: Search for weather flow: - ai: Search for "today's weather" - aiAssert: The results show weather information ``` ### The web target part Recommended page-level target: ```yaml page: url: https://example.com ``` Recommended browser-level target: ```yaml browser: url: https://example.com autoFollowNewPage: true ``` Compatibility form: ```yaml web: mode: browser url: https://example.com autoFollowNewPage: true ``` Shared options: ```yaml page: # The URL to visit, required. If `serve` is provided, provide the relative path. url: # Serve a local path as a static server, optional. serve: # The browser user agent, optional. userAgent: # The browser viewport width, optional, defaults to 1440. viewportWidth: # The browser viewport height, optional, defaults to 800. viewportHeight: # The browser's device pixel ratio, optional, defaults to the system's value. deviceScaleFactor: # Path to a JSON format browser cookie file, optional. cookie: # Chrome download directory (Puppeteer only), optional. # Relative paths are resolved from the current working directory. # Not supported in bridge mode. downloadPath: # Extra HTTP headers sent with every request (Puppeteer only), optional. # Useful when the server validates custom request headers. # Values must be strings; quote values YAML would treat as a boolean or number, e.g. "true". extraHTTPHeaders: X-Custom-Token: my-token Accept-Language: en-US # The strategy for waiting for network idle in Puppeteer mode, optional. # `timeout` applies to the initial opening of `web.url` defined in YAML and to later actions such as `aiTap` and `aiInput`. # `continueOnNetworkIdleError` only applies to the initial opening of `web.url` defined in YAML. waitForNetworkIdle: # The timeout in milliseconds for each network idle wait, optional, defaults to 2000ms. timeout: # Whether to continue if the initial opening of `web.url` defined in YAML times out while waiting for network idle, optional, defaults to true. # Later action-time waits always continue even if they time out. continueOnNetworkIdleError: # The path to the JSON file for outputting aiQuery/aiAssert results, optional. output: # Whether to save log content to a JSON file, optional, defaults to `false`. If true, saves to `unstableLogContent.json`. If a string, saves to the specified path. The log content structure may change in the future. unstableLogContent: # Whether to restrict page navigation to the current tab, optional, defaults to true. # Page mode only. Do not use it with `browser:` or `web.mode: browser`. forceSameTabNavigation: # Whether BrowserAgent should automatically continue in newly opened pages, optional, defaults to false. # Browser mode only. Use `browser:` or `web.mode: browser`. autoFollowNewPage: # CDP endpoint, optional. Connects to an existing browser instance via CDP instead of launching a new one. # Mutually exclusive with bridgeMode. cdpEndpoint: ws://localhost:9222/devtools/browser # The bridge mode, optional, defaults to false. Can be 'newTabWithUrl' or 'currentTab'. See below for more details. bridgeMode: false | 'newTabWithUrl' | 'currentTab' # Whether to close newly created tabs when the bridge disconnects, optional, defaults to false. closeNewTabsAfterDisconnect: # Whether to ignore HTTPS certificate errors, optional, defaults to false. acceptInsecureCerts: # Custom Chrome launch arguments (Puppeteer only, not supported in bridge mode), optional. # Use this to customize Chrome browser behavior, such as disabling third-party cookie blocking. # ⚠️ Security Warning: Some arguments (e.g., --no-sandbox, --disable-web-security) may reduce browser security. # Use only in controlled testing environments. chromeArgs: - '--disable-features=ThirdPartyCookiePhaseout' - '--disable-features=SameSiteByDefaultCookies' - '--window-size=1920,1080' ``` ### Chrome Bridge {#chrome-bridge} Complete [Chrome Bridge environment setup](/bridge-mode.md), then set `bridgeMode` in `web`: | Value | Behavior | | --------------- | ----------------------------------------- | | `newTabWithUrl` | Creates and connects a new tab at `url` | | `currentTab` | Connects the active tab and ignores `url` | ```yaml web: url: https://example.com bridgeMode: newTabWithUrl closeNewTabsAfterDisconnect: true tasks: - name: Check the page flow: - aiAssert: The page shows Example Domain ``` Run with the [YAML script runner](/yaml-script-runner.md) and authorize the connection in the extension. `closeNewTabsAfterDisconnect` defaults to `false`; setting it to `true` closes bridge-created tabs during cleanup, leaving pre-existing tabs open. Bridge mode cannot be combined with `cdpEndpoint` or `web.mode: browser`. It reuses desktop browser settings and ignores these fields: - `userAgent` - `viewportWidth` / `viewportHeight` - `deviceScaleFactor` - `waitForNetworkIdle` - `cookie` - `extraHTTPHeaders` - `downloadPath` - `chromeArgs` ### The `android` part ```yaml android: # The device ID, optional, defaults to the first connected device. deviceId: # The launch URL, optional, defaults to the device's current page. launch: # The path to the JSON file for outputting aiQuery/aiAssert results, optional. output: # All other options supported by the AndroidDevice constructor # For example: androidAdbPath, remoteAdbHost, remoteAdbPort, # imeStrategy, displayId, autoDismissKeyboard, keyboardDismissStrategy, # keyboardTypeDelay, minScreenshotBufferSize, alwaysRefreshScreenInfo, etc. # See the AndroidDevice constructor documentation for the complete list ``` :::info View Complete Android Configuration Options YAML scripts now support all configuration options from the `AndroidDevice` constructor. For the complete list of options, see [`AndroidDevice`](/sdk/android.md#androiddevice) in the Android API reference. ::: #### Android Platform-Specific Actions **`runAdbShell` - Execute ADB Shell Commands** Execute ADB shell commands on Android devices. Pass only the shell command itself, without the `adb shell` prefix. To set a command timeout, keep `timeout` as a shallow sibling of `runAdbShell`. ```yaml android: deviceId: 'test-device' tasks: - name: Clear app data flow: - runAdbShell: 'pm clear com.example.app' - name: Get battery info flow: - runAdbShell: 'dumpsys battery' - name: Tap screen coordinates flow: - runAdbShell: 'input tap 100 200' - name: Run command with timeout flow: - runAdbShell: 'dumpsys activity services' timeout: 60000 ``` **Common ADB Shell Commands:** - `pm clear ` - Clear app data - `dumpsys battery` - Get battery information - `dumpsys window` - Get window information - `settings get secure android_id` - Get device ID - `input tap ` - Tap screen coordinates - `input keyevent ` - Send key events **`launch` - Launch App or URL** Launch Android apps or open URLs. ```yaml android: deviceId: 'test-device' tasks: - name: Launch Settings app flow: - launch: com.android.settings - name: Open webpage flow: - launch: https://www.example.com ``` **`terminate` - Terminate App** Terminate (force-stop) a running Android app by package name. ```yaml android: deviceId: 'test-device' tasks: - name: Terminate Settings app flow: - terminate: com.android.settings ``` ### The `ios` part ```yaml ios: # WebDriverAgent port, optional, defaults to 8100. wdaPort: # WebDriverAgent host address, optional, defaults to localhost. wdaHost: # For gateways with a path prefix, use wdaBaseUrl instead of wdaHost/wdaPort. # Setting wdaBaseUrl together with either wdaHost or wdaPort causes an error. # wdaBaseUrl: # Optional independent MJPEG stream URL, including a gateway path if needed. # Cannot be combined with wdaMjpegPort. # wdaMjpegUrl: # Local MJPEG stream port, optional. Use this or wdaMjpegUrl. # wdaMjpegPort: # Whether to auto dismiss keyboard, optional, defaults to false. autoDismissKeyboard: # Launch URL or app bundle ID, optional, defaults to the device's current page. launch: # The path to the JSON file for outputting aiQuery/aiAssert results, optional. output: # Whether to save log content to a JSON file, optional, defaults to `false`. If true, saves to `unstableLogContent.json`. If a string, saves to the specified path. The log content structure may change in the future. unstableLogContent: # All other options supported by the IOSDevice constructor # See the IOSDevice constructor documentation for the complete list ``` For a gateway with a path prefix, set `wdaBaseUrl` and leave `wdaHost` and `wdaPort` unset. The MJPEG stream can use a separate URL: ```yaml ios: wdaBaseUrl: ${WDA_BASE_URL} wdaMjpegUrl: ${WDA_MJPEG_URL} ``` Set both environment variables before running the script. Studio Recorder exports use these references so gateway paths and access tokens stay out of the YAML file. :::info View Complete iOS Configuration Options YAML scripts now support all configuration options from the `IOSDevice` constructor. For the complete list of options, see [`IOSDevice`](/sdk/ios.md#iosdevice) in the iOS API reference. ::: #### iOS Platform-Specific Actions **`runWdaRequest` - Execute WebDriverAgent API Requests** Execute WebDriverAgent API requests directly on iOS devices. ```yaml ios: launch: 'com.apple.mobilesafari' tasks: - name: Press home button via WDA flow: - runWdaRequest: method: POST endpoint: /session/test/wda/pressButton data: name: home - name: Get device information flow: - runWdaRequest: method: GET endpoint: /wda/device/info ``` **Parameters:** - `method` (string, required): HTTP method (GET, POST, DELETE, etc.) - `endpoint` (string, required): WebDriverAgent API endpoint - `data` (any, optional): Request body data **Common WebDriverAgent Endpoints:** - `/wda/screen` - Get screen information - `/wda/device/info` - Get device information - `/session/{sessionId}/wda/pressButton` - Press hardware buttons - `/session/{sessionId}/wda/apps/launch` - Launch apps - `/session/{sessionId}/wda/apps/terminate` - Terminate apps - `/session/{sessionId}/wda/apps/activate` - Activate apps **`launch` - Launch App or URL** Launch iOS apps or open URLs. ```yaml ios: wdaPort: 8100 tasks: - name: Launch Settings app flow: - launch: com.apple.Preferences - name: Open webpage flow: - launch: https://www.example.com ``` **`terminate` - Terminate App** Terminate (close) a running iOS app by its bundle ID. ```yaml ios: wdaPort: 8100 tasks: - name: Terminate Settings app flow: - terminate: com.apple.Preferences ``` ### The `harmony` part The `harmony` section is used for HarmonyOS device automation via HDC. The device is connected with `hdc`, so make sure `hdc list targets` reports your device before running. ```yaml harmony: # The HarmonyOS device ID to connect to, optional, defaults to the first connected device. deviceId: # The app to launch, optional, defaults to the device's current screen. launch: # The path to the HDC executable, optional. hdcPath: # Whether to auto dismiss keyboard after input, optional, defaults to true. autoDismissKeyboard: # Custom mapping of app names to bundle names or explicit bundle/ability targets, optional. # User-provided mappings take precedence over defaults. appNameMapping: : # The path to the JSON file for outputting aiQuery/aiAssert results, optional. output: # All other options supported by the HarmonyDevice constructor ``` #### HarmonyOS Platform-Specific Actions **`launch` - Launch App** Launch a HarmonyOS app by its bundle name or an explicit `bundle/Ability` target. ```yaml harmony: deviceId: 'test-device' appNameMapping: Video: com.example.video/PhoneAbility tasks: - name: Launch app flow: - launch: Video ``` **`terminate` - Terminate App** Terminate (force-stop) a running HarmonyOS app by bundle name or mapped app name. ```yaml harmony: deviceId: 'test-device' tasks: - name: Terminate app flow: - terminate: com.example.app ``` **`runHdcShell` - Execute HDC Shell Command** Execute an HDC shell command on the HarmonyOS device. ```yaml harmony: deviceId: 'test-device' tasks: - name: Dump window info flow: - runHdcShell: command: 'hidumper -s WindowManagerService -a' ``` ### The `computer` part The `computer` section is used for PC desktop automation. It allows you to control the desktop environment, including mouse movements, keyboard inputs, and screen queries. ```yaml computer: # The display ID to use, optional, defaults to the primary display. displayId: # The path to the JSON file for outputting aiQuery/aiAssert results, optional. output: ``` #### Usage example ```yaml computer: {} tasks: - name: Open browser and search flow: - aiAct: press Cmd+Space - sleep: 500 - aiAct: type "Safari" and press Enter - sleep: 2000 - aiAct: press Cmd+L to focus address bar - aiAct: type "https://www.bing.com" - aiAct: press Enter - sleep: 3000 - aiAct: type "weather today" in the search box and press Enter - aiAssert: The results show weather information ``` :::info Platform Notes The demo scripts above use macOS commands. For Windows, modify the scripts to use: - `press Windows key` instead of `press Cmd+Space` - `type "Chrome"` instead of `type "Safari"` - `press Ctrl+L` instead of `press Cmd+L` ::: ### The `tasks` part The `tasks` part is an array that defines the steps of the script. Remember to add a `-` before each step to indicate it's an array item. The interfaces in the `flow` section are almost identical to the [API](/reference.md#common), with some differences in parameter nesting levels. ```yaml tasks: - name: continueOnError: # Optional, whether to continue to the next task on error, defaults to false. flow: # Auto Planning (.ai) # ---------------- # Perform an interaction. `ai` is a shorthand for `aiAct`. - ai: cacheable: # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True. deepThink: # Optional, guide aiAct to focus on task decomposition and separate planning from UI element locating. Defaults to false. deepLocate: # Optional, enable Deep Locate for UI element locating during aiAct execution. Defaults to false. # This usage is the same as `ai`. # Note: In earlier versions, this was also written as `aiAction`. The current version supports both names. - aiAct: cacheable: # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True. deepThink: # Optional, guide aiAct to focus on task decomposition and separate planning from UI element locating. Defaults to false. deepLocate: # Optional, enable Deep Locate for UI element locating during aiAct execution. Defaults to false. # Instant Action (.aiTap, .aiHover, .aiInput, .aiKeyboardPress, .aiScroll) # ---------------- # Tap an element described by a prompt. - aiTap: deepLocate: # Optional, whether to enable Deep Locate for this element. Defaults to False. xpath: # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty. cacheable: # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True. fileChooserAccept: | [, ] # Optional, file path(s) to upload when the tap triggers a file chooser; only available on web # Hover over an element described by a prompt. - aiHover: deepLocate: # Optional, whether to enable Deep Locate for this element. Defaults to False. xpath: # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty. cacheable: # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True. # Input text into an element described by a prompt. - aiInput: # The element to input text into. value: deepLocate: # Optional, whether to enable Deep Locate for this element. Defaults to False. xpath: # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty. cacheable: # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True. # Press a key (e.g., Enter, Tab, Escape) on an element described by a prompt. - aiKeyboardPress: # The element to press the key on. keyName: deepLocate: # Optional, whether to enable Deep Locate for this element. Defaults to False. xpath: # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty. cacheable: # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True. # Scroll globally or on an element described by a prompt. - aiScroll: # Optional, the element to scroll on. scrollType: 'singleAction' # or 'scrollToBottom' | 'scrollToTop' | 'scrollToRight' | 'scrollToLeft'. Defaults to 'singleAction'. direction: 'down' # or 'up' | 'left' | 'right'. Defaults to 'down'. Only effective when scrollType is singleAction. distance: # Optional, scroll distance in device logical pixels, meaning the coordinate units used by # the width and height returned by size() in a custom device integration. Use null to let Midscene decide automatically. # At runtime, this distance is converted into a swipe gesture travel distance on touch devices # or a wheel scroll delta on Web and desktop platforms. The actual content displacement is not guaranteed to match this value. deepLocate: # Optional, whether to enable Deep Locate for this element. Defaults to False. xpath: # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty. cacheable: # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True. # Log the current screenshot with a description in the report file. - recordToReport: # Optional, the title of the screenshot. If not provided, the title will be 'untitled'. content: <content> # Optional, the description of the screenshot. # Data Extraction # ---------------- # Perform a query that returns a JSON object. - aiQuery: <prompt> # Remember to describe the format of the result in the prompt. name: <name> # The key for the query result in the JSON output. # More APIs # ---------------- # Wait for a condition to be met, with a timeout (in ms, optional, defaults to 30000). - aiWaitFor: <prompt> timeout: <ms> # Perform an assertion. - aiAssert: <prompt> errorMessage: <error-message> # Optional, the error message to print if the assertion fails. name: <name> # Optional, give the assertion a name, which will be used as a key in the JSON output. - aiBoolean: <prompt> name: <name> # Optional, give the boolean result a name for JSON output. # Run one Gherkin Scenario. This is a Beta feature available starting in Midscene 1.10. - runGherkinScenario: | Scenario: Add a todo item Given the todo page is open When I add a todo item named "Buy milk" Then the todo list should contain "Buy milk" # Wait for a specified amount of time. - sleep: <ms> # Execute a piece of JavaScript code in the web page context. - javascript: <javascript> name: <name> # Optional, assign a name to the return value, which will be used as a key in the JSON output. - name: <name> flow: # ... ``` `runGherkinScenario` is a Beta feature available starting in Midscene 1.10. For supported rules and limitations, see [BDD-style scripts with Gherkin](/advanced/bdd-style-scripts-with-gherkin.md). #### Step Result Names Steps that write a result with `name` save that value into the YAML run result and the JSON output. Use `name` to label values that should appear in the run output. ```yaml tasks: - name: Save extracted data flow: - aiString: Get the product id shown on the page name: product_id - aiQuery: Get the search result after submitting the product id name: search_result ``` #### Upload Files With `aiTap` When clicking a button opens a file chooser, you can set `fileChooserAccept` directly on the `aiTap` step. It accepts either a single path or an array of paths. ```yaml tasks: - name: upload single file flow: - aiTap: Choose file button fileChooserAccept: ./fixtures/document.pdf - name: upload multiple files flow: - aiTap: Upload images button fileChooserAccept: - ./fixtures/image1.jpg - ./fixtures/image2.png ``` If you are already using a `locate` object for `prompt`, `images`, or other locate options, keep `fileChooserAccept` at the same level as `locate`. Do not nest it inside `locate` or inside the `aiTap` object: ```yaml tasks: - name: upload file with locate flow: - aiTap: locate: prompt: Click the upload button fileChooserAccept: ./fixtures/document.pdf ``` Notes: - `fileChooserAccept` is only available for web pages (Playwright, Puppeteer, or Chrome extension Bridge mode). - Relative paths are resolved from the current command working directory, not from the YAML file directory. - If a file does not exist, the script throws before the tap is executed. - In Chrome extension Bridge mode, local file uploads require the Midscene extension's "Allow access to file URLs" permission. Enable it in `chrome://extensions` > Midscene > "Details", then reconnect Bridge mode from the target `http(s)://` page. - Chrome extension Bridge mode does not support directory upload inputs (`webkitdirectory` / `directory`). Use Playwright for directory uploads. #### Prompting with images For steps whose prompt accepts images, you can attach images to the prompt by setting the `images` field to an array of objects, each containing a `name` and a `url`. (see the [API reference](/reference.md#prompting-with-images)), replace the string value with an object that contains: - `prompt`: The text prompt. - `images`: (Optional) The reference images used in the prompt. Each image needs a `name` and a `url`. - `convertHttpImage2Base64`: (Optional) Converts HTTP image links to Base64 before sending them to the model, which is useful when the link is not publicly accessible. Image URLs can be local paths, Base64 strings, or remote links. When using image links that cannot be accessed for the model, set `convertHttpImage2Base64: true` so Midscene will download the image and send the base64 string to the model. For interactions like `aiTap`, `aiHover`, `aiDoubleClick`, `aiRightClick`, put the text and images in the `locate` field as a sibling of the action key. ```yaml tasks: - name: Verify branding flow: - aiHover: locate: prompt: Move the cursor to the region containing the GitHub logo. images: - name: GitHub logo url: https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png convertHttpImage2Base64: true - aiTap: locate: prompt: Tap the region containing the GitHub logo. images: - name: GitHub logo url: https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png convertHttpImage2Base64: true ``` > The legacy nested format (where `locate` is indented under the action key, e.g. `aiTap: \n locate: ...`) is still supported but not recommended. For `aiAct` (and its `ai` shorthand), and for insight steps like `aiAsk`, `aiQuery`, `aiBoolean`, `aiNumber`, `aiString`, and `aiAssert`, you can set the `prompt` and `images` fields directly under the action key. ```yaml tasks: - name: Verify branding flow: - aiAssert: prompt: Check whether the image appears on the page. images: - name: target logo url: https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png convertHttpImage2Base64: true ``` ## Notes ### `agent.runYaml` only parses the `tasks` field When using the `agent.runYaml()` API, only the `tasks` field in the YAML file is parsed and executed. At that point the agent has already been initialized in the JS script, so it cannot be reinitialized based on the `agent` configuration in the YAML file. --- url: /awesome-midscene.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Awesome Midscene A curated list of community projects that extend Midscene.js capabilities across different platforms and programming languages. For official icons and brand colors, see [Brand resources](/brand-resources.md). ## Community projects New additions appear at the top of the list. ### [KiritoKing/midscene-jev-runner](https://github.com/KiritoKing/midscene-jev-runner) Browser automation with the [Jev](https://typesafe.ai/) decision model for Playwright and Midscene Test - Turns page controls and available operations into candidates for Jev to choose the next action and target; calls a text generation model when text input is needed - Works with an existing Playwright page or as a `jevAct` step in Midscene Test, with support for custom task completion checks ### [lhuanyu/midscene-android](https://github.com/lhuanyu/midscene-android) An Android app that runs Midscene automation directly on the device, without connecting to it from a PC via ADB - Operate apps with natural-language instructions, edit and run YAML scripts, and review execution reports and history on the device - Follow task progress through a floating overlay and interrupt execution when needed - The Agent and runtime run on the device; prompts and screenshots are sent to the model endpoint you configure ### [lhuanyu/midscene-ios](https://github.com/lhuanyu/midscene-ios) iOS Mirror automation support for Midscene - Enables automated testing and interaction with iOS applications - Extends Midscene's cross-platform capabilities to Apple's mobile ecosystem ### [Mofangbao/midscene-pc](https://github.com/Mofangbao/midscene-pc) PC operation device for Windows, macOS, and Linux - Enables automated testing and interaction with desktop applications across all major platforms - Supports both local and remote operation capabilities ### [Mofangbao/midscene-pc-docker](https://github.com/Mofangbao/midscene-pc-docker) Docker container image with Midscene-PC server pre-installed - Based on Ubuntu 20 with GNOME desktop for maximum application compatibility - Includes built-in VNC service for browser-based desktop monitoring - Deploy automation client directly on standard servers with a single command ### [Python51888/Midscene-Python](https://github.com/Python51888/Midscene-Python) Python SDK for Midscene automation - Brings Midscene's AI-powered automation capabilities to Python developers - Allows integration with existing Python testing and automation workflows ### [Master-Frank/midscene-java](https://github.com/Master-Frank/midscene-java) Java SDK for Midscene automation - Offers a JVM-friendly way to script Midscene experiences similar to the Python SDK - Fits easily into existing Java automation or testing pipelines ### [alstafeev/midscene-java](https://github.com/alstafeev/midscene-java) Java SDK for Midscene automation - Provides a JVM-native interface for scripting Midscene - Integrates seamlessly into established Java testing frameworks and automation workflows ## Contributing Have you created a project that extends Midscene.js? We'd love to feature it here! To add your project to this list, please submit an issue to the [Midscene repository](https://github.com/web-infra-dev/midscene), and tell us your awesome midscene project. ## Criteria for inclusion Projects featured in Awesome Midscene should: - Extend or integrate with Midscene.js functionality - Be actively maintained - Have clear documentation and usage examples - Provide value to the Midscene community *** _Don't see your favorite platform or language supported yet? Consider creating a community project or contributing to existing ones!_ --- url: /basics.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # The Basics This page explains Midscene's vision-based approach, usage options, and key APIs to help you understand and use the GUI Agent. To try it first, go to [Get started](/get-started.md). ## A vision-based approach to automation Midscene interprets screenshots, locates targets, performs actions, and observes the result. UI localization and actions do not depend on DOM data, selectors, or extra annotations. This has four main advantages: - **Serve the purpose of E2E testing**: Operate software as a user would and verify complete workflows from their perspective. Act on visible text, icons, and layout, then check the rendered result, including selected states, error messages, and obscured elements. - **Work across UI stacks**: HTML, Canvas, mobile, and desktop apps all appear as screenshots. Once a platform provides screenshots and actions, the same Agent APIs apply, reducing dependence on application internals. - **Align with mainstream model approaches**: [Gemini Computer Use](https://ai.google.dev/gemini-api/docs/computer-use) and [UI-TARS](https://github.com/bytedance/UI-TARS) both use screenshot-driven interaction. Midscene's model adapters let users choose models through a consistent API and benefit from improvements in model capabilities. - **Affordable model costs**: In the [AppControlBench evaluation](/app-control-bench-report.md), Doubao Seed 2.1 Turbo ran 60 tasks and passed 58, with a total model API cost of about $0.59. Actual costs vary with the model, task, and cache usage. This approach requires a model with UI localization capabilities; see [supported models](/model-selection.md). Data extraction and page understanding can still include DOM data when needed; see the [API reference](/reference.md#extraction-location-assertion). ## Choose how to use Midscene {#choose-your-path} Midscene provides a cross-platform GUI Agent for web, mobile, and desktop apps. It follows natural-language instructions to interact with interfaces, check results, and extract data. For testing, choose an integration approach based on your existing project setup and how you prefer to write test cases. If you prefer YAML-based testing, use **Midscene Test**, an E2E testing framework for web, mobile, and desktop apps. Describe test steps and expected results in YAML, extend business operations with TypeScript, and let the framework handle setup, cleanup, retries, and execution reports. If you already have a JavaScript/TypeScript test project or prefer writing tests in code, use the SDK to integrate the GUI Agent into frameworks such as Playwright Test, Rstest, or Vitest to add visual actions and assertions to your test cases. | Your goal | Start here | | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | Try natural-language actions and assertions | [Get started](/get-started.md) | | Organize web, mobile, or desktop tests in YAML | [Create a test project](/midscene-test/use.md) | | Write tests in a JavaScript/TypeScript project | [Integrate with Playwright Test](/integrate-with-playwright.md), [Rstest](/sdk/rstest.md), or [Vitest](/sdk/vitest.md) | | Run standalone automation workflows | [Standalone scripts](/sdk/standalone.md) | | Let an AI coding agent operate apps | [Midscene Skills](/skills.md) | ## Key APIs {#javascript-orchestration} ### Plan and interact **`aiAct`** [`aiAct`](/reference.md#agentaiact) accepts a goal described in natural language. It observes the interface, plans the next steps, locates the target elements, and executes the actions until the goal is complete. The prompt can also include assertions. Midscene verifies these assertions during execution and throws an error promptly if one fails. `aiAct` is flexible and autonomous, so it works well when a task has multiple steps, conditional branches, or an uncertain execution path. During execution, `aiAct` continuously uses AI to plan from the latest interface state, which means it usually takes more time and tokens than an instant interaction. Typical usage: ```typescript await agent.aiAct( 'Search for headphones, add the first item to the cart, and confirm that the cart count changes to 1', ); ``` ### Instant interactions Instant interaction APIs perform one specified action. Their main job is to locate a UI element and execute a fixed operation on it. These APIs do not plan a sequence of steps. A request such as “close the popup if it appears, then click the checkout button” should use `aiAct`; an instant interaction treats its prompt as a description of the target element, not as a workflow. **`aiTap`** [`aiTap`](/reference.md#agentaitap) locates and taps or clicks one element. Typical usage: ```typescript await agent.aiTap('The checkout button in the shopping cart'); ``` **`aiInput`** [`aiInput`](/reference.md#agentaiinput) locates an input field and enters a specified value. Its default `replace` mode clears the existing content before entering the new value. Typical usage: ```typescript await agent.aiInput('The email address input', { value: 'user@example.com', }); ``` Other input modes are `typeOnly`, which preserves the existing content, and `clear`, which only clears the field. Other instant interaction APIs include `aiHover`, `aiClearInput`, `aiKeyboardPress`, `aiScroll`, `aiPinch`, `aiLongPress`, `aiDoubleClick`, and `aiRightClick`. Platform support varies; see [Planning and interaction](/reference.md#planning-interaction) in the API reference. ### Insight Insight APIs observe the interface and return an analysis result without interacting with it. They use the current screenshot by default. On web pages, you can also pass `domIncluded` when the task requires DOM information that is not visible in the screenshot. **`aiAssert`** [`aiAssert`](/reference.md#agentaiassert) checks a condition described in natural language. It resolves when the condition is true. When the condition is false, it throws an error that includes the reason returned by the model. Typical usage: ```typescript await agent.aiAssert('The shopping cart contains one item and shows a subtotal'); ``` **`aiQuery`** [`aiQuery`](/reference.md#agentaiquery) extracts structured data from the interface. Describe both the required data and its expected type or shape in the prompt. Typical usage: ```typescript const items = await agent.aiQuery< Array<{ name: string; price: number }> >('The products in the shopping cart, {name: string, price: number}[]'); // Example items value: [{ name: 'Wireless headphones', price: 99.9 }] ``` **`aiBoolean`** [`aiBoolean`](/reference.md#agentaiboolean) answers a question about the interface and returns a boolean. Typical usage: ```typescript const loginDialogVisible = await agent.aiBoolean( 'Is the login dialog visible?', ); // Example loginDialogVisible value: true ``` Related convenience methods include [`aiNumber`](/reference.md#agentainumber) for numbers and [`aiString`](/reference.md#agentaistring) or [`aiAsk`](/reference.md#agentaiask) for strings. ### Improve planning and localization when needed - **`deepThink`: enhance planning**. Available on `aiAct`, it focuses on task decomposition and separates planning and element localization into different model calls. Use it for complex, multi-step tasks. See [`deepThink` planning mode](/reference.md#aiact-deepthink). - **`deepLocate`: enhance localization**. Available on APIs that locate elements, such as `aiAct` and `aiTap`, it uses an additional model call to improve accuracy for small or visually ambiguous targets. See [deep localization](/reference.md#deep-locate-deeplocate). Both options are off by default. Enable them independently or combine them in `aiAct`. They add model-call overhead, so start with the defaults and enable them when you encounter planning or localization problems. ```typescript await agent.aiAct('Complete the checkout form and stop before placing the order', { deepThink: true, }); await agent.aiTap('The cart icon in the upper-right corner', { deepLocate: true }); ``` ## Next steps - [Model Selection Guide](/model-selection.md): Learn when to use one Default model and when to combine models. - [Get started](/get-started.md): Set up your platform and model, then complete a first run. - [Create a test project](/midscene-test/use.md): Write and run YAML tests. - [API reference](/reference.md): Look up full options and platform support. --- url: /blog-introducing-instant-actions-and-deep-think.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Introducing Instant Actions and Deep Think From Midscene v0.14.0, we have introduced two new features: Instant Actions and Deep Think. ## Instant Actions - a more predictable way to perform actions You may have already been familiar with our `.ai` interface. It's an auto-planning interface to interact with web pages. For example, when performing a search, you can do this: ```typescript await agent.ai('type "Headphones" in search box, hit Enter'); ``` Behind the scene, Midscene will call the LLM to plan the steps and execute them. You can see the report file to see the process. It's a very common way for AI agents to these kinds of tasks. ![](/images/blog/report-planning.png) In the meantime, there are many testing engineers who want a faster way to perform actions. When using AI models with complex prompts, some of the LLM models may find it hard to plan the proper steps, or the coordinates of the elements may not be accurate. It could be frustrating for debugging the unpredictable process. To solve this problem, we have introduced the `aiTap()`, `aiHover()`, `aiInput()`, `aiKeyboardPress()`, `aiScroll()` interfaces. They are call the **"instant actions"**. These interfaces will directly perform the specified action as the interface name suggests, while the AI model is responsible for the easier tasks such as locating elements. The whole process can be obviously faster and more reliable after using them. For example, the search action above can be rewritten as: ```typescript await agent.aiInput('Headphones', 'search-box'); await agent.aiKeyboardPress('Enter'); ``` The typical workflow in the report file is like this, as you can see there is no planning process in the report file: ![](/images/blog/report-instant-action.png) The scripts with instant actions seems a little bit redundant (or not 'ai-style'), but we believe these structured interfaces are a good way to save time debugging when the action is already clear. ## Deep Think - a more accurate way to locate elements When using Midscene with some complex widgets, the LLM may find it hard to locate the target element. We have introduced a new option named `deepThink` to the instant actions. The signature of the instant actions with `deepThink` is like this: ```typescript await agent.aiTap('target', { deepThink: true }); ``` `deepThink` is a strategy of locating elements. It will first find an area that contains the target element, then "focus" on this area to search the element again. By this way, the coordinates of the target element will be more accurate. Let's take the workflow editor page of Coze.com as an example. There are many customized icons on the sidebar. This is usually hard for LLMs to distinguish the target element from its surroundings. ![](/images/blog/coze-sidebar.png) After using `deepThink` in instant actions, the yaml scripts will be like this (of course, you can also use the javascript interface): ```yaml tasks: - name: edit input panel flow: - aiTap: the triangle icon on the left side of the text "Input" deepThink: true - aiTap: the first checkbox in the Input form deepThink: true - aiTap: the expand button on the second row of the Input form (on the right of the checkbox) deepThink: true - aiTap: the delete button on the second last row of the Input form deepThink: true - aiTap: the add button on the last row of the Input form (second button from the right) deepThink: true ``` By viewing the report file, you can see Midscene has found every target element in the area. ![](/images/blog/report-coze-deep-think.png) Just like the example above, the highly-detailed prompt for `deepThink` is the key to keeping results stable. `deepThink` is only available with the models that support visual grounding like qwen2.5-vl. If you are using LLM models like gpt-4o, it won't work. --- url: /brand-resources.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Brand resources This page provides the official Midscene.js icon and brand color for documentation, integrations, and badges. ## Icon - <a href="/images/brand/midscenedotjs.svg" download>Monochrome SVG</a> - <a href="/images/brand/midscene-icon.png" download>Color icon</a> - [All brand assets on GitHub](https://github.com/web-infra-dev/midscene/tree/main/apps/site/docs/public/images/brand) The monochrome SVG uses a 24 × 24 viewBox and a single compound path. It has a transparent background and no explicit fill color, so it defaults to black. Set the fill color when rendering it. ## Brand color The Midscene.js brand color is dark gray: | Format | Value | | ------ | ------------ | | HEX | `#3F464C` | | RGB | `63, 70, 76` | This is the outline color of the color logo. Use `3F464C` when an icon library requires a six-digit hexadecimal value without the hash. For monochrome presentations, use the brand color on a light background or white on a dark background. Preserve the icon's proportions. ## Source and project information - [Monochrome SVG source](https://github.com/web-infra-dev/midscene/blob/main/apps/site/docs/public/images/brand/midscenedotjs.svg) - [Midscene.js repository](https://github.com/web-infra-dev/midscene) - [Project license](https://github.com/web-infra-dev/midscene/blob/main/LICENSE) --- url: /bridge-mode.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Chrome Bridge environment setup Chrome Bridge enables Node.js scripts to control your desktop Chrome browser through the Midscene Chrome extension, allowing you to reuse existing login sessions, cookies, and browser extensions. The Node.js process runs the Bridge Server and handles AI model calls, while the Chrome extension connects to that server and executes operations on browser tabs. ![Chrome Bridge](/images/midscene-bridge-mode.png) ## Installation and permissions 1. Install the [Midscene Chrome extension](https://chromewebstore.google.com/detail/midscene/gbldofcpkknbggpkmbdaefngejllnief). Once installed, it automatically listens for local connection requests in the background. 2. (Optional) If your script needs to upload local files, open `chrome://extensions`, go to the Midscene extension details, and enable **Allow access to file URLs**. Switch back to your target `http(s)://` tab before connecting. ## Validate model calls and page interactions in Playground In [Get started](/get-started.md?platform=web\&scene=playground), choose Web and Playground to save your model settings in the extension, run an `aiAct` action and an `aiAssert` assertion in TodoMVC, and inspect the steps and screenshots. The extension Playground controls the current page without a Node.js Bridge Server. After trying it, run the connection check below to verify that a script process can control Chrome through the extension. [](#) ## Verify the connection {#verify-connection} The minimal script below verifies the connection between your Node.js environment and the Chrome extension. It does not invoke any AI methods, so no model configuration is required. ### 1. Install dependencies Install Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`), install pnpm, and run `pnpm init` in your project directory (skip if `package.json` already exists). Then install the dependencies: ```sh [npm] npm install @midscene/web tsx --save-dev ``` ```sh [yarn] yarn add @midscene/web tsx --save-dev ``` ```sh [pnpm] pnpm add @midscene/web tsx --save-dev ``` ```sh [bun] bun add @midscene/web tsx --save-dev ``` ```sh [deno] deno add npm:@midscene/web npm:tsx --save-dev ``` ### 2. Write the code Save the following code as `bridge-check.ts`: ```typescript title="bridge-check.ts" import { AgentOverChromeBridge } from '@midscene/web/bridge-mode'; async function main() { const agent = new AgentOverChromeBridge(); try { await agent.connectNewTabWithUrl('https://example.com'); console.log('Chrome Bridge connected'); console.log(await agent.getBrowserTabList()); } finally { await agent.destroy(); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` ### 3. Run and authorize ```bash pnpm exec tsx bridge-check.ts ``` When prompted by the Chrome extension, click **Allow** to approve the connection (choose **Always Allow** to automatically approve future connections; you can reset this anytime in the extension's Bridge Mode panel). Once connected, Chrome opens `example.com` in a new tab, and the terminal prints `Chrome Bridge connected` followed by the current tab list. The script then finishes and disconnects, leaving the newly opened tab in Chrome. On the extension icon badge, a yellow dot indicates that it is listening for connections, while a green dot indicates an active connection (because this check script disconnects immediately after completion, the badge will briefly turn green and then return to yellow). ![Chrome Bridge connection](/images/bridge_in_extension.png) ## Next steps After validating the environment and Playground, choose how to continue: - **Write YAML tests**: create a project, run cases, and inspect reports with [Midscene Test](/midscene-test/use.md). - **Write automation workflows**: follow [Standalone automation scripts](/sdk/standalone.md) and select the Chrome Bridge example. - **Look up platform APIs**: see the [Chrome Bridge SDK API reference](/sdk/chrome-bridge.md) for constructor options, platform methods, and cleanup. Model settings saved in Playground are not automatically shared with test or script processes. Copy the validated settings into your project’s `.env` and load them as described in the integration guide. Keep the device connection tools, services, and permissions available. The Midscene Test Web template uses Playwright by default. To use Bridge, adapt [the project configuration](/midscene-test/configuration.md) to connect and destroy an `AgentOverChromeBridge` and register it with `createMidsceneNodes()`. Replace the template’s Playwright page initialization. Chrome Bridge does not expose a Playwright `Page`. To integrate with Playwright Test, follow [Web environment setup](/platforms/web.md). ## Remote access configuration {#remote-access-configuration} By default, the Bridge Server binds to `127.0.0.1` and only accepts connections from a Chrome extension on the same machine. For cross-machine setups (for example, running the script on Machine A and Chrome on Machine B), enable remote access on both sides: **1. Server side (Node.js script)** ```typescript // Option 1: Listen on all network interfaces (0.0.0.0:3766) const agent = new AgentOverChromeBridge({ allowRemoteAccess: true, }); // Option 2: Bind to a specific network interface IP const agent = new AgentOverChromeBridge({ host: '192.168.1.100', port: 3766, }); ``` **2. Client side (Chrome extension)** 1. Open the Chrome extension side panel and switch to **Bridge Mode**. 2. Enter the server address in the **Bridge Server URL** field: - Local connection: `ws://localhost:3766` (default) - Remote connection: `ws://192.168.1.100:3766` (replace with the IP address of the machine running the script) 3. Run your script and click **Allow** in the extension's confirmation dialog. ![bridge remote config](/images/bridge_remote_config.png) :::warning Security Notice Enabling remote access exposes the Bridge Server over the network. Make sure to: - Use it only within trusted private networks; - Restrict incoming connections with firewall rules; - Never expose the Bridge Server port to the public internet. ::: ## Troubleshooting {#faq} ### The extension fails to connect Verify that Chrome is open, the Midscene extension is enabled, and the **Bridge Server URL** in the extension's Bridge Mode panel matches the address and port your script is listening on (local default: `ws://127.0.0.1:3766`). For remote connections, also verify that the script has `allowRemoteAccess: true` or the appropriate `host` configured, and that the port is reachable through your firewall. ### How do I re-prompt for connection authorization? Reset the saved permissions in the extension's Bridge Mode panel, then rerun the script to trigger the confirmation dialog again. ### Where should I configure model credentials? When calling AI methods such as `aiAct` or `aiAssert`, [configure your model credentials](/model-api-setup.md) in the Node.js environment running the script. Model settings entered in the extension's Playground apply only to the Playground itself and are not shared with Node.js scripts. Also note that passing the connection check above only verifies bridge communication, not your model configuration. --- url: /caching.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Caching AI Planning and DOM Localization Midscene supports caching two kinds of data: AI Planning steps and matched element localization information. The former can be used across automation workflows to reduce AI model calls and improve execution efficiency; for web automation, the DOM localization part (XPath) in the latter can significantly reduce repeated locating overhead, but it is currently web-only and has [certain limitations](#limitations-of-xpath-in-caching-element-location). **Effect** With caching hit, time cost is significantly reduced. For example, in the following case, execution time was reduced from 51 seconds to 28 seconds. - **before** ![](/images/cache/no-cache-time.png) - **after** ![](/images/cache/use-cache-time.png) ## Cache files and storage Midscene's caching mechanism is based on input stability and output reusability. When the same task instructions are repeatedly executed in similar page environments, Midscene will prioritize using cached results to avoid repeated AI model calls, significantly improving execution efficiency. The core caching mechanisms include: - **Task instruction caching**: For planning operations (such as `ai`, `aiAct`), Midscene uses the prompt instruction as the cache key to store the execution plan returned by AI - **Element location caching (web only)**: For location operations (such as `aiLocate`, `aiTap`), the system uses the location prompt as the cache key to store element XPath information, and verifies whether the XPath is still valid on the next execution - **Invalidation mechanism**: When cache becomes invalid, the system automatically falls back to AI model for re-analysis - **Plan cache fallback**: If a cached `aiAct` plan fails at runtime, for example because an optional popup no longer appears, Midscene falls back to normal AI planning for the current run and clears the stale cache record's flow - **Never cache query results**: The query results like `aiBoolean`, `aiQuery`, `aiAssert` will never be cached. When this fallback path is used, Midscene does not write the fallback-generated flow back to the original prompt's plan cache, even if the current run succeeds. The cached steps may have already changed the page state before failing, so the fallback plan may only describe the remaining work and may not be valid from the initial page state. On the next run with the same prompt, the empty flow is treated as an unavailable cache entry and Midscene regenerates a complete plan cache from the initial state. Cache contents will be saved in the `./midscene_run/cache` directory with the `.cache.yaml` as the extension name. ## Cache strategies By configuring the `cache` option, you can enable caching for your agent. ### Disable cache Configuration: `cache: false` or not configuring the `cache` option Completely disable cache functionality, always call AI model for every operation. Suitable when you need real-time results or for debugging. By default, if you don't configure the `cache` option, caching is disabled. ```javascript // Direct Agent creation const agent = new PuppeteerAgent(page, { cache: false, }); ``` ```yaml # YAML configuration agent: cache: false ``` ### Read-write mode Configuration: `cache: { id: "my-cache-id" }` or `cache: { strategy: "read-write", id: "my-cache-id" }` Automatically read existing cache and update cache files during execution. The default value of `strategy` is `read-write`. ```javascript // Direct Agent creation - explicit cache ID const agent = new PuppeteerAgent(page, { cache: { id: "my-cache-id" }, }); // Explicitly specify strategy const agent = new PuppeteerAgent(page, { cache: { strategy: "read-write", id: "my-cache-id" }, }); ``` ```yaml # YAML configuration - explicit cache ID agent: cache: id: "my-cache-test" # Explicitly specify strategy agent: cache: id: "my-cache-test" strategy: "read-write" ``` YAML mode also supports `cache: true` to automatically use the file name as the cache ID. ### Read-only, manual write Configuration: `cache: { strategy: "read-only", id: "my-cache-id" }` Only read cache, no automatic writing to cache files. Requires manual `agent.flushCache()` call to write cache files. Suitable for production environments to ensure cache consistency. ```javascript // Direct Agent creation const agent = new PuppeteerAgent(page, { cache: { strategy: "read-only", id: "my-cache-id" }, }); // Manual cache write required await agent.flushCache(); ``` ```yaml # YAML configuration agent: cache: id: "my-cache-test" strategy: "read-only" ``` ### Write-only mode Configuration: `cache: { strategy: "write-only", id: "my-cache-id" }` Only write to cache, do not read existing cache contents. Always call AI model for each execution and write results to cache file. Suitable for initially building cache or updating cache. ```javascript // Direct Agent creation const agent = new PuppeteerAgent(page, { cache: { strategy: "write-only", id: "my-cache-id" }, }); ``` ```yaml # YAML configuration agent: cache: id: "my-cache-test" strategy: "write-only" ``` ### Compatibility mode (not recommended) Configuration via `MIDSCENE_CACHE=1` environment variable with cacheId, equivalent to read-write mode. ```javascript // Old way, requires MIDSCENE_CACHE=1 environment variable and cacheId const agent = new PuppeteerAgent(originPage, { cacheId: 'puppeteer-swag-sab' }); ``` ```bash MIDSCENE_CACHE=1 tsx demo.ts ``` ## Using Playwright AI Fixture from `@midscene/web/playwright` When using `PlaywrightAiFixture` from `@midscene/web/playwright`, pass the same `cache` options to control caching behaviour. ### Disable cache ```typescript // fixture.ts in sample code export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture({ cache: false, }), ); ``` ### Read-write mode ```typescript // fixture.ts in sample code // Auto-generate cache ID from test metadata export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture({ cache: true, }), ); // fixture.ts in sample code // Explicitly provide cache ID export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture({ cache: { id: "my-fixture-cache" }, }), ); ``` ### Read-only, manual write ```typescript // fixture.ts in sample code export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture({ cache: { strategy: "read-only", id: "readonly-cache" }, }), ); ``` When you run the fixture in read-only mode you need to manually persist the cache after your test steps. Use the `agentForPage` helper provided by the fixture to fetch the underlying agent, then call `agent.flushCache()` at the point where you want to write the cache file: ```typescript test.afterEach(async ({ page, agentForPage }, testInfo) => { // Only flush cache if the test passed if (testInfo.status === 'passed') { console.log('Test passed, flushing Midscene cache...'); const agent = await agentForPage(page); await agent.flushCache(); } else { console.log(`Test ${testInfo.status}, skipping Midscene cache flush.`); } }); test('manual cache flush', async ({ agentForPage, page, aiTap, aiWaitFor }) => { const agent = await agentForPage(page); await aiTap('first highlighted link in the hero section'); await aiWaitFor('the detail page loads completely'); await agent.flushCache(); }); ``` ### Write-only mode ```typescript // fixture.ts in sample code export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture({ cache: { strategy: "write-only", id: "write-only-cache" }, }), ); ``` In write-only mode, each test will call the AI model and automatically write results to cache file without reading existing cache. ## Cache Cleaning Midscene supports cleaning unused cache records when flushing cache to file, ensuring cache files stay lean and maintainable. This feature is **completely manual** and requires explicit call to `agent.flushCache({ cleanUnused: true })`. ### Manual Cleaning Mechanism When calling `agent.flushCache({ cleanUnused: true })`, the system will: 1. **Keep used caches**: Cache records that were matched and used in the current run will be retained 2. **Keep new caches**: Cache records newly generated in the current run will be retained 3. **Remove unused caches**: Old cache records that were not accessed will be automatically deleted 4. **Write to file**: The cleaned cache will be written to file ### Usage **Call in test afterEach:** ```javascript describe('test suite', () => { let resetFn: () => Promise<void>; let agent: PuppeteerAgent; afterEach(async () => { // Clean cache and write to file if (agent) { await agent.flushCache({ cleanUnused: true }); } // Then close the page if (resetFn) { await resetFn(); } }); it('test case', async () => { const { originPage, reset } = await launchPage('https://example.com/'); resetFn = reset; agent = new PuppeteerAgent(originPage, { cache: { id: 'my-cache-id' }, }); // ... test logic }); }); ``` **For Playwright AI Fixture users:** ```typescript test.afterEach(async ({ page, agentForPage }) => { const agent = await agentForPage(page); await agent.flushCache({ cleanUnused: true }); }); ``` ### Cleanup Behavior by Mode - **read-write mode**: Calling `flushCache({ cleanUnused: true })` will clean and write to file - **read-only mode**: Calling `flushCache({ cleanUnused: true })` will also clean and write to file (manual flush overrides read-only restriction) - **write-only mode**: No cleanup (does not read cache) **Note**: If you don't pass `cleanUnused: true` parameter, `flushCache()` will only write to file without cleaning unused caches. ## FAQ ### No cache file is generated Please ensure you have correctly configured caching: 1. **Direct Agent creation**: Set `cache: { id: "your-cache-id" }` in the constructor 2. **Playwright AI Fixture mode**: Set `cache: true` or `cache: { id: "your-cache-id" }` in fixture configuration 3. **YAML script mode**: Set `agent.cache.id` in the YAML file 4. **Read-only mode**: Ensure you called the `agent.flushCache()` method 5. **Legacy approach**: Set `cacheId` and enable `MIDSCENE_CACHE=1` environment variable ### How to check if the cache is hit? You can view the report file. If the cache is hit, you will see the `cache` tip and the time cost is obviously reduced. ### Why the cache is missed on CI? You need to commit the cache files to the repository in CI and recheck the cache hit conditions. ### Does it mean that AI services are no longer needed after using cache? No. Caching is the way to accelerate the execution, but it's not a tool for ensuring long-term script stability. We have noticed many scenarios where the cache may miss when the DOM structure changes. AI services are still needed to reevaluate the task when the cache miss occurs. ### How to manually remove the cache? You can remove the cache file in the `./midscene_run/cache` directory, or edit the contents in the cache file. ### How to disable the cache for a single API? You can use the `cacheable` option to disable the cache for a single API. Please refer to the documentation of the corresponding [API](/reference.md#common) for details. ### Limitations of XPath in caching element location Midscene uses [XPath](https://developer.mozilla.org/en-US/docs/Web/XML/XPath) to cache the element location. ⁠We are using a relatively strict strategy to prevent false matches. In these situations, the cache will not be accessed: 1. The text content of the new element at the same XPath is different from the cached element. 2. The DOM structure of the page is changed from the cached one. Additionally, since element location caching relies on DOM structure, caching is not available in the following scenarios: 1. **Canvas elements**: Graphics content inside Canvas does not have DOM nodes and cannot be located via XPath. 2. **Cross-origin iframes**: Browser security policies restrict access to the internal DOM of cross-origin iframes. 3. **Shadow DOM (closed mode)**: Closed Shadow DOM cannot be accessed from outside. 4. **WebGL / Dynamic SVG content**: Dynamically generated graphics may not have a stable DOM structure. When the cache is not hit or not available, the process will fall back to using AI services to find the element. ### Get more debug logs for caching You can set the `DEBUG=midscene:cache:*` environment variable to get more debug logs for caching. --- url: /changelog.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Changelog ## v1.18.2 ### Changes #### Features 🎉 - feat(android): expose an optional scrcpy encoder frame-rate hint by @quanruzhuoxiu in [https://github.com/web-infra-dev/midscene/pull/3416](https://github.com/web-infra-dev/midscene/pull/3416) #### Fixes 🐞 - fix(core): scale model scroll distances from input image pixels by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3392](https://github.com/web-infra-dev/midscene/pull/3392) - fix(site): use www documentation domain and repair outdated links by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3412](https://github.com/web-infra-dev/midscene/pull/3412) - fix(core): reuse Jev reference images across planning rounds by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3407](https://github.com/web-infra-dev/midscene/pull/3407) - fix(core): distinguish request and parse retry counts by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3417](https://github.com/web-infra-dev/midscene/pull/3417) - fix(core): honor planner cache policy throughout aiAct by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3418](https://github.com/web-infra-dev/midscene/pull/3418) #### Refactors ♻️ - refactor(core): reuse OpenRouter detection for Jev by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3405](https://github.com/web-infra-dev/midscene/pull/3405) - refactor(core): clarify UI context naming by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3410](https://github.com/web-infra-dev/midscene/pull/3410) #### Documentation 📖 - docs(site): document Ling 3.2 Flash model configuration by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3406](https://github.com/web-infra-dev/midscene/pull/3406) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.18.1...v1.18.2](https://github.com/web-infra-dev/midscene/compare/v1.18.1...v1.18.2) ## v1.18.1 ### Changes #### Features 🎉 - feat(core): add observe test runner node by @codeestX in [https://github.com/web-infra-dev/midscene/pull/3393](https://github.com/web-infra-dev/midscene/pull/3393) #### Fixes 🐞 - fix(core): unwrap Qwen3 locate response arrays by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3400](https://github.com/web-infra-dev/midscene/pull/3400) #### Documentation 📖 - docs(site): add Hy4 flash to model configuration by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3399](https://github.com/web-infra-dev/midscene/pull/3399) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.18.0...v1.18.1](https://github.com/web-infra-dev/midscene/compare/v1.18.0...v1.18.1) ## v1.18.0 ### Highlights #### Many new model integrations This release includes support for three models for UI automation: - **Qwen4-Max** (`qwen4-max`), with model family `qwen4`. [Qwen configuration guide](https://www.midscenejs.com/model-api-setup#qwen) - **Tencent Hunyuan 4** (`hy4`), with model family `tencent-hy`. [Tencent Hunyuan configuration guide](https://www.midscenejs.com/model-api-setup#tencent-hy) - **StepFun Step 3.7 Flash** (`step-3.7-flash`), with model family `step`. [StepFun configuration guide](https://www.midscenejs.com/model-api-setup#stepfun) ### Changes #### Features 🎉 - feat(core): add OpenRouter reasoning parameter support by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3375](https://github.com/web-infra-dev/midscene/pull/3375) - feat(core): add StepFun model adapter by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3391](https://github.com/web-infra-dev/midscene/pull/3391) - feat(core): add Qwen4 model adapter by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3397](https://github.com/web-infra-dev/midscene/pull/3397) #### Fixes 🐞 - fix(test): keep failure frames from the project's own packages folders by @gjreddy in [https://github.com/web-infra-dev/midscene/pull/3377](https://github.com/web-infra-dev/midscene/pull/3377) - fix(test): escape Case and project names in the GitHub job summary by @gjreddy in [https://github.com/web-infra-dev/midscene/pull/3378](https://github.com/web-infra-dev/midscene/pull/3378) - fix(core): clarify pinch distance semantics and API distance documentation by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3386](https://github.com/web-infra-dev/midscene/pull/3386) - fix(core): include execution ID in Jev requests by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3389](https://github.com/web-infra-dev/midscene/pull/3389) #### Refactors ♻️ - refactor(core): centralize OpenRouter reasoning parameters by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3388](https://github.com/web-infra-dev/midscene/pull/3388) #### Documentation 📖 - docs(site): homepage copy clarity by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3382](https://github.com/web-infra-dev/midscene/pull/3382) - docs(site): align Android preparation Node.js requirement by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3383](https://github.com/web-infra-dev/midscene/pull/3383) - docs(site): add Tencent HY API setup and model cards by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3372](https://github.com/web-infra-dev/midscene/pull/3372) - docs(site): add Browser Use as a CDP WebSocket URL source by @gregpr07 in [https://github.com/web-infra-dev/midscene/pull/3289](https://github.com/web-infra-dev/midscene/pull/3289) - docs(site): clarify model initialization config overrides by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3387](https://github.com/web-infra-dev/midscene/pull/3387) #### Other Changes - revert(report): remove animated webp report poc by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3390](https://github.com/web-infra-dev/midscene/pull/3390) #### New Contributors - @gregpr07 made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3289](https://github.com/web-infra-dev/midscene/pull/3289) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.8...v1.18.0](https://github.com/web-infra-dev/midscene/compare/v1.17.8...v1.18.0) ## v1.17.8 ### Changes #### Features 🎉 - feat(core): add Tencent HY model adapter by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3362](https://github.com/web-infra-dev/midscene/pull/3362) - feat(test): remove automatic credential redaction from run artifacts by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3371](https://github.com/web-infra-dev/midscene/pull/3371) - feat(badge): support skipped test counts by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3380](https://github.com/web-infra-dev/midscene/pull/3380) #### Fixes 🐞 - fix(webdriver): enforce request timeout through response body reads by @quanru in [https://github.com/web-infra-dev/midscene/pull/3232](https://github.com/web-infra-dev/midscene/pull/3232) - fix(web-integration): honor explicit slow swipe durations by @quanru in [https://github.com/web-infra-dev/midscene/pull/3243](https://github.com/web-infra-dev/midscene/pull/3243) - fix(core): clarify aiScroll node locator guidance by @codeestX in [https://github.com/web-infra-dev/midscene/pull/3353](https://github.com/web-infra-dev/midscene/pull/3353) - fix(core): update vulnerable runtime dependencies by @quanru in [https://github.com/web-infra-dev/midscene/pull/3356](https://github.com/web-infra-dev/midscene/pull/3356) - fix(badge): don't round a pass rate with failures to 100% by @gjreddy in [https://github.com/web-infra-dev/midscene/pull/3343](https://github.com/web-infra-dev/midscene/pull/3343) - fix(test): show paths literally in the GitHub job summary by @gjreddy in [https://github.com/web-infra-dev/midscene/pull/3334](https://github.com/web-infra-dev/midscene/pull/3334) - fix(workflow): upgrade security dependencies without overrides by @quanru in [https://github.com/web-infra-dev/midscene/pull/3358](https://github.com/web-infra-dev/midscene/pull/3358) - fix(android): measure planning-frame age after clock recalibration by @wannT-1 in [https://github.com/web-infra-dev/midscene/pull/3364](https://github.com/web-infra-dev/midscene/pull/3364) - fix(android): keep the reset packet count in the post-reset timeout error by @gjreddy in [https://github.com/web-infra-dev/midscene/pull/3363](https://github.com/web-infra-dev/midscene/pull/3363) - fix(core): handle GPT image-edge bboxes and separate coordinate semantics by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3368](https://github.com/web-infra-dev/midscene/pull/3368) - fix(test): omit misleading badges for failed runs by @quanru in [https://github.com/web-infra-dev/midscene/pull/3370](https://github.com/web-infra-dev/midscene/pull/3370) - fix(test): keep parentheses in the file path of a failure frame by @gjreddy in [https://github.com/web-infra-dev/midscene/pull/3369](https://github.com/web-infra-dev/midscene/pull/3369) - fix(ios): bound scroll gestures and propagate boundary failures by @quanru in [https://github.com/web-infra-dev/midscene/pull/3253](https://github.com/web-infra-dev/midscene/pull/3253) - fix(harmony): reject reversed and stationary edge scrolls by @quanru in [https://github.com/web-infra-dev/midscene/pull/3241](https://github.com/web-infra-dev/midscene/pull/3241) - fix(android): reject scrolls without room to move by @quanru in [https://github.com/web-infra-dev/midscene/pull/3242](https://github.com/web-infra-dev/midscene/pull/3242) - fix(core): add quick mappings for scroll and swipe directions by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3156](https://github.com/web-infra-dev/midscene/pull/3156) - fix(core): deduplicate cumulative planning context by @quanru in [https://github.com/web-infra-dev/midscene/pull/3254](https://github.com/web-infra-dev/midscene/pull/3254) - fix(test): keep project config stable when filtering test paths by @gjreddy in [https://github.com/web-infra-dev/midscene/pull/3332](https://github.com/web-infra-dev/midscene/pull/3332) - fix(web-integration): improve static report playground execution by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3090](https://github.com/web-infra-dev/midscene/pull/3090) - fix(core): preserve invalid System One responses in reports by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3379](https://github.com/web-infra-dev/midscene/pull/3379) #### Documentation 📖 - docs(site): add interactive get started guide by @ottomao in [https://github.com/web-infra-dev/midscene/pull/3335](https://github.com/web-infra-dev/midscene/pull/3335) - docs(site): clarify MobileWorld GUI-only scope by @simplyme0823 in [https://github.com/web-infra-dev/midscene/pull/2901](https://github.com/web-infra-dev/midscene/pull/2901) #### Testing 🧪 - test(workflow): finish migration to rstest and document SDK integration by @quanru in [https://github.com/web-infra-dev/midscene/pull/3359](https://github.com/web-infra-dev/midscene/pull/3359) - test(android): isolate anonymous release asset fallback from CI tokens by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3381](https://github.com/web-infra-dev/midscene/pull/3381) #### CI & Chore ⚙️ - chore(workflow): track midscene-action v1 tag by @await-ovo in [https://github.com/web-infra-dev/midscene/pull/3350](https://github.com/web-infra-dev/midscene/pull/3350) #### New Contributors - @gjreddy made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3343](https://github.com/web-infra-dev/midscene/pull/3343) - @wannT-1 made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3364](https://github.com/web-infra-dev/midscene/pull/3364) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.7...v1.17.8](https://github.com/web-infra-dev/midscene/compare/v1.17.7...v1.17.8) ## v1.17.7 ### Changes #### Features 🎉 - feat(test): unify runtime artifact directories (PR3) by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3338](https://github.com/web-infra-dev/midscene/pull/3338) #### CI & Chore ⚙️ - chore(core): support configurable locate prompt order and grouping by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3348](https://github.com/web-infra-dev/midscene/pull/3348) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.6...v1.17.7](https://github.com/web-infra-dev/midscene/compare/v1.17.6...v1.17.7) ## v1.17.6 ### Changes #### Features 🎉 - feat(badge): localize and redesign badge homepage by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3341](https://github.com/web-infra-dev/midscene/pull/3341) - feat(test): add summary badges and improve badge site metadata by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3342](https://github.com/web-infra-dev/midscene/pull/3342) - feat(web-integration): add CLI browser tab management by @quanru in [https://github.com/web-infra-dev/midscene/pull/3302](https://github.com/web-infra-dev/midscene/pull/3302) - feat(core): expose public SIWC authorization entry by @quanru in [https://github.com/web-infra-dev/midscene/pull/3349](https://github.com/web-infra-dev/midscene/pull/3349) #### Fixes 🐞 - fix(workflow): use dedicated badge deployment token by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3340](https://github.com/web-infra-dev/midscene/pull/3340) - fix(core): clarify external abort errors by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3320](https://github.com/web-infra-dev/midscene/pull/3320) - fix(core): respect model proxy settings in SIWC requests by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3330](https://github.com/web-infra-dev/midscene/pull/3330) - fix(core): preserve arrays in aiQuery JSON responses by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3345](https://github.com/web-infra-dev/midscene/pull/3345) - fix(core): locate Jev targets without a presence check by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3347](https://github.com/web-infra-dev/midscene/pull/3347) #### Performance 🚀 - perf(workflow): speed up CI with bounded AI concurrency by @quanru in [https://github.com/web-infra-dev/midscene/pull/3333](https://github.com/web-infra-dev/midscene/pull/3333) #### Testing 🧪 - test(report): run e2e files with isolated contexts at concurrency 3 by @await-ovo in [https://github.com/web-infra-dev/midscene/pull/3346](https://github.com/web-infra-dev/midscene/pull/3346) #### CI & Chore ⚙️ - chore(badge): add badge service with GitHub Actions deployment by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3339](https://github.com/web-infra-dev/midscene/pull/3339) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.5...v1.17.6](https://github.com/web-infra-dev/midscene/compare/v1.17.5...v1.17.6) ## v1.17.5 ### Changes #### Features 🎉 - feat(test): host Agent records in unified reports (PR2) by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3326](https://github.com/web-infra-dev/midscene/pull/3326) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.4...v1.17.5](https://github.com/web-infra-dev/midscene/compare/v1.17.4...v1.17.5) ## v1.17.4 ### Changes #### Features 🎉 - feat(core): add mouse action: aiMiddleClick by @lufy90 in [https://github.com/web-infra-dev/midscene/pull/2812](https://github.com/web-infra-dev/midscene/pull/2812) #### Fixes 🐞 - fix(core): preserve nested custom action parameter descriptions by @advance-hub in [https://github.com/web-infra-dev/midscene/pull/3305](https://github.com/web-infra-dev/midscene/pull/3305) - fix(web-integration): honor replace mode for focused inputs without locate by @advance-hub in [https://github.com/web-infra-dev/midscene/pull/3296](https://github.com/web-infra-dev/midscene/pull/3296) - fix(web-integration): align action hook option types with runtime arguments by @advance-hub in [https://github.com/web-infra-dev/midscene/pull/3322](https://github.com/web-infra-dev/midscene/pull/3322) - fix(core): skip dump serialization without update listeners by @advance-hub in [https://github.com/web-infra-dev/midscene/pull/3323](https://github.com/web-infra-dev/midscene/pull/3323) - fix(core): replace numbered point callout with badge-neutral centered marker by @NianZheChao in [https://github.com/web-infra-dev/midscene/pull/3096](https://github.com/web-infra-dev/midscene/pull/3096) - fix(recorder): preserve input events across field changes and stop by @dakjdakd in [https://github.com/web-infra-dev/midscene/pull/3192](https://github.com/web-infra-dev/midscene/pull/3192) - fix(test): publish GitHub summaries from the executable entry by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3321](https://github.com/web-infra-dev/midscene/pull/3321) #### Documentation 📖 - docs(site): redesign homepage feature sections by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3317](https://github.com/web-infra-dev/midscene/pull/3317) #### CI & Chore ⚙️ - chore(site): add provider selection to model configuration cards by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3328](https://github.com/web-infra-dev/midscene/pull/3328) #### New Contributors - @advance-hub made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3305](https://github.com/web-infra-dev/midscene/pull/3305) - @lufy90 made their first contribution in [https://github.com/web-infra-dev/midscene/pull/2812](https://github.com/web-infra-dev/midscene/pull/2812) - @NianZheChao made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3096](https://github.com/web-infra-dev/midscene/pull/3096) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.3...v1.17.4](https://github.com/web-infra-dev/midscene/compare/v1.17.3...v1.17.4) ## v1.17.3 ### Changes #### Features 🎉 - feat(core): add ant-ling model adapter by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3315](https://github.com/web-infra-dev/midscene/pull/3315) - feat(report): add directory report artifact foundation (PR1) by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3312](https://github.com/web-infra-dev/midscene/pull/3312) #### Refactors ♻️ - refactor(core): rename supportedTaskTypes to allowedTaskTypes by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3314](https://github.com/web-infra-dev/midscene/pull/3314) #### Documentation 📖 - docs(site): clarify test entry points by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3310](https://github.com/web-infra-dev/midscene/pull/3310) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.2...v1.17.3](https://github.com/web-infra-dev/midscene/compare/v1.17.2...v1.17.3) ## v1.17.2 ### Changes #### Features 🎉 - feat(core): support custom endpoints for System One models by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3301](https://github.com/web-infra-dev/midscene/pull/3301) #### Fixes 🐞 - fix(core): allow Jev as default model for supported tasks by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3308](https://github.com/web-infra-dev/midscene/pull/3308) - fix(core): support Gemini 4 Argon by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3309](https://github.com/web-infra-dev/midscene/pull/3309) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.1...v1.17.2](https://github.com/web-infra-dev/midscene/compare/v1.17.1...v1.17.2) ## v1.17.1 ### Changes #### Features 🎉 - feat(test): support namespaces for Midscene Nodes by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3300](https://github.com/web-infra-dev/midscene/pull/3300) #### Fixes 🐞 - fix(workflow): preserve MDX in release highlights by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3298](https://github.com/web-infra-dev/midscene/pull/3298) - fix(site): restore v1.17 changelog videos by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3299](https://github.com/web-infra-dev/midscene/pull/3299) #### Documentation 📖 - docs(site): sdk docs restructure by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3297](https://github.com/web-infra-dev/midscene/pull/3297) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.17.0...v1.17.1](https://github.com/web-infra-dev/midscene/compare/v1.17.0...v1.17.1) ## v1.17.0 ### Highlights #### Use your ChatGPT subscription Authorize Midscene through Sign in with ChatGPT (SIWC) to call GPT models using your ChatGPT subscription allowance. The video below demonstrates the browser extension's sign-in and authorization flow. See [Use your ChatGPT subscription](https://www.midscenejs.com/chatgpt-subscription) for setup instructions. #### Experimental Jev 1.14 support Jev can handle planning, localization, and judgments, working with a general-purpose default model for tasks such as text input. See the [Jev configuration guide](https://www.midscenejs.com/model-api-setup#jev) for setup instructions and limitations. The following measurements come from a single run of each demo. A step means one model call; latency excludes page actions and waits. Costs are in USD, calculated at $0.042 per million Jev input tokens, with output tokens free of charge. ##### Fruit tile matching: Jev only Jev handles clicks and localization to clear all fruit pairs until the remaining count reaches zero. [View the execution report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/jev/fruits-tile-matching-report.html). - Model latency per call: **0.887 seconds** on average, **0.774 seconds** at P50. - Input usage: **6,761.4 tokens** per call on average, **101,421 tokens** in total. - Model cost: **$0.000284** per call on average, **$0.00426** in total. ##### Registration form: Jev + DeepSeek Jev handles clicks, localization, gender dropdown selection, and completion checks. DeepSeek generates input values for the email, password, and username fields to complete the registration form together. [View the execution report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/jev/register-form-report.html). The following measurements **cover Jev only and exclude DeepSeek**: - Model latency per call: **0.583 seconds** on average, **0.559 seconds** at P50. - Input usage: **5,265.8 tokens** per call on average, **68,455 tokens** in total. - Model cost: **$0.000221** per call on average, **$0.002875** in total. ### Changes #### Fixes 🐞 - fix(chrome-extension): keep recorder screenshots on their source tab by @dakjdakd in [https://github.com/web-infra-dev/midscene/pull/3194](https://github.com/web-infra-dev/midscene/pull/3194) - fix(workflow): stabilize Studio notarization and unblock release notices by @quanru in [https://github.com/web-infra-dev/midscene/pull/3294](https://github.com/web-infra-dev/midscene/pull/3294) #### Refactors ♻️ - refactor(core): restructure Jev integration and planning delegation by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3295](https://github.com/web-infra-dev/midscene/pull/3295) #### New Contributors - @dakjdakd made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3194](https://github.com/web-infra-dev/midscene/pull/3194) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.16.5...v1.17.0](https://github.com/web-infra-dev/midscene/compare/v1.16.5...v1.17.0) ## v1.16.5 ### Changes **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.16.4...v1.16.5](https://github.com/web-infra-dev/midscene/compare/v1.16.4...v1.16.5) ## v1.16.4 ### Changes **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.16.3...v1.16.4](https://github.com/web-infra-dev/midscene/compare/v1.16.3...v1.16.4) ## v1.16.3 ### Changes #### Features 🎉 - feat(core): add SIWC auth mode and Chrome extension sign-in by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3287](https://github.com/web-infra-dev/midscene/pull/3287) #### Documentation 📖 - docs(site): make model configuration sections easier to discover by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3292](https://github.com/web-infra-dev/midscene/pull/3292) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.16.2...v1.16.3](https://github.com/web-infra-dev/midscene/compare/v1.16.2...v1.16.3) ## v1.16.2 ### Changes #### Features 🎉 - feat(test): redesign CLI reporting and model usage summaries by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3285](https://github.com/web-infra-dev/midscene/pull/3285) #### Fixes 🐞 - fix(workflow): diagnose Chrome Web Store OAuth failures by @quanru in [https://github.com/web-infra-dev/midscene/pull/3284](https://github.com/web-infra-dev/midscene/pull/3284) - fix(core): keep trailing parenthesis in auto-glm finish message by @kwy404 in [https://github.com/web-infra-dev/midscene/pull/3190](https://github.com/web-infra-dev/midscene/pull/3190) - fix(core): validate locate coordinate types strictly by @linhongyu510 in [https://github.com/web-infra-dev/midscene/pull/3068](https://github.com/web-infra-dev/midscene/pull/3068) - fix(core): validate swipe action parameters by @linhongyu510 in [https://github.com/web-infra-dev/midscene/pull/3069](https://github.com/web-infra-dev/midscene/pull/3069) - fix(workflow): build report dependencies and stabilize AI checks by @quanru in [https://github.com/web-infra-dev/midscene/pull/3290](https://github.com/web-infra-dev/midscene/pull/3290) #### Documentation 📖 - docs(site): reorganize model setup and debugging guides by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3288](https://github.com/web-infra-dev/midscene/pull/3288) - docs(site): standardize navigation capitalization by @ottomao in [https://github.com/web-infra-dev/midscene/pull/3291](https://github.com/web-infra-dev/midscene/pull/3291) #### New Contributors - @kwy404 made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3190](https://github.com/web-infra-dev/midscene/pull/3190) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.16.1...v1.16.2](https://github.com/web-infra-dev/midscene/compare/v1.16.1...v1.16.2) ## v1.16.1 ### Changes #### Features 🎉 - feat(test): add file concurrency with maxConcurrentFiles by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3259](https://github.com/web-infra-dev/midscene/pull/3259) #### Fixes 🐞 - fix(playground): isolate reports between executions by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3252](https://github.com/web-infra-dev/midscene/pull/3252) #### Documentation 📖 - docs(site): add GitHub Actions guide for Midscene Test by @await-ovo in [https://github.com/web-infra-dev/midscene/pull/3263](https://github.com/web-infra-dev/midscene/pull/3263) - docs(site): simplify GitHub Actions docs and link to Marketplace by @await-ovo in [https://github.com/web-infra-dev/midscene/pull/3276](https://github.com/web-infra-dev/midscene/pull/3276) - docs(site): clarify Jev setup with combined model configuration by @ottomao in [https://github.com/web-infra-dev/midscene/pull/3277](https://github.com/web-infra-dev/midscene/pull/3277) - docs(site): update introduction of GUI Agent by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3278](https://github.com/web-infra-dev/midscene/pull/3278) - docs(site): clarify Midscene Test terminology and release status by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3279](https://github.com/web-infra-dev/midscene/pull/3279) - docs(site): migrate introduction to the homepage by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3282](https://github.com/web-infra-dev/midscene/pull/3282) #### Testing 🧪 - test(report): migrate report app e2e tests to midscene-test and publish CI reports by @await-ovo in [https://github.com/web-infra-dev/midscene/pull/3275](https://github.com/web-infra-dev/midscene/pull/3275) #### New Contributors - @await-ovo made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3263](https://github.com/web-infra-dev/midscene/pull/3263) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.16.0...v1.16.1](https://github.com/web-infra-dev/midscene/compare/v1.16.0...v1.16.1) ## v1.16.0 ### Highlights #### Jev 1.4 support: faster, lower-cost visual E2E testing Midscene now supports Jev 1.4, continuing our focus on visual understanding to drive UI automation. With this integration, developers can experience faster, lower-cost E2E testing. See the [Jev configuration guide](https://www.midscenejs.com/model-common-config#jev) for setup instructions and the current experimental limitations. In the tile-matching game test shown in the demo below, 28 model calls were made, with model inference averaging **393.57 ms (approximately 0.39 seconds) per call**. Each call averaged **5,025 input tokens** and **67 output tokens**, at a model cost of approximately **$0.000211 per call**. This is calculated at $0.042 per million input tokens, with output tokens free of charge. ### Changes **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.15.6...v1.16.0](https://github.com/web-infra-dev/midscene/compare/v1.15.6...v1.16.0) ## v1.15.6 ### Changes #### Features 🎉 - feat(llm): add dedicated locate model configuration by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3268](https://github.com/web-infra-dev/midscene/pull/3268) - feat(llm): add experimental Jev model support by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3271](https://github.com/web-infra-dev/midscene/pull/3271) #### CI & Chore ⚙️ - chore(core): redesign introduction page by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3267](https://github.com/web-infra-dev/midscene/pull/3267) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.15.5...v1.15.6](https://github.com/web-infra-dev/midscene/compare/v1.15.5...v1.15.6) ## v1.15.5 ### Changes #### Features 🎉 - feat(web): add Puppeteer test runner nodes by @quanru in [https://github.com/web-infra-dev/midscene/pull/3160](https://github.com/web-infra-dev/midscene/pull/3160) - feat(report): redesign test report workspace and clarify execution details by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3245](https://github.com/web-infra-dev/midscene/pull/3245) #### Fixes 🐞 - fix(core): preserve aiAct reference images for independent locating by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3257](https://github.com/web-infra-dev/midscene/pull/3257) - fix(ios): wait for input readiness and restore focus after clearing by @quanru in [https://github.com/web-infra-dev/midscene/pull/3239](https://github.com/web-infra-dev/midscene/pull/3239) - fix(shared): preserve empty string CLI argument values by @quanru in [https://github.com/web-infra-dev/midscene/pull/3260](https://github.com/web-infra-dev/midscene/pull/3260) - fix(core): align default scrolling across Android, iOS, and HarmonyOS by @resonlei in [https://github.com/web-infra-dev/midscene/pull/3225](https://github.com/web-infra-dev/midscene/pull/3225) - fix(web-integration): preserve CLI viewport after disconnect by @quanru in [https://github.com/web-infra-dev/midscene/pull/3261](https://github.com/web-infra-dev/midscene/pull/3261) - fix(test): validate wait options and preserve cross-module screenshots by @quanru in [https://github.com/web-infra-dev/midscene/pull/3246](https://github.com/web-infra-dev/midscene/pull/3246) - fix(web-integration): launch cookie tests without sandbox on Linux CI by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3269](https://github.com/web-infra-dev/midscene/pull/3269) #### CI & Chore ⚙️ - chore(core): add a highlight section to release note by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3256](https://github.com/web-infra-dev/midscene/pull/3256) #### New Contributors - @resonlei made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3225](https://github.com/web-infra-dev/midscene/pull/3225) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.15.4...v1.15.5](https://github.com/web-infra-dev/midscene/compare/v1.15.4...v1.15.5) ## v1.15.4 ### Changes 2026-10-14 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.15.4) #### Features 🎉 - feat(test): add TodoMVC create starters and example sync by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3210](https://github.com/web-infra-dev/midscene/pull/3210) #### Fixes 🐞 - fix(site): restore x profile link in ios showcases by @ottomao in [https://github.com/web-infra-dev/midscene/pull/3145](https://github.com/web-infra-dev/midscene/pull/3145) - fix(core): clarify planning cycle limit error by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3251](https://github.com/web-infra-dev/midscene/pull/3251) #### Documentation 📖 - docs(core): guide to use chatgpt subscription by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3248](https://github.com/web-infra-dev/midscene/pull/3248) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.15.3...v1.15.4](https://github.com/web-infra-dev/midscene/compare/v1.15.3...v1.15.4) ## v1.15.3 ### Changes 2026-10-13 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.15.3) #### Features 🎉 - feat(test): generate Markdown results after each test run by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3240](https://github.com/web-infra-dev/midscene/pull/3240) #### Fixes 🐞 - fix(test): clarify project creation guidance and test reference by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3229](https://github.com/web-infra-dev/midscene/pull/3229) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.15.2...v1.15.3](https://github.com/web-infra-dev/midscene/compare/v1.15.2...v1.15.3) ## v1.15.2 ### Changes 2026-10-12 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.15.2) #### Fixes 🐞 - fix(core): drain cancelled operations before runner continuation by @codeestX in [https://github.com/web-infra-dev/midscene/pull/3216](https://github.com/web-infra-dev/midscene/pull/3216) - fix(site): redirect historical documentation URLs by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3237](https://github.com/web-infra-dev/midscene/pull/3237) - fix(workflow): centralize AI CI connection timeout by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3238](https://github.com/web-infra-dev/midscene/pull/3238) - fix(report): retain test evidence and clarify execution failures by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3226](https://github.com/web-infra-dev/midscene/pull/3226) #### Documentation 📖 - docs(site): add Rome OS and reorder homepage users by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3231](https://github.com/web-infra-dev/midscene/pull/3231) #### CI & Chore ⚙️ - ci(workflow): increase AI network connection attempt timeout by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3230](https://github.com/web-infra-dev/midscene/pull/3230) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.15.1...v1.15.2](https://github.com/web-infra-dev/midscene/compare/v1.15.1...v1.15.2) ## v1.15.1 ### Changes 2026-10-12 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.15.1) #### Fixes 🐞 - fix(test): load tsx through its ESM entry for project configs by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3227](https://github.com/web-infra-dev/midscene/pull/3227) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.15.0...v1.15.1](https://github.com/web-infra-dev/midscene/compare/v1.15.0...v1.15.1) ## v1.15.0 ### Changes 2026-10-10 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.15.0) #### Features 🎉 - feat(core): add custom action readiness hook by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3133](https://github.com/web-infra-dev/midscene/pull/3133) - feat(test): add model verification command and setup guidance by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3209](https://github.com/web-infra-dev/midscene/pull/3209) - feat(llm): configure model streaming and record call metadata by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3214](https://github.com/web-infra-dev/midscene/pull/3214) - feat(cli): add ChatGPT SIWC login and refresh by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3215](https://github.com/web-infra-dev/midscene/pull/3215) #### Fixes 🐞 - fix(report): prepare timeline screenshots in atomic groups by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3211](https://github.com/web-infra-dev/midscene/pull/3211) - fix(test): preserve CLI error stacks and causes by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3212](https://github.com/web-infra-dev/midscene/pull/3212) #### Refactors ♻️ - refactor(cli): nest SIWC credentials with file metadata by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3220](https://github.com/web-infra-dev/midscene/pull/3220) #### Documentation 📖 - docs(site): refresh homepage messaging and layout by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3204](https://github.com/web-infra-dev/midscene/pull/3204) #### CI & Chore ⚙️ - chore(docs): update homepage by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3219](https://github.com/web-infra-dev/midscene/pull/3219) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.14.0...v1.15.0](https://github.com/web-infra-dev/midscene/compare/v1.14.0...v1.15.0) ## v1.14.0 ### Changes 2026-09-29 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.14.0) #### Features 🎉 - feat(web-integration): add BrowserAgent page selection actions by @quanru in [https://github.com/web-infra-dev/midscene/pull/2774](https://github.com/web-infra-dev/midscene/pull/2774) - feat(test): add setAIContext node for midscene/test by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3188](https://github.com/web-infra-dev/midscene/pull/3188) - feat(ios): support gateway WDA base URLs by @quanru in [https://github.com/web-infra-dev/midscene/pull/3187](https://github.com/web-infra-dev/midscene/pull/3187) - feat(core): support Responses API with configuration and documentation by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3161](https://github.com/web-infra-dev/midscene/pull/3161) #### Fixes 🐞 - fix(core): record HTTP responses on model parsing failures by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3185](https://github.com/web-infra-dev/midscene/pull/3185) - fix(site): restore legacy URLs and refresh favicon cache by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3198](https://github.com/web-infra-dev/midscene/pull/3198) - fix(site): redirect retired documentation URLs by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3202](https://github.com/web-infra-dev/midscene/pull/3202) - fix(cli): upgrade yargs for Node.js 26 compatibility by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3203](https://github.com/web-infra-dev/midscene/pull/3203) #### Refactors ♻️ - refactor(core): configure locate result keys and aliases by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3189](https://github.com/web-infra-dev/midscene/pull/3189) #### Documentation 📖 - docs(site): consolidate images under a dedicated directory by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3186](https://github.com/web-infra-dev/midscene/pull/3186) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.13.3...v1.14.0](https://github.com/web-infra-dev/midscene/compare/v1.13.3...v1.14.0) ## v1.13.3 ### Changes 2026-09-23 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.13.3) #### Features 🎉 - feat(test): expose run health metrics and inline report assets by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3172](https://github.com/web-infra-dev/midscene/pull/3172) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.13.2...v1.13.3](https://github.com/web-infra-dev/midscene/compare/v1.13.2...v1.13.3) ## v1.13.2 ### Changes 2026-09-23 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.13.2) #### Fixes 🐞 - fix(computer): avoid encoded PowerShell transport on Windows by @quanru in [https://github.com/web-infra-dev/midscene/pull/3166](https://github.com/web-infra-dev/midscene/pull/3166) #### Documentation 📖 - docs(site): add GPT-6 Sol and Luna model guidance by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3182](https://github.com/web-infra-dev/midscene/pull/3182) - docs(site): add midscene-android and midscene-jev-runner to Awesome Midscene by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3179](https://github.com/web-infra-dev/midscene/pull/3179) #### CI & Chore ⚙️ - chore(test): generate separate node references for each project by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3181](https://github.com/web-infra-dev/midscene/pull/3181) - chore(test): update spec for midscene test by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3184](https://github.com/web-infra-dev/midscene/pull/3184) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.13.1...v1.13.2](https://github.com/web-infra-dev/midscene/compare/v1.13.1...v1.13.2) ## v1.13.1 ### Changes 2026-09-22 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.13.1) #### Features 🎉 - feat(report): redesign test reports and unify timeline interactions by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3174](https://github.com/web-infra-dev/midscene/pull/3174) #### Fixes 🐞 - fix(cli): allow sequential YAML files to reuse one page by @quanru in [https://github.com/web-infra-dev/midscene/pull/3164](https://github.com/web-infra-dev/midscene/pull/3164) #### Documentation 📖 - docs(site): update Xiaomi MiMo model guidance by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3176](https://github.com/web-infra-dev/midscene/pull/3176) #### CI & Chore ⚙️ - chore(workflow): upgrade rstest to 0.12.0 by @fi3ework in [https://github.com/web-infra-dev/midscene/pull/3178](https://github.com/web-infra-dev/midscene/pull/3178) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.13.0...v1.13.1](https://github.com/web-infra-dev/midscene/compare/v1.13.0...v1.13.1) ## v1.13.0 ### Changes 2026-09-20 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.13.0) #### Features 🎉 - feat(test): unify native Test and legacy YAML execution and reporting by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3139](https://github.com/web-infra-dev/midscene/pull/3139) #### Fixes 🐞 - fix(report): support dark mobile tabs by @quanru in [https://github.com/web-infra-dev/midscene/pull/3162](https://github.com/web-infra-dev/midscene/pull/3162) - fix(shared): enable declaration maps by @Amour1688 in [https://github.com/web-infra-dev/midscene/pull/3165](https://github.com/web-infra-dev/midscene/pull/3165) #### Documentation 📖 - docs(site): generalize GPT original detail limitations by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3163](https://github.com/web-infra-dev/midscene/pull/3163) #### New Contributors - @Amour1688 made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3165](https://github.com/web-infra-dev/midscene/pull/3165) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.9...v1.13.0](https://github.com/web-infra-dev/midscene/compare/v1.12.9...v1.13.0) ## v1.12.9 ### Changes 2026-09-17 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.9) #### Features 🎉 - feat(computer): support desktop swipe gestures by @quanru in [https://github.com/web-infra-dev/midscene/pull/3144](https://github.com/web-infra-dev/midscene/pull/3144) - feat(core): expose device adapter schema and types by @quanru in [https://github.com/web-infra-dev/midscene/pull/3153](https://github.com/web-infra-dev/midscene/pull/3153) - feat(report): support mobile steps and player views by @quanru in [https://github.com/web-infra-dev/midscene/pull/3155](https://github.com/web-infra-dev/midscene/pull/3155) - feat(report): support portable step selectors by @quanru in [https://github.com/web-infra-dev/midscene/pull/3159](https://github.com/web-infra-dev/midscene/pull/3159) - feat(test): support native ESM project configs by @quanru in [https://github.com/web-infra-dev/midscene/pull/3154](https://github.com/web-infra-dev/midscene/pull/3154) #### Fixes 🐞 - fix(harmony): convert swipe duration to HDC speed by @quanru in [https://github.com/web-infra-dev/midscene/pull/3149](https://github.com/web-infra-dev/midscene/pull/3149) #### Refactors ♻️ - refactor(core): centralize model request lifecycle and protocol calls by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3147](https://github.com/web-infra-dev/midscene/pull/3147) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.8...v1.12.9](https://github.com/web-infra-dev/midscene/compare/v1.12.8...v1.12.9) ## v1.12.8 ### Changes 2026-09-16 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.8) #### Fixes 🐞 - fix(core): retry invalid planning action parameters by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3138](https://github.com/web-infra-dev/midscene/pull/3138) - fix(core): retry incomplete planning responses by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3146](https://github.com/web-infra-dev/midscene/pull/3146) - fix(core): clarify scroll and swipe intent in planning by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3136](https://github.com/web-infra-dev/midscene/pull/3136) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.7...v1.12.8](https://github.com/web-infra-dev/midscene/compare/v1.12.7...v1.12.8) ## v1.12.7 ### Changes 2026-09-15 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.7) #### Fixes 🐞 - fix(core): clarify and validate scroll and swipe actions by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3134](https://github.com/web-infra-dev/midscene/pull/3134) - fix(computer): improve modifier-key input compatibility in desktop clients by @quanru in [https://github.com/web-infra-dev/midscene/pull/3124](https://github.com/web-infra-dev/midscene/pull/3124) - fix(web-integration): reuse static UI context by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3089](https://github.com/web-infra-dev/midscene/pull/3089) - fix(android-playground): preserve scrcpy GOP integrity by @quanru in [https://github.com/web-infra-dev/midscene/pull/3142](https://github.com/web-infra-dev/midscene/pull/3142) - fix(core): record YAML sleep in reports without model dependencies by @quanru in [https://github.com/web-infra-dev/midscene/pull/3118](https://github.com/web-infra-dev/midscene/pull/3118) - fix(shared): preserve schema-typed CLI strings by @quanru in [https://github.com/web-infra-dev/midscene/pull/3135](https://github.com/web-infra-dev/midscene/pull/3135) - fix(computer): capture reliable opaque RDP screenshots by @quanru in [https://github.com/web-infra-dev/midscene/pull/3140](https://github.com/web-infra-dev/midscene/pull/3140) #### Documentation 📖 - docs(site): add application knowledge guide and update context examples by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3143](https://github.com/web-infra-dev/midscene/pull/3143) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.6...v1.12.7](https://github.com/web-infra-dev/midscene/compare/v1.12.6...v1.12.7) ## v1.12.6 ### Changes 2026-09-10 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.6) #### Features 🎉 - feat(report): add unified Midscene Test reports with visual debugging by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3109](https://github.com/web-infra-dev/midscene/pull/3109) - feat(test): support project-scoped node registration by @LawisChen in [https://github.com/web-infra-dev/midscene/pull/3111](https://github.com/web-infra-dev/midscene/pull/3111) #### Fixes 🐞 - fix(core): collect streaming usage through stream completion by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3117](https://github.com/web-infra-dev/midscene/pull/3117) - fix(core): preserve global model config with custom clients by @linhongyu510 in [https://github.com/web-infra-dev/midscene/pull/3094](https://github.com/web-infra-dev/midscene/pull/3094) #### Refactors ♻️ - refactor(core): split model service caller by protocol by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3116](https://github.com/web-infra-dev/midscene/pull/3116) - refactor(test): align platform test exports and clarify project docs by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3123](https://github.com/web-infra-dev/midscene/pull/3123) #### Documentation 📖 - docs(site): fix reference callout boundary and section headings by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3121](https://github.com/web-infra-dev/midscene/pull/3121) - docs(site): update DeepSeek Flash model configuration by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3131](https://github.com/web-infra-dev/midscene/pull/3131) #### CI & Chore ⚙️ - chore(test): add model configuration template to .env.example and update README; adjust create command tests by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3115](https://github.com/web-infra-dev/midscene/pull/3115) #### New Contributors - @LawisChen made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3111](https://github.com/web-infra-dev/midscene/pull/3111) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.5...v1.12.6](https://github.com/web-infra-dev/midscene/compare/v1.12.5...v1.12.6) ## v1.12.5 ### Changes 2026-09-08 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.5) #### Features 🎉 - feat(test): add 'create' command to create testing project by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3102](https://github.com/web-infra-dev/midscene/pull/3102) - feat(core): add GPT-6 adapter and model-specific Codex parameters by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3110](https://github.com/web-infra-dev/midscene/pull/3110) #### Fixes 🐞 - fix(computer): smooth native drag trajectory by @quanru in [https://github.com/web-infra-dev/midscene/pull/3098](https://github.com/web-infra-dev/midscene/pull/3098) - fix(studio): restrict file exports and default local services to loopback by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3103](https://github.com/web-infra-dev/midscene/pull/3103) - fix(visualizer): show aiAct output alongside report by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3091](https://github.com/web-infra-dev/midscene/pull/3091) - fix(core): unify normalized coordinate mapping and rounding by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3113](https://github.com/web-infra-dev/midscene/pull/3113) #### Refactors ♻️ - refactor(core): use authoritative centers throughout localization by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3100](https://github.com/web-infra-dev/midscene/pull/3100) #### Documentation 📖 - docs(site): unify Midscene Test branding by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3106](https://github.com/web-infra-dev/midscene/pull/3106) - docs(workflow): organize readmes around GUI Agent and Testing Kit by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3108](https://github.com/web-infra-dev/midscene/pull/3108) - docs(site): clarify execution records and reorder testing kit by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3112](https://github.com/web-infra-dev/midscene/pull/3112) #### CI & Chore ⚙️ - ci(workflow): add `notify_stable_release` dispatch option to toggle IM notifications by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3107](https://github.com/web-infra-dev/midscene/pull/3107) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.4...v1.12.5](https://github.com/web-infra-dev/midscene/compare/v1.12.4...v1.12.5) ## v1.12.4 ### Changes 2026-09-07 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.4) #### Features 🎉 - feat(core): support scoped AI contexts and stateless Test Runner workflows by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3065](https://github.com/web-infra-dev/midscene/pull/3065) #### Fixes 🐞 - fix(computer): handle Linux delayed input by @simplyme0823 in [https://github.com/web-infra-dev/midscene/pull/3081](https://github.com/web-infra-dev/midscene/pull/3081) - fix(cli): honor HarmonyOS batch target overrides by @quanru in [https://github.com/web-infra-dev/midscene/pull/3082](https://github.com/web-infra-dev/midscene/pull/3082) - fix(core): retry locate responses with missing coordinates by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3095](https://github.com/web-infra-dev/midscene/pull/3095) - fix(test): settle running steps on cancellation by @quanru in [https://github.com/web-infra-dev/midscene/pull/3088](https://github.com/web-infra-dev/midscene/pull/3088) - fix(core): avoid duplicate YAML assertion errors by @quanru in [https://github.com/web-infra-dev/midscene/pull/3044](https://github.com/web-infra-dev/midscene/pull/3044) #### Performance 🚀 - perf(shared): cache system Chrome path resolution by @quanru in [https://github.com/web-infra-dev/midscene/pull/3052](https://github.com/web-infra-dev/midscene/pull/3052) - perf(visualizer): memoize selected action lookup by @quanru in [https://github.com/web-infra-dev/midscene/pull/3054](https://github.com/web-infra-dev/midscene/pull/3054) #### Documentation 📖 - docs(core): update overview for test runner by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3092](https://github.com/web-infra-dev/midscene/pull/3092) - docs(site): use official Doubao pricing by @simplyme0823 in [https://github.com/web-infra-dev/midscene/pull/3093](https://github.com/web-infra-dev/midscene/pull/3093) #### Testing 🧪 - test(web-integration): expand input E2E coverage by @quanruzhuoxiu in [https://github.com/web-infra-dev/midscene/pull/2953](https://github.com/web-infra-dev/midscene/pull/2953) #### CI & Chore ⚙️ - chore(test): align node contracts with agent APIs by @yuyutaotao in [https://github.com/web-infra-dev/midscene/pull/3101](https://github.com/web-infra-dev/midscene/pull/3101) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.3...v1.12.4](https://github.com/web-infra-dev/midscene/compare/v1.12.3...v1.12.4) ## v1.12.3 ### Changes 2026-09-02 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.3) #### Features 🎉 - feat(core): add configurable text input strategies by @quanruzhuoxiu in [https://github.com/web-infra-dev/midscene/pull/3042](https://github.com/web-infra-dev/midscene/pull/3042) #### Fixes 🐞 - fix(android): recover static scrcpy screenshots in-band by @quanru in [https://github.com/web-infra-dev/midscene/pull/3074](https://github.com/web-infra-dev/midscene/pull/3074) - fix(ios): make keyboard auto-dismiss best effort by @quanru in [https://github.com/web-infra-dev/midscene/pull/3075](https://github.com/web-infra-dev/midscene/pull/3075) - fix(android): harden scrcpy freshness recovery by @quanru in [https://github.com/web-infra-dev/midscene/pull/3080](https://github.com/web-infra-dev/midscene/pull/3080) - fix(studio): restore packaged Android device preview by @quanru in [https://github.com/web-infra-dev/midscene/pull/3077](https://github.com/web-infra-dev/midscene/pull/3077) - fix(core): make JSON object validation explicit by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3076](https://github.com/web-infra-dev/midscene/pull/3076) - fix(computer): use physical pixels for Windows DPI scaling by @quanru in [https://github.com/web-infra-dev/midscene/pull/3064](https://github.com/web-infra-dev/midscene/pull/3064) - fix(core): use rstest mock API in core tests by @quanru in [https://github.com/web-infra-dev/midscene/pull/3084](https://github.com/web-infra-dev/midscene/pull/3084) #### Refactors ♻️ - refactor(core): decouple model interaction protocols by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3070](https://github.com/web-infra-dev/midscene/pull/3070) - refactor(core): simplify planning locate parameters by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3073](https://github.com/web-infra-dev/midscene/pull/3073) #### Documentation 📖 - docs(site): refresh homepage model strategy cards by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3035](https://github.com/web-infra-dev/midscene/pull/3035) #### CI & Chore ⚙️ - chore(workflow): migrate core to rstest by @fi3ework in [https://github.com/web-infra-dev/midscene/pull/3033](https://github.com/web-infra-dev/midscene/pull/3033) #### Other Changes - style(site): polish homepage toolkit cards and dividers by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3078](https://github.com/web-infra-dev/midscene/pull/3078) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.2...v1.12.3](https://github.com/web-infra-dev/midscene/compare/v1.12.2...v1.12.3) ## v1.12.2 ### Changes 2026-08-28 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.2) #### Features 🎉 - feat(core): apply preferred language to planning details by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3062](https://github.com/web-infra-dev/midscene/pull/3062) #### Fixes 🐞 - fix(android): avoid scrcpy server upload memory leak by @quanru in [https://github.com/web-infra-dev/midscene/pull/3048](https://github.com/web-infra-dev/midscene/pull/3048) - fix(web-integration): validate CDP endpoint protocol by @quanru in [https://github.com/web-infra-dev/midscene/pull/3051](https://github.com/web-infra-dev/midscene/pull/3051) - fix(android-playground): correct dev:server bin path by @quanru in [https://github.com/web-infra-dev/midscene/pull/3050](https://github.com/web-infra-dev/midscene/pull/3050) - fix(shared): preserve recorder artifacts during signal shutdown by @quanru in [https://github.com/web-infra-dev/midscene/pull/3049](https://github.com/web-infra-dev/midscene/pull/3049) #### Refactors ♻️ - refactor(core): organize DeepSeek model files by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3059](https://github.com/web-infra-dev/midscene/pull/3059) #### Documentation 📖 - docs(site): add appcontrolbench by @simplyme0823 in [https://github.com/web-infra-dev/midscene/pull/3031](https://github.com/web-infra-dev/midscene/pull/3031) - docs(site): clarify preferred language behavior by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3061](https://github.com/web-infra-dev/midscene/pull/3061) - docs(site): clarify AppControlBench chart grouping by @simplyme0823 in [https://github.com/web-infra-dev/midscene/pull/3063](https://github.com/web-infra-dev/midscene/pull/3063) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.1...v1.12.2](https://github.com/web-infra-dev/midscene/compare/v1.12.1...v1.12.2) ## v1.12.1 ### Changes 2026-08-27 · [GitHub Release](https://github.com/web-infra-dev/midscene/releases/tag/v1.12.1) #### Features 🎉 - feat(site): implement the V4 homepage design by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3025](https://github.com/web-infra-dev/midscene/pull/3025) - feat(test): add P0 platform preset nodes by @quanru in [https://github.com/web-infra-dev/midscene/pull/3026](https://github.com/web-infra-dev/midscene/pull/3026) #### Fixes 🐞 - fix(android): adopt upstream ADB disconnect fix by @quanru in [https://github.com/web-infra-dev/midscene/pull/3016](https://github.com/web-infra-dev/midscene/pull/3016) - fix(core): make task execution errors transport-safe by @quanru in [https://github.com/web-infra-dev/midscene/pull/3000](https://github.com/web-infra-dev/midscene/pull/3000) - fix(ios): make keyboard dismissal deterministic by @quanru in [https://github.com/web-infra-dev/midscene/pull/3017](https://github.com/web-infra-dev/midscene/pull/3017) - fix(site): restore docs header alignment and update AVATR logo by @xiong35 in [https://github.com/web-infra-dev/midscene/pull/3032](https://github.com/web-infra-dev/midscene/pull/3032) - fix(android): constrain replanning screenshots to scrcpy max size by @quanru in [https://github.com/web-infra-dev/midscene/pull/3021](https://github.com/web-infra-dev/midscene/pull/3021) - fix(android): configure bitrate and harden scrcpy recovery by @quanru in [https://github.com/web-infra-dev/midscene/pull/3009](https://github.com/web-infra-dev/midscene/pull/3009) - fix(core): deduplicate multimodal reference images in reports by @quanru in [https://github.com/web-infra-dev/midscene/pull/3019](https://github.com/web-infra-dev/midscene/pull/3019) - fix(cli): restore YAML task progress output by @quanru in [https://github.com/web-infra-dev/midscene/pull/3028](https://github.com/web-infra-dev/midscene/pull/3028) - fix(cli): preserve serial YAML config order by @quanru in [https://github.com/web-infra-dev/midscene/pull/2972](https://github.com/web-infra-dev/midscene/pull/2972) - fix(workflow): replace simple-git-hooks with husky by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3037](https://github.com/web-infra-dev/midscene/pull/3037) - fix(cli): isolate shared-browser YAML tabs by @quanru in [https://github.com/web-infra-dev/midscene/pull/2967](https://github.com/web-infra-dev/midscene/pull/2967) - fix(android): avoid unreliable select-all when clearing inputs by @quanru in [https://github.com/web-infra-dev/midscene/pull/3018](https://github.com/web-infra-dev/midscene/pull/3018) - fix(test): load TypeScript configs on Windows by @dajiaohuang in [https://github.com/web-infra-dev/midscene/pull/3030](https://github.com/web-infra-dev/midscene/pull/3030) - fix(core): omit DeepSeek temperature in thinking mode by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3043](https://github.com/web-infra-dev/midscene/pull/3043) - fix(shared): remove Canvas image fallback by @quanruzhuoxiu in [https://github.com/web-infra-dev/midscene/pull/2888](https://github.com/web-infra-dev/midscene/pull/2888) #### Documentation 📖 - docs(site): update DeepSeek card description by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3036](https://github.com/web-infra-dev/midscene/pull/3036) - docs(site): add v1.11 and v1.12 changelogs by @quanruzhuoxiu in [https://github.com/web-infra-dev/midscene/pull/3034](https://github.com/web-infra-dev/midscene/pull/3034) - docs(site): move DeepSeek guidance into model notes by @EAGzzyCSL in [https://github.com/web-infra-dev/midscene/pull/3039](https://github.com/web-infra-dev/midscene/pull/3039) #### Testing 🧪 - test(report): verify screenshot pixel integrity by @linhongyu510 in [https://github.com/web-infra-dev/midscene/pull/2976](https://github.com/web-infra-dev/midscene/pull/2976) #### CI & Chore ⚙️ - chore(workflow): migrate cli and web-integration to rstest by @fi3ework in [https://github.com/web-infra-dev/midscene/pull/3007](https://github.com/web-infra-dev/midscene/pull/3007) #### Other Changes - 支持bridge 模式创建不打扰用户的 tab by @RainMountainCao in [https://github.com/web-infra-dev/midscene/pull/3038](https://github.com/web-infra-dev/midscene/pull/3038) #### New Contributors - @RainMountainCao made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3038](https://github.com/web-infra-dev/midscene/pull/3038) - @dajiaohuang made their first contribution in [https://github.com/web-infra-dev/midscene/pull/3030](https://github.com/web-infra-dev/midscene/pull/3030) - @linhongyu510 made their first contribution in [https://github.com/web-infra-dev/midscene/pull/2976](https://github.com/web-infra-dev/midscene/pull/2976) **Full Changelog**: [https://github.com/web-infra-dev/midscene/compare/v1.12.0...v1.12.1](https://github.com/web-infra-dev/midscene/compare/v1.12.0...v1.12.1) ## v1.12 - DeepSeek V4, Midscene Test, and Report Timing Summaries v1.12 adds DeepSeek V4 vision model support, introduces Midscene Test (Beta), and adds timing summaries to reports. ### DeepSeek V4 Vision Model Support - Added support for `deepseek-v4-flash-vision-exp`. See [Common Model Configuration](/model-api-setup.md#deepseek) for setup and [Midscene 1.12: Support for DeepSeek V4 Flash Vision Exp Multimodal Model](https://medium.com/@midscene/midscene-1-12-support-for-deepseek-v4-flash-vision-exp-multimodal-model-f87395075114?postPublishedType=initial) for details. ### Midscene Test (Beta) - Added `@midscene/test` for natural-language tests in YAML with TypeScript Node extensions. Midscene Test will gradually replace the legacy YAML automation solution; its protocol and APIs remain in Beta. See the [Midscene Test overview](/midscene-test/overview.md). ### Reports and Reliability - The Report sidebar now shows total elapsed time and model-call time. Markdown reports also summarize time and token usage by model. - The screenshot pipeline now saves observation frames as JPEG, reducing the storage footprint of run artifacts. - Fixed resource resolution for external yadb and scrcpy binaries in Electron ASAR packages. ## v1.11 - Cross-Platform Reliability Improvements v1.11 improves model verification, mobile input, and report generation reliability. ### Reliability and Documentation - Fixed the model verification callback losing its Playground SDK method context. - Fixed HarmonyOS explicit app launches failing to resolve declared abilities or mapped launch targets. - Android and HarmonyOS now select all text before clearing an input, improving compatibility across input methods and controls. - Playwright report filenames are now bounded and collision-resistant, preventing `ENAMETOOLONG` failures from long titles. - Added execution cost data to the Doubao Seed Android showcase. ## v1.10 - BDD-Style Scripts, Doubao-Seed-2.1, and MCP Retirement v1.10 adds BDD-style Gherkin script execution, upgrades the recommended Doubao model to Doubao-Seed-2.1, and formally retires MCP server packages. Going forward, use Skills and the platform CLIs when AI agents need to drive Midscene. ### BDD-Style Scripts with Gherkin - Added `agent.runGherkinScenario()` for running Gherkin scenarios directly from JavaScript / TypeScript. - Added the `runGherkinScenario` step for YAML flows, so natural-language scenarios can be written as `Given` / `When` / `Then` steps and executed in order. - `Given` / `When` map to `aiAct`, while `Then` and following `And` / `But` steps map to `aiAssert`. This keeps test cases readable in natural language while giving them a stable step structure. - Midscene currently supports a single-`Scenario` subset of Gherkin. BDD-related capabilities are still in Beta. See: [BDD-Style Scripts with Gherkin](/advanced/bdd-style-scripts-with-gherkin.md) ### New Model Support - Recommended and supported `Doubao-Seed-2.1-turbo`, which has very fast localization speed and strong localization quality in our current private evaluation set. - The Doubao Seed family now uses `MIDSCENE_MODEL_FAMILY="doubao-seed"`, while the legacy `doubao-vision` family remains compatible. See: [Common Model Configuration](/model-api-setup.md#doubao-seed-model), [Model Strategy](/model-selection.md) ### MCP Retirement - Midscene no longer ships MCP server packages, including `@midscene/web-bridge-mcp`, `@midscene/android-mcp`, `@midscene/ios-mcp`, `@midscene/harmony-mcp`, `@midscene/computer-mcp`, and `@midscene/mcp`. - Use [Skills](/skills.md) and the platform CLIs when AI coding agents need to operate browsers, mobile devices, or desktop apps. - If you still depend on MCP servers, pin Midscene to `1.9.8`. This is the final version that includes MCP support. See: [MCP Integration Has Been Retired](/mcp.md) ## v1.9 - New Model Support, YAML Automation, and AndroidWorld Benchmark v1.9 expands model support, improves YAML automation, and makes reports, Android automation, Web input, and desktop automation more reliable. ### AndroidWorld Benchmark Midscene now includes an AndroidWorld benchmark report. With v1.9.5, Midscene achieved **Pass\@1 93.10%**, **Pass\@2 95.69%**, and **Pass\@3 97.41%** in this benchmark. See: [AndroidWorld Benchmark Report](/android-world-benchmark-report.md) ### New Model Support - Added Kimi and Xiaomi MiMo model support. See: [Common Model Configuration](/model-api-setup.md) ### Model and Planning Updates - `aiAct` now supports image prompts. - `MIDSCENE_MODEL_REASONING_ENABLED` now supports `default`, so Midscene can follow each model family's default thinking behavior. - Gemini thinking content and GPT-5 reasoning configuration are now handled more completely. - `aiAct` falls back to model planning when a cached plan becomes invalid, and clears the corresponding cache entry. - AI request errors now include retry-attempt details, parse failures preserve raw model responses, and parsed locate results are validated before use. - Model dumps now expose more model response metadata, including raw choice messages and response model names in usage data. - The `deepLocate` search area is now displayed in reports. ### Chrome Extension - Chrome extension Bridge mode now supports file upload. - Bridge-mode file uploads now honor file chooser accept filters and WSL file paths. ### YAML, CLI, and MCP - `1.9.8` is the final Midscene version that includes MCP support. Later versions retire MCP server packages in favor of Skills and the platform CLIs. - Platform CLIs now accept agent behavior init args. - YAML scripts now support the HarmonyOS target in the CLI, so HarmonyOS automation can be driven through the same script runner workflow as Web, Android, iOS, and Computer. See: [Automate with Scripts in YAML](/automate-with-scripts-in-yaml.md), [HarmonyOS API](/sdk/harmonyos.md) - YAML Web config supports custom HTTP headers for browser automation. - YAML Web config supports `downloadPath` for browser downloads. - YAML runs now surface real execution errors instead of ending as a silent "not executed" case. - YAML batch runs can retry failed cases. - Successful YAML runs now print the report path. - Explicit YAML report file names are now honored. - CLI / MCP / Skill flows can expose `deepLocate` / `deepThink` controls through shared flags. - Assert CLI / MCP tooling forwards custom failure messages to make assertion failures clearer. - The CLI resolves `@rstest/core` from the CLI package itself and lazy-loads Rstest core, making framework runs more stable from external launch paths. ### Reports - `recordToReport` now supports custom screenshots. - Report exports keep image paths aligned with exported screenshots. - Reports include a JSON tree view for inspecting structured task and model data. - Report screenshots, labels, playground server origin handling, and context spacing were refined. ### Studio and Recorder - Studio recorder descriptions and preview input coalescing were stabilized. - Studio now handles invalid model environment configuration more safely. - Recorder workflows can generate Markdown replay output. ### Android Automation - Android action controls and planning guidance were improved for native mobile automation flows. ### Computer Automation - Computer desktop automation now ships Intel packaging. - Libnut scrolling now emits one full wheel delta per scroll tick. ### Bug Fixes - Fixed `longPress` duration in Web integration being capped at 600ms. - Fixed dropped characters when Web input fields re-render during typing. - Fixed HarmonyOS MCP startup failures caused by `photon` / `sharp` WASM initialization in some environments. - Fixed blank first-frame screenshots in Computer RDP sessions. - Self-healed missing execute permission on the Computer phased-scroll helper. - Added a warning for elevated Windows app input drops. - Added IPv6 RDP host support for Computer automation. ### Documentation Updates - Documented Azure OpenAI-compatible endpoint setup. ## v1.8 - Midscene Studio Desktop App & Multi-Platform Enhancements v1.8 introduces **Midscene Studio**, a brand-new desktop application, alongside new interaction APIs (long press / clear input), refined model planning behavior, and broad upgrades across device integrations, the report system, and the MCP toolset. ### Midscene Studio — A New Desktop Application (Beta) Midscene Studio is an Electron-based desktop app that brings every Midscene playground into a single native shell. It is currently in **Beta** — download the current Studio build from the [latest release page](https://github.com/web-infra-dev/midscene/releases/latest) by choosing a `midscene-studio-beta-*` asset, try it out, and let us know what works (and what doesn't): - **Multi-platform playground**: Switch seamlessly between Web, Android, iOS, HarmonyOS, and Computer playgrounds inside the same Studio app - **Interactive device preview**: Manually drive Android / iOS / HarmonyOS device previews with mouse and touch input; Web preview supports live streaming #### Coming next: record-to-replay Midscene scripts inside Studio We're building a full record → script → replay loop into Studio: drive a real device inside Studio, automatically capture the interaction as a structured Midscene script, then replay, debug, and export it without leaving the app. The capability will roll out across upcoming releases — stay tuned. ### YAML Workflow Enhancements - **Android `runAdbShell` timeout**: A `timeout` option is now accepted in both the JavaScript API and YAML scripts. See: [Android API](/sdk/android.md), [Automate with Scripts in YAML](/automate-with-scripts-in-yaml.md) ### New Interaction APIs - **`agent.aiLongPress()`**: Long-press a target element to trigger long-press menus and similar gestures. See: [API Reference](/reference.md#agentailongpress) - **`agent.aiClearInput()`**: Clear the contents of an input field, ideal when clearing needs to be its own step. See: [API Reference](/reference.md#agentaiclearinput) ### Device and Platform Integrations - **iOS external WDA sessions**: iOS now supports connecting to existing WebDriverAgent sessions, making it easier to reuse an external WDA setup - **Pluggable iOS device implementation**: The iOSDevice implementation can be overridden, enabling deeper extension or customization - **Computer remote desktop**: RDP connection options are now exposed through Computer MCP / CLI connection tools, letting you take over a remote Windows desktop directly - **`agentForComputer` rename**: `agentForComputer` is introduced as the primary API; the original `agentFromComputer` is kept as a deprecated alias - **Puppeteer CLI viewport options**: The Puppeteer CLI now accepts viewport configuration, so you can size the browser at launch from the command line ### Model and Planning Behavior - **Usage intent decoupled from config slot**: Model usage intent is now tracked separately from resolved config slots, making multi-model planning, locating, and report display clearer - **Native thinking off by default**: For supported model families, Midscene now disables model-native thinking by default to improve execution speed and stability. See: [Model-Native Thinking Mode](/model-config.md#model-native-reasoning) - **Doubao fast tier**: Doubao fast tier configuration is now supported through `MIDSCENE_MODEL_EXTRA_BODY_JSON={"service_tier":"fast"}`. See: [Common Model Configuration](/model-api-setup.md) - **GLM-5V-Turbo support**: Added support for Zhipu GLM-5V-Turbo. See: [Common Model Configuration](/model-api-setup.md) - **Better scrollable select planning**: Planning for scrollable selects (dropdowns, scroll wheels) is more reliable in complex scenarios ### MCP and Platform CLIs - **New `assert` MCP tool**: The MCP server now exposes an assertion tool backed by `aiAssert`, so AI assistants can run assertions directly. See: [MCP](/mcp.md) - **Image prompts in assert**: The assert CLI / MCP tool now accepts images as prompt input, so you can assert against a reference image - **Bare init args in platform CLIs**: Platform CLIs simplify argument passing and now accept platform Agent constructor options directly - **Playwright fixture passes Agent options through**: `PlaywrightAiFixture` now forwards `PlaywrightAgent` constructor options, so you can customize the Agent while keeping the fixture ### Report System - **CLI report merging**: A new `report-tool merge` subcommand lets you combine multiple report files into one for centralized review - **Screenshot tool calls recorded in reports**: `take_screenshot` invocations now appear in reports, easing diagnosis of screenshot-related issues ### Chrome Extension - **Automated Chrome Web Store publishing**: The Chrome Web Store extension release pipeline is now fully automated, shortening release cycles ### Bug Fixes - Fixed `aiAct` completion being emitted before actions actually run - Fixed insight prompts prioritizing reference images over the current screenshot in some cases - Fixed Bridge attachment after new-tab navigation - Fixed Playground tap projection on iOS / HarmonyOS / Computer - Fixed HarmonyOS per-call `autoDismissKeyboard` - Fixed excessive Android Playground video streaming memory usage - Fixed Computer scroll default distance not matching Web - Fixed out-of-range bbox handling for models that return normalized `[0,1000]` coordinates - Fixed `aiAct` options not being inherited in Bridge mode - Fixed Action API return values diverging from the documented shape - Fixed `maxTokens` not aligning with intent model config - Fixed server port probing on a non-`0.0.0.0` host that did not match the actual listen host - Fixed `deepThink` dump flag being lost in reports - Fixed sporadic dropped characters when typing on iOS - Fixed unwanted HarmonyOS system action delay overrides ## v1.7 - Flexible Report File Consumption, with Qwen 3.6 Support ### Flexible Report File Consumption Starting in v1.7.0, you can extract raw screenshots and JSON data from report files, or convert reports into Markdown so other tools can continue consuming that content. ## Example You can parse a report file into a Markdown file like this: ```md # Act - Search for and play videos related to Midscene - Execution start: 2026-04-08T02:13:04.795Z - Task count: 21 ## 1. Plan - Click the top search box to activate input - Status: finished - Start: 2026-04-08T02:13:04.845Z - End: 2026-04-08T02:13:15.296Z - Cost(ms): 10451 - Screen size: 2880 x 1536 ![task-1](./screenshots/execution-1-task-1-f9fc3bf9-bdf6-48dd-abea-f8f29874d8c1.jpeg) ..... ``` You can then use the [Remotion Skill](https://www.remotion.dev/docs/ai/skills?utm_source=midscenejs) to parse that Markdown file and generate a customized replay video. The generated video looks like this: Midscene supports parsing report files through either the CLI or the JavaScript SDK. See: [Consume Report Files](/consume-report-file.md) ### Qwen 3.6 Model Support Added support for the Qwen 3.6 model, so you can use the latest Qwen model in Midscene. See: [Model Config](/model-config.md) ### Chrome Extension Recording Language Setting A new YAML output language option is available in the Chrome extension's recording settings, supporting English, Chinese, Japanese, and more. You can also set it to Auto to follow the system language. ### Android / HarmonyOS Improvements - Added `terminate` action on Android and HarmonyOS to force-stop apps, useful for resetting app state during testing. See: [Android API](/sdk/android.md), [HarmonyOS API](/sdk/harmonyos.md) - Fixed placeholder text unexpectedly retained when typing on X/Twitter on Android - Fixed Android Playground LAN access issues ### Debugging Improvements - Execution logs can now be saved to disk for post-hoc troubleshooting - Playground config page now supports running a connectivity test when saving model config, catching configuration errors early - Skill CLI `run` command now supports passing images as prompts via the `--image` flag ### Bug Fixes - Fixed unclear error messages when file chooser encounters missing files - Fixed incomplete error collection in CLI batch runner summary - Fixed `aiScroll` indentation formatting errors in YAML scripts - Fixed inaccurate `aiLocate` element bounding box - Fixed missing fallback when screenshot capture fails - Fixed incorrect handling of empty model responses in some cases - Fixed tab reuse issues in CDP connection mode - Fixed `aiQuery` result missing under certain data structures - Fixed AutoGLM app launch parameter format issue - Fixed dropdown display issues in Playground - Fixed custom request header aliases not working in model config ## v1.6 - CDP Connection, Pinch/Zoom & Multi-Model Enhancements v1.6 adds CDP browser connection mode, cross-platform pinch/zoom gestures, GPT-5/GPT-5.4 model support, along with improvements to element locating, report system, Chrome extension, and more. ### CDP Browser Connection Mode You can now connect to an existing browser instance via CDP (Chrome DevTools Protocol) for automation, without having Midscene launch a new browser. This is useful when you need to reuse an existing browser session. See: [Skills - Browser Automation](/skills.md), [YAML Script Runner - CDP Mode](/yaml-script-runner.md#use-cdp-connection-mode) ### Cross-Platform Pinch/Zoom Gestures Pinch/zoom gestures are now supported on Android, iOS, and HarmonyOS, enabling use cases like map zooming and image preview. See: [API Reference - aiPinch](/reference.md#agentaipinch) ### GPT-5 / GPT-5.4 & Codex App-Server Provider Support Added support for GPT-5, GPT-5.4 models and Codex app-server provider. You can now use the latest OpenAI models for visual understanding and automation. See: [Model Config](/model-config.md), [Model Strategy](/model-selection.md) ### Custom extraBody for Model Requests A new `extraBody` configuration allows you to pass additional custom parameters in model API requests, useful for specific model deployments or environments. See the [`MIDSCENE_MODEL_EXTRA_BODY_JSON` environment variable](/model-config.md#advanced-settings-optional) in Advanced Settings. ### `deepThink` Renamed to `deepLocate` The `deepThink` parameter in element-locating APIs has been renamed to `deepLocate` to better describe its "deep locate" purpose. The original `deepThink` parameter still works but we recommend migrating. See: [API Reference](/reference.md#common) ### Skill CLI & Platform Tool Enhancements - **Skill CLI Custom Interfaces**: Skill CLI now supports custom interfaces for more flexible Skill extensibility. See: [Skills](/skills.md) - **Unified MCP Tool Export**: All platform packages (Web, Android, iOS, etc.) now export MidsceneTools uniformly, making MCP integration simpler. See: [MCP](/mcp.md) - **iOS App Termination by bundleId**: You can now terminate iOS apps by bundleId, making it easier to reset app state during testing. See: [iOS API Reference](/sdk/ios.md) - **CLI Version Display**: CLI now shows version info in health checks, helping you troubleshoot environment issues ### Task Cancellation Support `aiAct` now supports `AbortSignal`, allowing you to cancel operations mid-execution instead of waiting for them to complete. See: [API Reference - aiAct](/reference.md#agentaiact) ### Element Locating Optimization The `deepLocate` flow has been optimized for better efficiency and accuracy when locating elements in complex interfaces. ### Report & Playback Improvements - **Faster Large Report Loading**: Screenshots in reports are now lazy-loaded, significantly speeding up reports with many steps - **Mobile Reports with Device Shells**: Report playback now shows device shells, giving you a more realistic view of mobile automation - **More Precise Timing**: AI call and action execution timing in reports is now more precise, helping you identify performance bottlenecks ### Stability Improvements - AI planning now automatically retries once on intermittent parse failures, reducing test interruptions from network issues - Device health check now includes monitor detection, helping diagnose display issues in headless environments ### Chrome Extension Improvements - Fixed crash when generating scripts after stopping recording - Fixed lag during long recording sessions caused by message serialization performance - Bridge mode now has start/stop control buttons, and fixed connection drops during confirmation ### Bug Fixes - Fixed MCP server becoming a zombie process with 100% CPU usage in some cases - Fixed screenshots not retrying when page navigation is in progress - Fixed text input loss on Android in certain scenarios - Fixed `aiNumber` returning incorrect results for some formats - Fixed `aiScroll` throwing errors when called without arguments - Fixed AutoGLM back/home actions not working correctly across different platforms - Fixed report display issues when model names contain `/` - Fixed report player not resetting properly after playback completes - Fixed Deep Think toggle not reading environment variable configuration in Playground - Fixed cursor size displaying incorrectly in high-resolution device screenshots - Fixed Chrome launch path resolution failing on Linux - Fixed inaccurate element locating on pages with iframes - Fixed HarmonyOS screen info parsing errors at certain render resolutions - Fixed device orientation displaying incorrectly after canceling tasks in Playground ## v1.5 - HarmonyOS Support v1.5 adds HarmonyOS automation support, Qwen3.5 and doubao-seed 2.0 model support, along with multiple improvements to desktop automation, report system, Chrome extension, and more. ### HarmonyOS Automation Support New `@midscene/harmony` package officially supports HarmonyOS platform automation. Midscene's automation capabilities now extend from Web, Android, iOS, and Desktop to the HarmonyOS ecosystem. ### Qwen3.5 & doubao-seed 2.0 Model Support Added support for Qwen3.5 and doubao-seed 2.0 models, allowing developers to leverage newer models for better visual understanding. ### Generic Model Reasoning Configuration New `MIDSCENE_MODEL_REASONING_EFFORT` environment variable provides a generic model reasoning effort configuration, enabling developers to uniformly control reasoning behavior across different models. ### Desktop Automation Improvements - **Xvfb virtual display support**: Support Xvfb virtual display for headless Linux environments, enabling desktop automation on CI/CD servers without GUI - **Connection health check**: Added health check during desktop automation connection for improved reliability - **macOS input optimization**: All text input on macOS now uses clipboard to avoid IME issues - **Mouse control failure detection**: Automatically detects mouse control failure and warns about admin privilege requirements - **Stop execution optimization**: Checks destroyed state to abort screenshot operations promptly when stopping execution ### Screenshot & Display Optimization - **Custom screenshot shrink**: Support custom screenshot shrink ratio to optimize performance while maintaining recognition accuracy - **Android scalingRatio decoupling**: Decoupled scalingRatio from size() method for improved flexibility ### Report System Improvements - **More detailed timing**: Finer-grained timing information in reports helps developers analyze performance bottlenecks more precisely - **Directory mode support for mergeReports**: `mergeReports` now supports directory mode report files ### Chrome Extension Improvements - **Always decline option**: Chrome extension adds "always decline" option with confirm race condition fix - **Close Bridge server after CLI**: Bridge server automatically closes after CLI command completes, preventing lingering processes ### Bug Fixes - Fixed `z.preprocess` handling in input mode schema for correct form rendering - Fixed Android swipe parameter passing - Fixed web size calculation - Fixed `BASE_URL_FIX_SCRIPT` closing tag not recognized by HTML parser - Fixed undefined page guard in PlaywrightAgent/PuppeteerAgent constructors ## v1.4 - Skills: Let AI Assistants Control Your Devices v1.4 introduces Midscene Skills — a set of installable skill packs for AI assistants like Claude Code and OpenClaw, enabling them to directly control browsers, desktops, Android, and iOS devices. This release also includes a standalone desktop MCP service, independent CLI entry points for each platform package, enhanced AI planning, and more. ### Midscene Skills — Device Control Skills for AI Assistants Midscene Skills is a set of skill packs that can be installed into AI assistants like Claude Code and OpenClaw. Once installed, AI assistants can control browsers, desktops, Android, and iOS devices using natural language. Each platform package (`@midscene/android`, `@midscene/ios`, `@midscene/web`, etc.) now exposes an independent CLI entry point, which is the foundation that Skills is built upon. **Supported Platforms:** - Browser (Puppeteer headless mode) - Chrome Bridge (user's own desktop Chrome) - Desktop (macOS, Windows, Linux) - Android (via ADB) - iOS (via WebDriverAgent) See: [Midscene Skills](https://github.com/web-infra-dev/midscene-skills) ### Standalone Desktop Automation MCP Package New `@midscene/computer-mcp` package provides PC desktop automation as a standalone MCP service. Developers can use desktop automation capabilities directly in MCP-compatible tools like Cursor and Trae without additional integration. See docs: [PC Desktop Automation](/platforms/desktop.md) ### Chrome Extension MCP Background Connection The Chrome extension now supports background Bridge mode MCP connection, exposing the desktop browser as an MCP tool to AI assistants, further expanding the MCP ecosystem. ### AI Planning Enhancements - **New `deepLocate` option for `aiAct`**: Enable deep locating during action execution, improving element locating accuracy in complex interfaces - **Swipe vs DragAndDrop semantic distinction**: The model can now more precisely distinguish between swipe and drag-and-drop operations, reducing gesture planning errors - **LLM planning page navigation restrictions**: Prevents the model from generating unreasonable page navigation during planning, improving task execution stability - **AppleScript keyboard input on macOS**: Improved keyboard input stability and compatibility in desktop automation - **Cursor move action**: New cursor move action support ### YAML Scripts & File Upload Enhancements - **YAML `aiTap` supports `fileChooserAccept`**: Handle file upload dialogs directly in YAML scripts - **Directory upload support**: Web supports `webkitdirectory` type folder selection upload ### Chrome Extension Bridge Mode Caching Bridge mode now supports caching, reusing existing AI planning results to reduce repeated calls and improve debugging efficiency. ### Android Improvements - Optimized text input logic for improved input stability ### iOS Improvements - **Playground live screen stream**: iOS Playground now features live screen preview for real-time device monitoring during debugging. ## v1.3 - PC Desktop Automation Support v1.3 introduces brand new PC desktop automation capabilities, significantly improves Android screenshot performance, and brings multiple enhancements to report system and stability. ### New PC Desktop Automation Support Midscene now supports PC desktop automation on Windows, macOS, and Linux, driving native keyboard and mouse controls. Whether it's Electron, Qt, WPF, or native desktop applications, they can all be automated through the visual model approach. **Core Capabilities:** - **Mouse Operations**: click, double-click, right-click, mouse move, drag and drop - **Keyboard Input**: text input, key combinations (Cmd/Ctrl/Alt/Shift) - **Screenshots**: capture screenshots from any monitor - **Multi-monitor Support**: operate across multiple displays simultaneously **Usage Methods:** - Zero-code trial via Computer Playground - JavaScript SDK for scripting - YAML automation scripts and CLI tools - HTML report playback for all operation paths See documentation: [PC Desktop Automation](/platforms/desktop.md) ### Major Android Screenshot Performance Improvement With Scrcpy screenshot mode enabled, screenshot time drops from 500–2000ms to **100–200ms**, significantly improving Android automation response speed. This is particularly useful for remote device debugging and high frame rate scenarios. See documentation: [Scrcpy Screenshot Mode](/sdk/android.md#scrcpy) ### Deep Thinking Mode Enhancement The `aiAct` deep thinking (deepThink) mode now not only helps with element location but also optimizes overall task planning, achieving better execution results in complex forms and multi-step workflows. ### Report Experience Optimization - **Timeline Collapse**: New collapse toggle button for easier viewing of long task flows - **Time Unit Changed to Seconds**: More readable - **Step Sync Highlighting**: Sidebar step highlighting syncs in real-time with player playback - **Reduced Memory Usage**: Optimized report generation mechanism to effectively reduce runtime memory usage ### Mobile Platform Improvements #### Android - More stable special character and Unicode input - More relaxed app package name matching for Launch action (ignores case and spaces) - Auto-retry when screenshot anomalies occur on certain devices #### iOS - More relaxed Bundle ID matching (ignores case and spaces) ### Web Automation Improvements - Fixed issue where Puppeteer could hang when taking screenshots of inactive tabs - Fixed inaccurate window size in headed mode - `shareBrowserContext` mode now supports preserving localStorage and sessionStorage - Playwright multi-project configuration automatically distinguishes test cases by browser in reports - Fixed `typeOnly` mode not working in YAML script input actions ### Other Improvements - Image processing performance improved - SVG icon cache issue fixed - Playground now displays specific reasons for model configuration errors ## v1.2 - Zhipu AI Open-Source Model Support and File Upload Support v1.2 introduces support for Zhipu AI open-source models, adds file upload functionality, and fixes several issues affecting user experience, making automated testing more reliable. ### New Zhipu AI Open-Source Model Support #### Zhipu GLM-V Vision Model - Zhipu GLM-V series models are open-source vision models launched by Zhipu AI, available in multiple parameter versions, supporting both cloud deployment and local deployment. - See: [GLM-V Model Configuration](/model-api-setup.md#glm-v) #### Zhipu AutoGLM Mobile Automation Model - Zhipu AutoGLM is an open-source mobile automation model launched by Zhipu AI. It can understand mobile screen content based on natural language instructions, and combined with intelligent planning capabilities, generate operation processes to complete user needs. - See: [AutoGLM Model Configuration](/model-api-setup.md#auto-glm) ### File upload feature File upload is a common requirement in Web automation scenarios. v1.2 adds file upload capability for the web, supporting natural language operations for file input boxes, making form automation more complete. See: [aiTap file upload](/reference.md#agentaitap) ### Cache mechanism optimization Fixed the issue where cache wasn't updated after DOM changes. When page DOM changes cause cache validation to fail, the system now automatically updates the cache, avoiding operation failures due to stale cache and improving automation script stability. ### Report and Playground improvements #### Deep thinking tag optimization - Fixed the issue where deepThink tags weren't displayed correctly in reports when using `.aiAct()` method with deep thinking. Now you can clearly see which operations used deep thinking capability in reports - Improved the style of summary rows in reports for better readability #### Playground stability improvements - Fixed the issue where Playground didn't properly create agent instances in `getActionSpace` when using agentFactory mode, ensuring normal operation across various usage modes - Optimized Playground output display to prevent overly long reportHTML content from affecting the interface ### Model configuration updates Updated configuration parameters for Qwen model's deep thinking functionality to ensure compatibility with the latest model version. ## v1.1 - `aiAct` deep thinking and extensible MCP SDK v1.1 optimizes model planning capabilities and MCP extensibility, making automation more stable in complex scenarios while providing more flexible solutions for enterprise MCP service deployments. ### `aiAct` can enable deep thinking (deepThink) When deep thinking is enabled in `aiAct`, the model will interpret intent more thoroughly and optimize its planning results. This is suited for complex forms, multi-step flows, and similar scenarios. It improves accuracy but increases planning latency. Currently supported: Qwen3-vl on Alibaba Cloud and Doubao-vision on Volcano Engine. See [Model strategy](/model-selection.md) for details. Example usage: ```typescript await agent.aiAct('If the UI shows an "Add shipping address" button, expand the existing "Shipping address" list and select the last item', { deepThink: true }); ``` ### MCP extension and SDK exposure Developers can use the MCP SDK exposed by Midscene to flexibly deploy a public MCP service. This capability applies to Agent instances on any platform. Typical application scenarios: - Run MCP in enterprise intranet to control private device pools - Package Midscene capabilities as internal microservices for multiple teams - Extend custom automation toolchains See documentation: [MCP Services](/mcp.md) ### Chrome extension improvements - Fixed potential event loss during recording, improving recording stability - Optimized coordinate passing in `describeElement` for better element description accuracy ### CLI and configuration enhancements - **File parameter support**: Fixed CLI issue where `--files` parameter wasn't properly handled when `--config` was specified; now they can be flexibly combined - **Dynamic configuration**: Fixed Playground not reading the `MIDSCENE_REPLANNING_CYCLE_LIMIT` environment variable properly ### iOS Agent compatibility improvements - Optimized `getWindowSize` method to automatically fall back to legacy endpoint when newer API is unavailable, improving compatibility with WebDriverAgent versions ### Report and Playground improvements - Fixed issue where report wasn't properly initialized before accessing screen properties - Fixed abnormal behavior of stop function in Playground - Improved error handling during video export to avoid crashes caused by frame cancel Thanks to contributors: @FriedRiceNoodles ## v1.0 - Midscene v1.0 is here! Midscene v1.0 is here! Try it out today and see how it can help you automate your workflows. ### See our new [Showcases](/showcases.md) page for real-world examples Register the GitHub form autonomously in a web browser and pass all field validations: Plus these real-world showcases: - [iOS Automation - Meituan coffee order](/showcases.md#ios) - [iOS Automation - Auto-like the first @midscene_ai tweet](/showcases.md#ios) - [Android Automation - DCar: Xiaomi SU7 specs](/showcases.md#android) - [Android Automation - Booking a hotel for Christmas](/showcases.md#android) - [MCP Integration - Midscene MCP UI prepatch release](/showcases.md) Some community developers have successfully built on Midscene's capability to [integrate with any interface](/integrate-with-any-interface.md), extending it with a robotic arm plus vision and voice models for in-vehicle large-screen testing scenarios. See the video below. ### 🚀 Pure vision path Starting in v1.0, Midscene fully adopts a visual-understanding approach to deliver more stable UI automation. Visual models provide: - **Stable results**: Leading vision models (Doubao Seed 1.6, Qwen3-VL, etc.) are reliable enough for most production needs - **UI workflow planning**: Vision models generally excel at planning UI flows and can handle many complex task sequences - **Works everywhere**: Automation no longer depends on the rendering stack—Android, iOS, desktop apps, or a browser `<canvas>`: if you can capture a screenshot, Midscene can interact with it - **Developer-friendly**: Dropping selectors and DOM keeps prompts simpler; teammates unfamiliar with rendering tech can become productive quickly - **Far fewer tokens**: Removing DOM extraction cuts token usage by about 80%, lowering cost and speeding up local runs - **Open-source options**: Open-source vision models like Qwen3-VL 8B/30B perform well, enabling self-hosted deployments See our updated [Model strategy](/model-selection.md) for details. ### 🚀 Better results by multiple model combinations Beyond the default interaction intent, Midscene defines Planning and Insight intents, and developers can enable dedicated models for each. For example, you can use a GPT model for planning while using the default Qwen3-VL model for element localization. Multi-model combinations let you scale up handling of complex requirements as needed. ### 🚀 Runtime architecture optimization - Reuse portions of context to reduce device-info calls and improve runtime performance - Optimize Action Space combinations for Web and mobile environments to provide models with a more useful toolset ### 🚀 Report improvements - Parameter view: mark interaction parameter locations, merge screenshot context, and identify model planning results faster - Style updates: dark mode report rendering for better readability - Token usage display: summarize token consumption by model to analyze cost across scenarios ### 🚀 MCP architecture redesign We redefined Midscene MCP services around vision-driven UI operations. Each Action in the iOS / Android / Web Action Space is exposed as an MCP tool, providing atomic operations so developers can focus on higher-level Agents without worrying about UI operation details, while keeping success rates high. See [MCP architecture](/mcp.md). ### 🚀 Mobile automation #### iOS improvements - Added compatibility across WebDriverAgent 5.x–7.x - Added WebDriver Clear API support to solve dynamic input field issues - Improved device compatibility #### Android improvements - Added screenshot polling fallback to improve remote device stability - Added automatic screen-orientation adaptation (displayId screenshots) - Added YAML script support for `runAdbShell` #### Cross-platform - Expose system operation helpers on the Agent instance, including Home, Back, RecentApp, and more ### 🚧 API changes Method renames (backward compatible) - Renamed `aiAction()` → `aiAct()` (old method kept with deprecation warning) - Renamed `logScreenshot()` → `recordToReport()` (old method kept with deprecation warning) Environment variable renames (backward compatible) - Renamed `OPENAI_API_KEY` → `MIDSCENE_MODEL_API_KEY` (new variable preferred, old variable as fallback) - Renamed `OPENAI_BASE_URL` → `MIDSCENE_MODEL_BASE_URL` (new variable preferred, old variable as fallback) ### ⬆️ Upgrade to the latest version Upgrade only the packages you use. For example: `npm install @midscene/web@latest` `npm install @midscene/android@latest` `npm install @midscene/ios@latest` If you use the CLI installed globally: `npm i -g @midscene/cli` ## v0.30 - Cache management upgrade and mobile experience optimization ### More flexible cache strategy v0.30 improves the cache system, allowing you to control cache behavior based on actual needs: - **Multiple cache modes available**: Supports read-only, write-only, and read-write strategies. For example, use read-only mode in CI environments to reuse cache, and use write-only mode in local development to update cache - **Automatic cleanup of unused cache**: Agent can automatically clean up unused cache records when destroyed, preventing cache files from accumulating - **Simplified unified configuration**: Cache configuration parameters for CLI and Agent are now unified, no need to remember different configurations ### Report management convenience - **Support for merging multiple reports**: In addition to playwright scenarios, all scenarios now support merging multiple automation execution reports into a single file for centralized viewing and sharing of test results ### Mobile automation optimization #### iOS platform improvements - **Real device support improvement**: Removed simctl check restriction, making iOS real device automation smoother - **Auto-adapt device display**: Implemented automatic device pixel ratio detection, ensuring accurate element positioning on different iOS devices #### Android platform enhancements - **Flexible screenshot optimization**: Added `screenshotResizeRatio` option, allowing you to customize screenshot size while ensuring visual recognition accuracy, reducing network transmission and storage overhead - **Screen info cache control**: Use `alwaysRefreshScreenInfo` option to control whether to fetch screen information each time, allowing cache reuse in stable environments to improve performance - **Direct ADB command execution**: AndroidAgent added `runAdbCommand` method for convenient execution of custom device control commands #### Cross-platform consistency - **ClearInput support on all platforms**: Solves the problem of AI being unable to accurately plan clear input operations across platforms ### Feature enhancements - **Failure classification**: CLI execution results can now distinguish between "skipped failures" and "actual failures", helping locate issue causes - **aiInput append mode**: Added `append` option to append input while preserving existing content, suitable for editing scenarios - **Chrome extension improvements**: - Popup mode preference saved to localStorage, remembering your choice on next open - Bridge mode supports auto-connect, reducing manual operations - Support for GPT-4o and non-visual language models ### Type safety improvements - **Zod schema validation**: Introduced type checking for action parameters, detecting parameter errors during development to avoid runtime issues - **Number type support**: Fixed `aiInput` support for number type values, making type handling more robust ### Bug fixes - Fixed potential issues caused by Playwright circular dependencies - Fixed issue where `aiWaitFor` as the first statement could not generate reports - Improved video recorder delay logic to ensure the last frame is captured - Optimized report display logic to view both error information and element positioning information simultaneously - Fixed issue where `cacheable` option in `aiAction` subtasks was not properly passed ### Community - Awesome Midscene section added [midscene-java](/awesome-midscene.md) community project ## v0.29 - iOS platform support added ### iOS platform support added The biggest highlight of v0.29 is the official introduction of iOS platform support! Now you can connect and automate iOS devices through WebDriver, extending Midscene's powerful AI automation capabilities to the Apple ecosystem, details: [Support iOS automation](/platforms/ios.md). ### Qwen3-VL model adaptation We've adapted the latest Qwen `Qwen3-VL` model, giving developers faster and more accurate visual understanding capabilities. See [Model strategy](/model-selection.md). ### AI core capability enhancement - **UI-TARS Model Performance Optimization**: Optimized aiAct planning, improved dialogue history management, and provided better context awareness capabilities - **AI Assertion and Action Optimization**: We updated the prompt for `aiAssert` and optimized the internal implementation of `aiAct`, making AI-driven assertions and action execution more precise and reliable ### Reporting and debugging experience optimization - **URL Parameter Playback Control**: To improve debugging experience, you can now directly control the default behavior of report playback through URL parameters ### Documentation - Updated documentation deployment cache strategy to ensure users can access the latest documentation content in time ## v0.28 - Build your own GUI automation agent by integrating with your own interface (preview feature) ### Support for integration with any interface (preview feature) v0.28 introduces the capability to integrate with your own interface. Define an interface controller class that conforms to the `AbstractInterface` definition, and you can get a fully-featured Midscene Agent. The typical use case for this feature is to build a GUI automation Agent for your own interface, such as IoT devices, in-house applications, car displays, etc.! Combined with the universal Playground architecture and SDK enhancement features, developers can conveniently debug custom devices. For more information, please refer to [Integrate with Any Interface (Preview Feature)](/integrate-with-any-interface.md) ### Android platform optimization - **Planning Cache Support**: Added planning cache functionality for Android platform, improving execution efficiency - **Input Strategy Enhancement**: Optimized input clearing strategy based on IME settings, improving Android platform input experience - **Scroll Calculation Improvement**: Optimized scroll endpoint calculation algorithm for Android platform ### Gesture operation extension - **Double-Click Operation Support**: Added support for double-click actions - **Long Press and Swipe Gestures**: Added support for long press and swipe gestures ### Core function enhancement - **Agent Configuration Isolation**: Implemented model configuration isolation between different agents, avoiding configuration conflicts - **Execution Option Extension**: Added useCache and replanningCycleLimit configuration options for Agent, providing more fine-grained control - **YAML Script Support**: Support for running universal custom devices through YAML scripts, enhancing automation capabilities ### Bug fixes - Fixed Qwen model search region size issues - Optimized deepThink parameter handling and rectangle size calculation - Resolved issues related to Playwright double-click operations - Improved TEXT action type processing logic ### Documentation and community - Added custom interface documentation to help developers better extend functionality - Added [Awesome Midscene](/awesome-midscene.md) section in README to showcase community projects ## v0.27 - Core module refactoring, assertions and reports functionally enhanced ### Core module refactoring Based on the introduction of [Rslib](https://github.com/web-infra-dev/rslib) in v0.26 to improve development experience and reduce contribution thresholds, v0.27 takes it a step further by refactoring the core modules on a large scale. This makes it extremely easy to extend new devices and add new AI operations, and we sincerely welcome community developers to contribute! **Due to the wide scope of this refactoring, please feel free to report any issues you encounter after upgrading, and we will address them promptly.** ### API enhancement - **`aiAssert` Functionally Enhanced** - New `name` field allows naming different assertion tasks, making it easier to identify and parse in JSON output results - New `domIncluded` and `screenshotIncluded` options allow flexible control over whether to send DOM snapshots and page screenshots to AI ### Chrome extension playground upgrade - All Agent APIs can be directly debugged and run in the Playground! Interactive, extraction, and verification cover three major categories of methods, with visual operations and verification that boost your automation development efficiency! Come experience the truly versatile AI automation platform! 🚀 ### Report function optimization - **New Marking Layer Switch**: The report player has added a switch to hide the marking layer, allowing users to view the original page view without obstruction when playing back. ### Bug fixes - Fixed the problem that `aiWaitFor` sometimes caused the report to not be generated - Reduced memory consumption of Playwright plugin ## v0.26 - Toolchain fully integrated [Rslib](https://github.com/web-infra-dev/rslib), greatly improving development experience and reducing contribution threshold ### Web integration optimization - Support freezing page context([freezePageContext](/reference.md#agentfreezepagecontext)/[unfreezePageContext](/reference.md#agentunfreezepagecontext)), so that all subsequent operations reuse the same page snapshot, avoiding repeated page status acquisition - Add all agent APIs to Playwright fixture, simplify test script writing, and solve the problem of not generating reports when using agentForPage ### Android automation enhancement - New keyboard hiding strategy([keyboardDismissStrategy](/sdk/android.md#androiddevice)), allowing you to specify the way to automatically hide the keyboard ### Report function optimization - Report content lazy parsing, solving the problem of report crash when the report is large - Report player adds automatic zoom switch, making it easier to view the global perspective playback - Support aiAssert / aiQuery tasks in report playback, to fully show the entire page change process - Fix the problem that the sidebar status is not displayed as a failure icon when the assertion fails - Fix the problem that the drop-down filter in the report cannot be switched ### Build and engineering - Build tool migration to [Rslib](https://github.com/web-infra-dev/rslib) library development tool, improving build efficiency and development experience - Full repository source code jump, making it easier for developers to view source code - MCP npm package product volume optimization, from 56M to 30M, greatly improving loading speed ### Bug fixes - CLI automatically opens headed mode when keepWindow is true - Fix the implementation problem of getGlobalConfig, solve the problem of abnormal environment variable initialization - Ensure that the mime-type in base64 encoding is correct - Fix the return value type of aiAssert task ## v0.25 - Support using images as AI prompt input ### Core function enhancement - New worker runtime support, support running in worker environment - Support using images as AI prompt input, see [Prompting with images](/reference.md#prompting-with-images) - Image processing upgrade, using Photon & Sharp for efficient image cropping ### Web integration optimization - Get XPath by coordinates, improve cache reproducibility - Cache file moves plan module to the front, improving readability - Chrome Recorder supports exporting all events to markdown documents - agent supports specifying HTML report name, see [reportFileName](/reference.md#common) ### Android automation enhancement - Long press gesture support - Pull-to-refresh support ### Bug fixes - Use global config to handle environment variables, avoid issues caused by multiple packaging - Manually construct error information when error object serialization fails - Fix playwright report type dependency declaration order issue - Fix MCP packaging issue ### Documentation AI-friendly - [LLMs.txt](/llm-txt.md) is now available in both Chinese and English, making it easier for AI to understand - Each document now has a copy-to-markdown button, making it easier to feed to AI ### Other function enhancement - Chrome Recorder supports aiScroll function - Refactor aiAssert to be consistent with aiBoolean ## v0.24 - MCP for Android automation ### MCP for Android automation - You can now use Midscene MCP to automate Android apps, just like you use it for web apps. Read more: [MCP for Android Automation](/mcp.md) ### Optimization - For Mac platform Puppeteer, a double input clearing mechanism has been added to ensure that the input box is cleared before input ### Development experience - Simplify the way to build `htmlElement.js` to avoid report template build issues caused by circular dependencies - Optimize development workflow, just use `npm run dev` to enter midscene project development ## v0.23 - New report style and YAML script ability enhancement ### Report system upgrade #### New report style - New report style design, providing clearer and more beautiful test result display - Optimize report layout and visual effects, improve user reading experience - Enhance report readability and information hierarchy structure ![](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/new%20report.png) ### YAML script ability enhancement #### Support multiple YAML files batch execution - New config mode support, support configure Yaml file running order, browser reuse strategy, parallelism - Support getting JSON format running results ![](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/Tuji_20250722_161353.338.png) ### Test coverage enhancement #### Android test enhancement - New Android platform related test cases, improve code quality and stability - Improve test coverage, ensure the reliability of Android features ## v0.22- Chrome extension recording function released ### Web integration enhancement #### New recording function - Chrome extension adds recording function, which can record user operations on the page and generate automation scripts - Support recording click, input, scroll and other common operations, greatly reducing the threshold for writing automation scripts - The recorded operations can be directly played back and debugged in the Playground #### Upgrade to IndexedDB for storage - Chrome extension's Playground and Bridge now use IndexedDB for data storage - Compared to the previous storage scheme, it provides larger storage capacity and better performance - Support storing more complex data structures, laying the foundation for future feature extensions #### Customize replanning cycle limit - Set the `MIDSCENE_REPLANNING_CYCLE_LIMIT` environment variable to customize the maximum number of re-planning cycles allowed when executing operations (aiAct). - The default value is 10. When the AI needs to re-plan more than this limit, an error will be thrown and suggest splitting the task. - Provide more flexible task execution control, adapting to different automation scenarios ```bash export MIDSCENE_REPLANNING_CYCLE_LIMIT=10 # default value is 10 ``` ### Android interaction optimization #### New screenshot path generation - Generate a unique file path for each screenshot to avoid file overwrite issues - Improve stability in concurrent test scenarios ## v0.21 - Chrome extension UI upgrade ### Web integration enhancement #### New chat-style user interface - New chat-style user interface design for better user experience #### Flexible timeout configuration - Supports overriding timeout settings from test fixture, providing more flexible timeout control - Applicable scenarios: Different test cases require different timeout settings #### Unified Puppeteer and Playwright configuration - New `waitForNavigationTimeout` and `waitForNetworkIdleTimeout` parameters for Playwright - Unified timeout options configuration for Puppeteer and Playwright, providing consistent API experience, reducing learning costs #### New data export callback mechanism - New `agent.onDumpUpdate` callback function, can get real-time notification when data is exported - Refactored the post-task processing flow to ensure the correct execution of asynchronous operations - Applicable scenarios: Monitoring or processing exported data ### Android interaction optimization #### Input experience improvement - Changed click input to slide operation, improving interaction response and stability - Reduced operation failures caused by inaccurate clicks ## v0.20 - Support for assigning XPath to locate elements ### Web integration enhancement #### New `aiAsk` method - Allows direct questioning of the AI model to obtain string-formatted answers for the current page. - Applicable scenarios: Tasks requiring AI reasoning such as Q\&A on page content and information extraction. - Example: ```typescript await agent.aiAsk('any question') ``` #### Support for passing XPath to locate elements - Location priority: Specified XPath > Cache > AI model location. - Applicable scenarios: When the XPath of an element is known and the AI model location needs to be skipped. - Example: ```typescript await agent.aiTap('submit button', { xpath: '//button[@id="submit"]' }) ``` ### Android improvement #### Playground tasks can be cancelled - Supports interrupting ongoing automation tasks to improve debugging efficiency. #### Enhanced `aiLocate` API - Returns the Device Pixel Ratio, which is commonly used to calculate the real coordinates of elements. ### Report generation optimization Improve report generation mechanism, from batch storage to single append, effectively reducing memory usage and avoiding memory overflow when the number of test cases is large. ## v0.19 - Support for getting complete execution process data ### New API for getting Midscene execution process data Add the `_unstableLogContent` API to the agent. Get the execution process data of Midscene, including the time of each step, the AI tokens consumed, and the screenshot. The report is generated based on this data, which means you can customize your own report using this data. Read more: [API documentation](/reference.md#agent_unstablelogcontent) ### CLI support for adjusting Midscene env variable priority By default, `dotenv` does not override the global environment variables in the `.env` file. If you want to override, you can use the `--dotenv-override` option. Read more: [YAML script runner](/yaml-script-runner.md#configure-environment-variables-with-env) ### Reduce report file size Reduce the size of the generated report by trimming redundant data, significantly reducing the report file size for complex pages. The typical report file size for complex pages has been reduced from 47.6M to 15.6M! ## v0.18 - Enhanced reporting features 🚀 Midscene has another update! It makes your testing and automation processes even more powerful: ### Custom node in report - Add the `recordToReport` API to the agent. Take a screenshot of the current page as a report node, and support setting the node title and description to make the automated testing process more intuitive. Applicable for capturing screenshots of key steps, error status capture, UI validation, etc. - Example: ```javascript test('login github', async ({ ai, aiAssert, aiInput, recordToReport }) => { if (CACHE_TIME_OUT) { test.setTimeout(200 * 1000); } await ai('Click the "Sign in" button'); await aiInput('quanru', 'username'); await aiInput('123456', 'password'); // log by your own await recordToReport('Login page', { content: 'Username is quanru, password is 123456', }); await ai('Click the "Sign in" button'); await aiAssert('Login success'); }); ``` ### Support for downloading reports as videos - Support direct video download from the report player, just by clicking the download button on the player interface. ![](/images/blog/export-video.png) - Applicable scenarios: Share test results, archive reproduction steps, and demonstrate problem reproduction. ### More Android configurations exposed - Optimize input interactions in Android apps and allow connecting to remote Android devices - `autoDismissKeyboard?: boolean` - Optional parameter. Whether to automatically dismiss the keyboard after entering text. The default value is true. - `androidAdbPath?: string` - Optional parameter. Used to specify the path of the adb executable file. - `remoteAdbHost?: string` - Optional parameter. Used to specify the remote adb host. - `remoteAdbPort?: number` - Optional parameter. Used to specify the remote adb port. - Examples: ```typescript await agent.aiInput('Search Box', 'Test Content', { autoDismissKeyboard: true }) ``` ```typescript const agent = await agentFromAdbDevice('s4ey59', { autoDismissKeyboard: false, // Optional parameter. Whether to automatically dismiss the keyboard after entering text. The default value is true. androidAdbPath: '/usr/bin/adb', // Optional parameter. Used to specify the path of the adb executable file. remoteAdbHost: '192.168.10.1', // Optional parameter. Used to specify the remote adb host. remoteAdbPort: '5037' // Optional parameter. Used to specify the remote adb port. }) ``` Upgrade now to experience these powerful new features! - [Custom Report Node API documentation](/reference/index.md#log-screenshot) - [API documentation for more Android configuration items](/sdk/android.md#androiddevice) ## v0.17 - Let AI see the DOM of the page ### Data query API enhanced To meet more automation and data extraction scenarios, the following APIs have been enhanced with the `options` parameter, supporting more flexible DOM information and screenshots: - `agent.aiQuery(dataDemand, options)` - `agent.aiBoolean(prompt, options)` - `agent.aiNumber(prompt, options)` - `agent.aiString(prompt, options)` #### New `options` parameter - `domIncluded`: Whether to pass the simplified DOM information to AI model, default is off. This is useful for extracting attributes that are not visible on the page, like image links. - `screenshotIncluded`: Whether to pass the screenshot to AI model, default is on. #### Code example ```typescript // Extract all contact information (including hidden avatarUrl attributes) const contactsData = await agent.aiQuery( "{name: string, id: number, company: string, department: string, avatarUrl: string}[], extract all contact information including hidden avatarUrl attributes", { domIncluded: true } ); // Check if the id attribute of the first contact is 1 const isId1 = await agent.aiBoolean( "Is the first contact's id is 1?", { domIncluded: true } ); // Get the ID of the first contact (hidden attribute) const firstContactId = await agent.aiNumber("First contact's id?", { domIncluded: true }); // Get the avatar URL of the first contact (invisible attribute on the page) const avatarUrl = await agent.aiString( "What is the Avatar URL of the first contact?", { domIncluded: true } ); ``` ### New right-click ability Have you ever encountered a scenario where you need to automate a right-click operation? Now, Midscene supports a new `agent.aiRightClick()` method! #### Function Perform a right-click operation on the specified element, suitable for scenarios where right-click events are customized on web pages. Please note that Midscene cannot interact with the browser's native context menu after right-click. #### Parameter description - `locate`: Describe the element you want to operate in natural language - `options`: Optional, supports `deepThink` (AI fine-grained positioning) and `cacheable` (result caching) #### Example ```typescript // Right-click on a contact in the contacts application, triggering a custom context menu await agent.aiRightClick("Alice Johnson"); // Then you can click on the options in the menu await agent.aiTap("Copy Info"); // Copy contact information to the clipboard ``` ### A complete example In this report file, we show a complete example of using the new `aiRightClick` API and new query parameters to extract contact data including hidden attributes. Report file: [puppeteer-2025-06-04_20-34-48-zyh4ry4e.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/puppeteer-2025-06-04_20-34-48-zyh4ry4e.html) The corresponding code can be found in our example repository: [puppeteer-demo/extract-data.ts](https://github.com/web-infra-dev/midscene-example/blob/main/puppeteer-demo/extract-data.ts) ### Refactor cache Use xpath cache instead of coordinates, improve cache hit rate. Refactor cache file format from json to yaml, improve readability. ## v0.16 - Support MCP ### Midscene MCP 🤖 Use Cursor / Trae to help write test cases. 🕹️ Quickly implement browser operations akin to the Manus platform. 🔧 Integrate Midscene capabilities swiftly into your platforms and tools. Read more: [MCP](/mcp.md) ### Support structured API for agent APIs: `aiBoolean`, `aiNumber`, `aiString`, `aiLocate` Read more: [Use JavaScript to Optimize the AI Automation Code](/basics.md#javascript-orchestration) ## v0.15 - Android automation unlocked! ### Android automation unlocked! 🤖 AI Playground: natural‑language debugging 📱 Supports native, Lynx & WebView apps 🔁 Replayable runs 🛠️ YAML or JS SDK ⚡ Auto‑planning & Instant Actions APIs Read more: [Android automation](/platforms/android.md) ### More features - Allow custom midscene_run dir - Enhance report filename generation with unique identifiers and support split mode - Enhance timeout configurations and logging for network idle and navigation - Adapt for gemini-2.5-pro ## v0.14 - Instant actions "Instant Actions" introduces new atomic APIs, enhancing the accuracy of AI operations. Read more: [Instant Actions](/blog-introducing-instant-actions-and-deep-think.md) ## v0.13 - DeepThink mode ### Atomic AI interaction methods - Supports aiTap, aiInput, aiHover, aiScroll, and aiKeyboardPress for precise AI actions. ### DeepThink mode - Enhances click accuracy with deeper contextual understanding. ![](/images/blog/0.13.0.jpeg) ## v0.12 - Integrate Qwen 2.5 VL ### Integrate Qwen 2.5 VL's native capabilities - Keeps output accuracy. - Supports more element interactions. - Cuts operating cost by over 80%. ## v0.11.0 - UI-TARS model caching ### UI-TARS model support caching - Enable caching by document 👉 : [Enable Caching](/caching.md) - Enable effect ![](/images/blog/0.11.0.png) ### Optimize DOM tree extraction strategy - Optimize the information ability of the dom tree, accelerate the inference process of models like GPT 4o ![](/images/blog/0.11.0-2.png) ## v0.10.0 - UI-TARS model released UI-TARS is a Native GUI agent model released by the **Seed** team. It is named after the [TARS robot](https://interstellarfilm.fandom.com/wiki/TARS) in the movie [Star Trek](https://en.wikipedia.org/wiki/Star_Trek), which has high intelligence and autonomous thinking capabilities. UI-TARS **takes images and human instructions as input information**, can correctly perceive the next action, and gradually approach the goal of human instructions, leading to the best performance in various benchmark tests of GUI automation tasks compared to open-source and closed-source commercial models. ![](/images/blog/0.10.0.png) UI-TARS: Pioneering Automated GUI Interaction with Native Agents - Figure 1 ![](/images/blog/0.10.0-2.png) UI-TARS: Pioneering Automated GUI Interaction with Native - Figure 4 ### Model advantage UI-TARS has the following advantages in GUI tasks: - **Target-driven** - **Fast inference speed** - **Native GUI agent model** - **Private deployment without data security issues** ## v0.9.0 - Bridge mode released With the Midscene browser extension, you can now use scripts to link with the desktop browser for automated operations! We call it "Bridge Mode". Compared to previous CI environment debugging, the advantages are: 1. You can reuse the desktop browser, especially Cookie, login state, and front-end interface state, and start automation without worrying about environment setup. 2. Support manual and script cooperation to improve the flexibility of automation tools. 3. Simple business regression, just run it locally with Bridge Mode. ![](/images/blog/0.9.0.png) Documentation: [Use Chrome Extension to Experience Midscene](/bridge-mode.md) ## v0.8.0 - Chrome extension ### New Chrome extension, run Midscene anywhere Through the Midscene browser extension, you can run Midscene on any page, without writing any code. Experience it now 👉: [Use Chrome Extension to Experience Midscene](/platforms/web.md#chrome-extension) ## v0.7.0 - Playground ability ### Playground ability, debug anytime Now you don't have to keep re-running scripts to debug prompts! On the new test report page, you can debug the AI execution results at any time, including page operations, page information extraction, and page assertions. ## v0.6.0 - Doubao model support ### Doubao model support - Support for calling Doubao models, reference the environment variables below to experience. ```bash MIDSCENE_OPENAI_INIT_CONFIG_JSON='{"baseURL":"https://xxx.net/api/v3","apiKey":"xxx"}' MIDSCENE_MODEL_NAME='ep-20240925111815-mpfz8' MIDSCENE_MODEL_TEXT_ONLY='true' ``` Summarize the availability of Doubao models: - Currently, Doubao only has pure text models, which means "seeing" is not available. In scenarios where pure text is used for reasoning, it performs well. - If the use case requires combining UI analysis, it is completely unusable Example: ✅ The price of a multi-meat grape (can be guessed from the order of the text on the interface) ✅ The language switch text button (can be guessed from the text content on the interface: Chinese, English text) ❌ The left-bottom play button (requires image understanding, failed) ### Support for GPT-4o structured output, cost reduction By using the gpt-4o-2024-08-06 model, Midscene now supports structured output (structured-output) features, ensuring enhanced stability and reduced costs by 40%+. Midscene now supports hitting GPT-4o prompt caching features, and the cost of AI calls will continue to decrease as the company's GPT platform is deployed. ### Test report: support animation playback Now you can view the animation playback of each step in the test report, quickly debug your running script ### Speed up: merge plan and locate operations, response speed increased by 30% In the new version, we have merged the Plan and Locate operations in the prompt execution to a certain extent, which increases the response speed of AI by 30%. > Before ![](/images/blog/0.6.0.png) > after ![](/images/blog/0.6.0-2.png) ### Test report: the accuracy of different models - GPT 4o series models, 100% correct rate - doubao-pro-4k pure text model, approaching usable state ![](/images/blog/0.6.0-3.png) ![](/images/blog/0.6.0-4.png) ### Problem fix - Optimize the page information extraction to avoid collecting obscured elements, improving success rate, speed, and AI call cost 🚀 > before ![](/images/blog/0.6.0-5.png) > after ![](/images/blog/0.6.0-6.png) ## v0.5.0 - Support GPT-4o structured output ### New features - Support for gpt-4o-2024-08-06 model to provide 100% JSON format limit, reducing Midscene task planning hallucination behavior ![](/images/blog/0.5.0.png) - Support for Playwright AI behavior real-time visualization, improve the efficiency of troubleshooting ![](/images/blog/0.5.0-2.png) - Cache generalization, cache capabilities are no longer limited to playwright, pagepass, puppeteer can also use cache ```diff - playwright test --config=playwright.config.ts # Enable cache + MIDSCENE_CACHE=true playwright test --config=playwright.config.ts ``` - Support for azure openAI - Support for AI to add, delete, and modify the existing input ### Problem fix - Optimize the page information extraction to avoid collecting obscured elements, improving success rate, speed, and AI call cost 🚀 - During the AI interaction process, unnecessary attribute fields were trimmed, reducing token consumption. - Optimize the AI interaction process to reduce the likelihood of hallucination in KeyboardPress and Input events - For pagepass, provide an optimization solution for the flickering behavior that occurs during the execution of Midscene ```javascript // Currently, pagepass relies on a too low version of puppeteer, which may cause the interface to flicker and the cursor to be lost. The following solution can be used to solve this problem const originScreenshot = puppeteerPage.screenshot; puppeteerPage.screenshot = async (options) => { return await originScreenshot.call(puppeteerPage, { ...options, captureBeyondViewport: false }); }; ``` ## v0.4.0 - Support CLI usage ### New features - Support for Cli usage, reducing the usage threshold of Midscene ```bash # Headed mode (visible browser) access baidu.com and search "weather" npx @midscene/cli --headed --url https://www.baidu.com --action "input 'weather', press enter" --sleep 3000 # Visit GitHub status page and save the status to ./status.json npx @midscene/cli --url https://www.githubstatus.com/ \ --query-output status.json \ --query '{serviceName: string, status: string}[], github page status, return service name' ``` - Support for AI to wait for a certain time to continue the subsequent task execution - Playwright AI task report shows the overall time and aggregates AI tasks by test group ### Problem fix - Optimize the AI interaction process to reduce the likelihood of hallucination in KeyboardPress and Input events ## v0.3.0 - Support AI report HTML ### New features - Generate html format AI report, aggregate AI tasks by test group, facilitate test report distribution ### Problem fix - Fix the problem of AI report scrolling preview ## v0.2.0 - Control Puppeteer by natural language ### New features - Support for using natural language to control puppeteer to implement page automation 🗣️💻 - Provide AI cache capabilities for playwright framework, improve stability and execution efficiency - AI report visualization, aggregate AI tasks by test group, facilitate test report distribution - Support for AI to assert the page, let AI judge whether the page meets certain conditions ## v0.1.0 - Control Playwright by natural language ### New features - Support for using natural language to control puppeteer to implement page automation 🗣️💻 - Support for using natural language to extract page information 🔍🗂️ - AI report visualization, AI behavior, AI thinking visualization 🛠️👀 - Direct use of GPT-4o model, no training required 🤖🔧 --- url: /chatgpt-subscription.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Use a ChatGPT subscription Authorize Midscene through [Sign in with ChatGPT (SIWC)](https://developers.openai.com/siwc/token-sharing-open-source/sign-in) to call GPT models using your ChatGPT subscription. This guide walks you through sign-in, configuration, and connection verification. A ChatGPT subscription and a [model API key](/model-api-setup.md) are two ways to connect Midscene. You can choose either based on your model payment plan. ## Quick start Choose the section for your environment. Both paths use `MIDSCENE_MODEL_AUTH_MODE="siwc"`, so Midscene reads the saved credentials and refreshes access tokens automatically. Available models depend on your ChatGPT account. The examples below use `gpt-6-sol`. GPT model families and usage notes are the same as when [using a model API key](/model-api-setup.md#gpt). ### Browser extension 1. In the Midscene sidebar, click the settings icon to open the model configuration dialog, then click **Use your ChatGPT plan** and follow the on-screen instructions to sign in and authorize plan usage. 2. Paste the following configuration into the same dialog: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` 3. Click **Verify** to test the connection. For failed checks, see [Model advanced configuration and debugging](/model-config.md#verify-model-connectivity). ### CLI / SDK First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Next, add the following configuration to your `.env` file. See the [model configuration guide](/model-api-setup.md) for how to load it into your runtime. ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Finally, run this command in the directory containing your `.env` file: ```bash pnpm dlx @midscene/cli model verify ``` This command uses values from `.env` to override variables with the same names in the current shell. For failed checks, see [Model advanced configuration and debugging](/model-config.md#verify-model-connectivity). ## Usage and credentials - SIWC consumes your subscription usage. ChatGPT determines how token consumption translates into plan usage. Midscene reports show token consumption for each task step. - CLI credentials are saved to `~/.midscene/siwc.json`; extension credentials are saved in the extension's local storage. Midscene does not collect your credentials. - With `MIDSCENE_MODEL_AUTH_MODE="siwc"`, Midscene automatically refreshes access tokens at runtime, so you do not need to manage them manually. This is supported in both Node.js and the browser extension. If refreshing fails, authorize again. - The model proxy environment variables `MIDSCENE_MODEL_HTTP_PROXY` and `MIDSCENE_MODEL_SOCKS_PROXY` also apply to SIWC sign-in and token refresh. - The CLI and browser extension store credentials independently. Refreshing tokens from the command line does not update the browser extension's credentials. - Follow OpenAI's regional restrictions and terms of use. See the [Sign in with ChatGPT Terms](https://openai.com/policies/sign-in-with-chatgpt-terms/). ## Advanced: manage access tokens manually Use this path if you prefer to manage tokens yourself. Do not set `MIDSCENE_MODEL_AUTH_MODE="siwc"` in this case. ### Get and configure an access token Run the login command and complete authorization in your browser: ```bash pnpm dlx @midscene/cli model siwc login ``` The command saves credentials to `~/.midscene/siwc.json` and prints an access token and its expiration time. Replace `<your-access-token>` below with that token: **ChatGPT subscription (SIWC)** ```bash MIDSCENE_MODEL_BASE_URL="https://api.openai.com/v1" MIDSCENE_MODEL_API_KEY="<your-access-token>" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" MIDSCENE_MODEL_PROTOCOL="openai-responses" # SIWC requires the Responses API MIDSCENE_MODEL_STREAM_MODE="stream" # SIWC requires streaming ``` SIWC requires the Responses API with streaming enabled. Keep the `openai-responses` and `stream` settings in the example. Midscene handles these settings automatically when using SIWC authentication in the quick start. Load this configuration into your runtime following the [model configuration guide](/model-api-setup.md), or paste it into the extension's model configuration dialog. Verify the connection with `pnpm dlx @midscene/cli model verify` from the directory containing your `.env` file, or click **Verify** in the extension. ### Refresh the access token According to OpenAI's documentation, access tokens expire after one hour. A refresh token is needed to obtain a new access token. See the [OpenAI token reference](https://developers.openai.com/siwc/token-sharing-open-source/token-reference). Run the following command to refresh the token: ```bash pnpm dlx @midscene/cli model siwc refresh ``` The command updates the local credentials and prints a new access token. Replace `MIDSCENE_MODEL_API_KEY` with the new token and reload the configuration. If you pasted the token into the extension, update its configuration too. ## Legacy: reuse your Codex sign-in {#use-codex-app-server-oauth-no-api-key} This approach is deprecated. Use the SIWC quick start above for new setups. Existing Codex sign-in configuration If you already signed in with Codex CLI (`codex login`) and want Midscene to use that OAuth session directly, set: ```bash export MIDSCENE_MODEL_BASE_URL="codex://app-server" export MIDSCENE_MODEL_NAME="gpt-6-sol" # or another model shown by Codex model/list export MIDSCENE_MODEL_FAMILY="gpt-6" ``` Notes: - `MIDSCENE_MODEL_API_KEY` is not required in this mode. - Midscene will call `codex app-server` through stdio. - Make sure `codex` is available in your PATH and verify auth with `codex login status`. The drawback of this approach is that we have observed longer execution times and higher token consumption than when calling an OpenAI-compatible API directly. For this reason, we do not recommend it. --- url: /consume-report-file.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Consume Report Files Midscene HTML report files capture the full execution history of a single Agent, making them useful for replay and debugging. Starting in v1.7.0, you can extract raw screenshots and JSON data from a report file, or convert the report into Markdown so other tools can consume it. Both `split` and `to-markdown` export images to `screenshots/` and reuse repeated images. Use the image paths provided in the exported content. ## Example You can parse a report file into a Markdown file like this: ```md # Act - Search for and play videos related to Midscene - Execution start: 2026-04-08T02:13:04.795Z - Task count: 21 ## 1. Plan - Click the top search box to activate input - Status: finished - Start: 2026-04-08T02:13:04.845Z - End: 2026-04-08T02:13:15.296Z - Cost(ms): 10451 - Screen size: 2880 x 1536 ![task-1](./screenshots/<image-1>.jpeg) ### Recorder - #1 type=screenshot, ts=2026-04-08T02:13:15.296Z, timing=after-calling ![task-1](./screenshots/<image-2>.jpeg) ## 2. Locate - The search input with the placeholder text "Li Weigang's Daily Life" at the top - Status: finished - Start: 2026-04-08T02:13:15.305Z - End: 2026-04-08T02:13:15.306Z - Cost(ms): 1 - Screen size: 2880 x 1536 - Locate center: (1489, 71) ..... ``` You can then combine it with the [Remotion Skill](https://www.remotion.dev/docs/ai/skills?utm_source=midscenejs) to parse the Markdown file and generate a customized replay video. The generated video looks like this: <video src="https://lf3-static.bytednsdoc.com/obj/eden-cn/vhaeh7vhabf/midscene-replay.mp4" height="300" controls></video> ## Parse With The CLI The report parsing tool is included in each platform CLI package, such as `@midscene/web` and `@midscene/android`. The subcommand is `report-tool`. Extract report contents as JSON and export the related screenshots into the `output-data` directory: ```shell npx @midscene/web report-tool --action split --htmlPath ./midscene_run/report/puppeteer-2026/index.html --outputDir ./output-data ``` Convert the report file into Markdown and write the result into the `output-markdown` directory: ```shell npx @midscene/web report-tool --action to-markdown --htmlPath ./midscene_run/report/puppeteer-2026/index.html --outputDir ./output-markdown ``` Merge multiple report files into a single combined report: ```shell npx @midscene/web report-tool --action merge-html \ --htmlReport ./midscene_run/report/case-a/index.html \ --htmlReport ./midscene_run/report/case-b.html \ --outputDir ./merged --outputName all-cases ``` Repeat `--htmlReport` once per source report. `--outputDir` and `--outputName` are optional; when omitted, the merged file is written to the default Midscene report directory with an auto-generated name. Pass `--overwrite` to replace an existing merged file. ## Parse With The JavaScript SDK If you prefer to control report parsing in code, use `splitReportFile`, `reportFileToMarkdown`, and `mergeReportFiles` from `@midscene/core`. ```ts import { mergeReportFiles, reportFileToMarkdown, splitReportFile, } from '@midscene/core'; const splitResult = splitReportFile({ htmlPath: './midscene_run/report/puppeteer-2026/index.html', outputDir: './output-data', }); console.log(splitResult.executionJsonFiles); const markdownResult = await reportFileToMarkdown({ htmlPath: './midscene_run/report/puppeteer-2026/index.html', outputDir: './output-markdown', }); console.log(markdownResult.markdownFiles); const mergedResult = mergeReportFiles({ htmlPaths: [ './midscene_run/report/case-a/index.html', './midscene_run/report/case-b.html', ], outputDir: './merged', outputName: 'all-cases', }); console.log(mergedResult.mergedReportPath); ``` `splitReportFile`, `reportFileToMarkdown`, and `mergeReportFiles` serve different outputs: - `splitReportFile` generates JSON files for the original structured objects (one `*.execution.json` per execution). The JSON keeps the raw `ReportActionDump`-style data and exports screenshots alongside it. The returned `executionJsonFiles` and `screenshotFiles` are lists of generated file paths. - `reportFileToMarkdown` converts the same report into human-readable Markdown and exports the screenshots referenced by that Markdown. The returned `markdownFiles` contains the generated Markdown file paths. - `mergeReportFiles` combines several report files into one merged HTML report. It is a thin wrapper over [`ReportMergingTool`](/reference.md#new-reportmergingtool) that derives `testTitle`/`testDescription` from each source report's `groupName` automatically. Use it when you run multiple CLI actions or tests and want to consolidate their reports. ## About Fields In JSON And Markdown The parsed JSON and Markdown structures may change as Midscene evolves. Use the actual conversion result as the source of truth. --- url: /data-privacy.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Data privacy ⁠Midscene.js is an open-source project (GitHub: [Midscene](https://github.com/web-infra-dev/midscene/)) under the MIT license. You can see all the codes in the public repository. The Midscene project does not collect your screenshots, API keys, or access tokens through the SDK. During AI steps, the SDK sends the required screenshots, prompts, and page context directly to the model service you configure. That service’s privacy policy governs how it stores and uses this data. By default, Midscene saves reports and logs on the machine running the task, under `midscene_run/report` and `midscene_run/log`. If your scripts, application screens, or execution results contain sensitive information such as plaintext tokens or cookies, that information may also appear in reports and logs. Manage access and retention, and remove sensitive content before sharing. In CI, console logs and uploaded artifacts may also be visible to people with access to the job. If you prefer building Midscene.js and its Chrome Extension in your own environment instead of using the published versions, you can refer to the [Contributing Guide](https://github.com/web-infra-dev/midscene/blob/main/CONTRIBUTING.md) to find building instructions. --- url: /faq.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # FAQ ## Platform-Specific FAQ The following platform-specific FAQs are maintained in their respective documentation: - [Web Browser - Playwright](/sdk/playwright.md#faq) - [Web Browser - Puppeteer](/integrate-with-puppeteer.md#faq) - [Web Browser - Chrome Extension](/platforms/web.md#chrome-extension-faq) - [Web Browser - Bridge Mode](/bridge-mode.md#faq) - [Android](/platforms/android.md#faq) - [iOS](/platforms/ios.md#faq) - [HarmonyOS](/platforms/harmonyos.md#faq) - [PC Desktop](/platforms/desktop.md#faq) ## Why are uppercase letters or modifier keys lost when controlling desktop clients such as VNC? {#keyboard-input-through-desktop-clients} When you use `@midscene/computer` to control VNC, TeamViewer, or a virtual machine console, some clients may not recognize every keyboard event. For example, uppercase `K` may become `k`, `!` may become `1`, or `Control+S` may produce only `s`. If this happens, add a delay between modifier-key events. The following configuration has been verified with a full-screen VNC client on Windows. ```typescript import { agentForComputer } from '@midscene/computer'; const agent = await agentForComputer({ inputStrategy: 'sequential', keyboardTypeDelay: 120, keyboardModifierDelay: 100, keyboardLayout: 'en-US', }); ``` `keyboardModifierDelay` is the primary option for fixing lost modifiers. Start with `100`. After keyboard input works correctly, reduce the value gradually if needed. ### Why does adding a delay help? Uppercase letters, shifted symbols, and keyboard shortcuts all depend on modifier keys. For example: - Uppercase `K` requires `Shift`, followed by `K`. - On an en-US keyboard, `!` requires `Shift`, followed by `1`. - `Control+S` requires `Control`, followed by `S`. Midscene converts these operations into modifier-down, primary-key, and key-release events. Some desktop clients capture these events and forward them to another system or feature. If the events arrive too close together, the client may not retain the modifier state while handling the primary key. The result can be a lowercase letter, a number instead of a symbol, or a shortcut reduced to its primary key. When you set `keyboardModifierDelay`, Midscene sends these events in phases and waits between each phase. This gives the desktop client time to recognize and forward the modifier state. Full-screen VNC is one verified example. However, this behavior is not limited to VNC or remote-control software. Any desktop client that captures or forwards keyboard events can be affected by input timing. ### What does each option do? - `keyboardModifierDelay` controls the wait between phases of a modified-key input. It applies to shortcuts such as `Control+S` and to the implicit `Shift` in uppercase letters. - `keyboardTypeDelay` controls the wait between consecutive text characters. - `inputStrategy: 'sequential'` enters text one character at a time, allowing Midscene to send the corresponding key sequence for uppercase letters and shifted symbols. - `keyboardLayout: 'en-US'` enables shifted-character mapping for the en-US keyboard layout. For example, it uses `Shift+1` to enter `!`. Uppercase Latin letters do not require `keyboardLayout`. Only layout-dependent shifted characters such as `!`, `@`, and `#` require this option. :::warning Set `keyboardLayout: 'en-US'` only when both the local and target environments use the en-US key mapping. Other layouts may place symbols on different keys or require modifiers such as AltGr. ::: ### Which input methods support this option? `keyboardModifierDelay` applies only to the local libnut keyboard driver. - Local desktop control on Windows and Linux uses libnut. - macOS uses this path when you set `keyboardDriver: 'libnut'`. - The option has no effect on direct RDP input. - The option has no effect on the default macOS AppleScript keyboard driver. AppleScript uses a different input method. Whether a desktop client recognizes it still depends on the client's shortcut interception, keyboard mode, and layout conversion. ### How do I send keyboard shortcuts? Pass the shortcut through the `keyName` option. Join modifiers and the primary key with `+`, without surrounding spaces. ```typescript // Send Control+S to the element that already has focus. await agent.aiKeyboardPress(undefined, { keyName: 'Control+S', }); // Locate the terminal first, then send Control+Shift+P. await agent.aiKeyboardPress('the terminal window', { keyName: 'Control+Shift+P', }); ``` Use `Control+S`, not `Control + S`. When the target already has focus, pass `undefined` as the first argument. This prevents an additional click from changing the current selection or caret position. ## What data is sent to AI model? The screenshot will be sent to the AI model. In some cases, like setting the `domIncluded` option to `true` when calling `aiAsk` or `aiQuery`, the DOM information will also be sent. ⁠If you are worried about data privacy issues, please refer to [Data Privacy](/data-privacy.md) ## My model provider requires adding specific headers to requests You can use `defaultHeaders` in the `MIDSCENE_MODEL_INIT_CONFIG_JSON` environment variable to specify headers to include in the request. For example: ```bash # Add a header with key "foo" and value "bar" to the request MIDSCENE_MODEL_INIT_CONFIG_JSON='{"defaultHeaders":{"foo":"bar"}}' ``` If your provider documentation calls this field `extra_headers` or `extraHeaders`, Midscene also accepts those aliases and normalizes them to `defaultHeaders`. When multiple aliases are present, the priority is: `defaultHeaders` > `extra_headers` > `extraHeaders`. You can generate the JSON string with JSON serialization to avoid mistakes when writing it by hand: ```javascript JSON.stringify({ defaultHeaders: { foo: 'bar' } }) ``` ## How do I use Azure OpenAI Service? When using Azure OpenAI Service, first choose the model and fill in the regular configuration from [Use a model API key](/model-api-setup.md). Azure only requires changing the model service URL and API Key to the Azure form: ```bash MIDSCENE_MODEL_BASE_URL="https://<your-resource>.services.ai.azure.com/openai/v1" # Or https://<your-resource>.openai.azure.com/openai/v1 MIDSCENE_MODEL_API_KEY="<your-azure-api-key>" ``` In other words, other settings such as `MIDSCENE_MODEL_NAME` and `MIDSCENE_MODEL_FAMILY` should still follow the corresponding model section in [Use a model API key](/model-api-setup.md). Azure is only a model provider with different authentication, not a special model. This uses the normal OpenAI-compatible path with `Authorization: Bearer ...`. Depending on `MIDSCENE_MODEL_PROTOCOL`, requests go to `/openai/v1/chat/completions` (the default) or `/openai/v1/responses`. Confirm that your Azure model and endpoint support the selected protocol. Do not append `/chat/completions` or `/responses` to `MIDSCENE_MODEL_BASE_URL`. For most `/openai/v1` endpoints you do not need `api-version`. If your resource still rejects the request with `400 Missing required query parameter: api-version`, the `/openai/v1` surface on that specific resource has not GA'd yet. Inject the query parameter through `defaultQuery`: ```bash MIDSCENE_MODEL_INIT_CONFIG_JSON='{"defaultQuery":{"api-version":"preview"}}' ``` Use the `api-version` value your resource expects (`preview`, or a dated version like `2025-01-01-preview` shown in the Azure portal). The query parameter is appended to the selected protocol's request path, for example `.../openai/v1/chat/completions?api-version=preview` or `.../openai/v1/responses?api-version=preview`. If an Azure-compatible gateway only accepts the `api-key` header, use this fallback: ```bash MIDSCENE_MODEL_API_KEY="placeholder" MIDSCENE_MODEL_INIT_CONFIG_JSON='{"defaultHeaders":{"api-key":"<your-azure-api-key>"}}' ``` In this fallback, `MIDSCENE_MODEL_API_KEY="placeholder"` only satisfies the OpenAI SDK constructor check. The real key is sent through `defaultHeaders.api-key`. These two fallbacks can be combined when a resource needs both `api-version` and the `api-key` header: ```bash MIDSCENE_MODEL_API_KEY="placeholder" MIDSCENE_MODEL_INIT_CONFIG_JSON='{"defaultQuery":{"api-version":"preview"},"defaultHeaders":{"api-key":"<your-azure-api-key>"}}' ``` Azure AD / keyless auth (`DefaultAzureCredential`) is not supported. Use an API key. ## Clicks are offset when using Azure OpenAI With a GPT-5 family model, you may find that the same script clicks the correct spot on the official OpenAI API but a consistently offset spot on Azure OpenAI's Chat Completions API. The offset scales with resolution: it appears at large screenshots (e.g. `1920x1080`) and disappears at small ones (e.g. `1280x600`). We observed that this issue is related to image handling in Azure's Chat Completions API. GPT-5 returns absolute coordinates based on the screenshot it actually sees, and Midscene sends the screenshot with `"detail": "original"` so the model sees the full-resolution image (see the [GPT-5 notes](/model-api-setup.md#gpt)). In affected Chat Completions requests, Azure does not honor `"detail": "original"`, so it downscales large images server-side (the short side is capped at 768). The model then answers in the downscaled coordinate space while Midscene maps coordinates against the original resolution, producing a proportional offset. You can confirm `original` is not taking effect by checking token usage: when `original` works, image token consumption is noticeably higher. We have verified that `"detail": "original"` works correctly with Azure's Responses API, so we recommend switching to the Responses protocol first: ```bash MIDSCENE_MODEL_PROTOCOL="openai-responses" ``` Confirm that your model supports the Responses API and use its corresponding Base URL. See [Protocol type](/model-config.md#model-api-type) for configuration details. If you cannot switch protocols yet, you can also: 1. Use the official OpenAI GPT-5, or configure a separate model dedicated to grounding (localization) and keep the Azure GPT-5 only as the planning model. 2. Pre-shrink the screenshot with the `screenshotShrinkFactor` agent option so the image stays under Azure's downscale threshold and no server-side resizing happens. See [`screenshotShrinkFactor`](/reference.md#common). ## How to improve the running time? There are several ways to improve the running time: 1. Use instant action interface like `agent.aiTap('Login Button')` instead of `agent.ai('Click Login Button')`. 2. Use a lower resolution if possible, this will reduce the input token cost. 3. Change to a faster model service 4. Use caching to accelerate the debug process. Read more about it in [Caching](/caching.md). ## How do I configure the midscene_run directory? Midscene saves reports, logs, and caches in `midscene_run/` by default. Standalone scripts, legacy YAML, and Playwright use the working directory as their base. Midscene Test uses the Test project. See [artifact directories](/midscene-test/running.md#unified-artifact-root-and-migration). You can customize the directory location using the `MIDSCENE_RUN_DIR` environment variable, which accepts both relative and absolute paths: ```bash # Using a relative path export MIDSCENE_RUN_DIR="./my_custom_dir" # Using an absolute path export MIDSCENE_RUN_DIR="/tmp/midscene_output" ``` Common subdirectories: - `report/` - Agent and Midscene Test reports (self-contained HTML by default) - `test-results/` - Execution results and diagnostic records - `log/` - Debug log files - `cache/` - Cache files (see [Caching](/caching.md)) - `output/` - Files produced during execution For global runtime options, see [Runtime configuration](/reference.md#runtime-configuration). ## How do I control the report player's default replay style via a link? You can override the default values of the **Focus on cursor** and **Show element markers** toggles by adding query parameters to the report URL, which determines whether the report highlights the cursor position and element markers. Use `focusOnCursor` and `showElementMarkers` with values such as `true`, `false`, `1`, or `0`. For example: `...?focusOnCursor=false&showElementMarkers=true`. ## How do I embed the report as a bare player? When embedding the report in another page (for example, in an `iframe`), add the `player-only=1` query parameter to strip all the surrounding chrome (top bar, sidebar, timeline, and detail side) and keep only the replay player. Two more flags tune the player: - `play-control=1` — in player-only mode, show the bottom playback control bar (hidden by default). Opt-in; enabled only by `=1`. - `auto-play` — whether playback starts automatically on load. This is independent of `player-only` and applies to every report player. It is **on by default**; add `auto-play=0` to disable it. A typical embed looks like `...?player-only=1&play-control=1`. It also composes with the `#task-<id>` hash anchor, so you can deep-link to a specific step and show only its player: `...?player-only=1#task-0-5`. To open any report (embedded or not) without autoplay, use `...?auto-play=0`. ## Inaccurate Element Positioning If you encounter inaccurate element positioning when using Midscene, follow these steps to troubleshoot and resolve the issue: ### 1. Upgrade to the Latest Version Make sure you are using the latest version of Midscene, as new versions typically include optimizations and improvements for positioning accuracy. ```bash # Web automation npm install @midscene/web@latest # iOS automation npm install @midscene/ios@latest # CLI tool npm install @midscene/cli@latest # Or other packages corresponding to your platform ``` ### 2. Use Better Vision Models Midscene's element positioning capability relies on the AI model's visual understanding ability, so be sure to choose models that support visual capabilities. Generally, newer versions and models with larger parameters perform better than older versions and smaller models. For example, Qwen3-VL performs better than Qwen2.5-VL, and its plus version performs better than the flash version. For current model recommendations, see [Model Selection Guide](/model-selection.md). ### 3. Check Model Family Configuration Verify that the `MIDSCENE_MODEL_FAMILY` parameter is set correctly in your model configuration. Incorrect `MIDSCENE_MODEL_FAMILY` configuration will affect Midscene's adaptation logic for the model. See [Use a model API key](/model-api-setup.md) for details. ### 4. Optimize prompts with visual features and position information If the positioning result randomly lands on unrelated elements and varies significantly between runs, the model usually cannot understand the semantics behind the icon button. For example, `aiTap('profile center')` is a functional description, and the model may not know the specific appearance of a profile icon. In contrast, `aiTap('person avatar icon')` is a visual description, so the model can locate the element based on its visual characteristics. Solution: optimize prompts by combining visual features and position information to describe the element. ```typescript // ❌ Using only a functional description await agent.aiTap('profile center'); // ✅ Using a visual description await agent.aiTap('person avatar icon'); // ✅ Combining visual features and position information await agent.aiTap('person avatar icon in the top right corner of the page'); ``` ### 5. Enable `deepLocate` If the positioning result lands near the target element but is still off by a few pixels, the model has probably identified the right target but still has some positioning deviation. Solution: enabling `deepLocate` can significantly improve positioning accuracy. ```typescript await agent.aiTap('Login button', { deepLocate: true }); ``` For more information about `deepLocate`, please refer to the [API documentation](/reference/index.md#deep-locate-deeplocate). ### 6. Increase the browser DPR to 2 on web If you are running Midscene in a web browser, you can try increasing the DPR to `2`. In CI environments, the default DPR is often `1`. Raising it to `2` makes the page clearer, which usually improves positioning for small elements. Keep in mind that this will consume more tokens. ## The model plans the wrong scroll or swipe direction in aiAct {#scroll-and-swipe-directions} If the model plans the wrong scroll or swipe direction in `aiAct()`, the cause may be ambiguity in the natural-language instruction. For example, “scroll down” can mean several things: - **Move the mouse wheel downward**: with common Windows mouse-wheel settings, the page content moves upward. - **Move a finger downward on the screen**: the page content follows the finger downward. - **Reveal content below the current viewport**: the required finger or mouse-wheel movement depends on how the device is operated. The model may therefore plan a direction that differs from your expectation because it interpreted the instruction differently. A good way to reduce ambiguity is to **state the result you want to achieve** in the instruction. For example: - “Scroll down the page to the footer.” - “Scroll the date picker up to increase the date.” - “Scroll the page to the right to view the content of the tab on the right.” Even if you and the model interpret a direction word differently, a clear goal helps the model plan the correct movement. Midscene instructs the model to prioritize the goal of the scroll or swipe when determining the movement direction. For vague instructions such as “scroll down” or “swipe down”, if the context still does not clarify the intent, the following defaults apply: - **scroll**: interpret the direction as the off-screen content to reveal. For example, scroll down means revealing content below the current viewport. - **swipe**: interpret the direction as finger movement. For example, swipe down means moving the finger downward. ## Does the Doubao phone use Midscene under the hood? No. ## Which Web package entry points should I import? Use `@midscene/web/playwright`, `@midscene/web/playwright/agent`, `@midscene/web/puppeteer` or the package root for Web integration. Generic Agent and YAML APIs are available from `@midscene/core/agent` and `@midscene/core/yaml`. The stale `@midscene/web/utils`, `@midscene/web/ui-utils`, `@midscene/web/yaml` and `@midscene/web/agent` declarations have been removed: they referenced files absent from published packages. Check the package's supported exports when updating custom integrations. --- url: /get-started.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started {#get-started} Answer three questions to open the setup steps for your platform, way of use, and model. Each path ends with a first run whose result you can inspect. ## All setup paths {#all-setup-paths} Each link opens the steps for one combination of platform, way of use, and model connection. **Web** - Playground: [ChatGPT subscription](/get-started/web-playground-chatgpt.md) · [Model API Key](/get-started/web-playground-api-key.md) - Midscene Test: [ChatGPT subscription](/get-started/web-test-chatgpt.md) · [Model API Key](/get-started/web-test-api-key.md) - Playwright Test: [ChatGPT subscription](/get-started/web-sdk-chatgpt.md) · [Model API Key](/get-started/web-sdk-api-key.md) **Android** - Playground: [ChatGPT subscription](/get-started/android-playground-chatgpt.md) · [Model API Key](/get-started/android-playground-api-key.md) - Midscene Test: [ChatGPT subscription](/get-started/android-test-chatgpt.md) · [Model API Key](/get-started/android-test-api-key.md) - Rstest / Vitest: [ChatGPT subscription](/get-started/android-sdk-chatgpt.md) · [Model API Key](/get-started/android-sdk-api-key.md) **iOS** - Playground: [ChatGPT subscription](/get-started/ios-playground-chatgpt.md) · [Model API Key](/get-started/ios-playground-api-key.md) - Midscene Test: [ChatGPT subscription](/get-started/ios-test-chatgpt.md) · [Model API Key](/get-started/ios-test-api-key.md) - Rstest / Vitest: [ChatGPT subscription](/get-started/ios-sdk-chatgpt.md) · [Model API Key](/get-started/ios-sdk-api-key.md) **HarmonyOS** - Playground: [ChatGPT subscription](/get-started/harmonyos-playground-chatgpt.md) · [Model API Key](/get-started/harmonyos-playground-api-key.md) - Midscene Test: [ChatGPT subscription](/get-started/harmonyos-test-chatgpt.md) · [Model API Key](/get-started/harmonyos-test-api-key.md) - Rstest / Vitest: [ChatGPT subscription](/get-started/harmonyos-sdk-chatgpt.md) · [Model API Key](/get-started/harmonyos-sdk-api-key.md) **Desktop** - Playground: [ChatGPT subscription](/get-started/desktop-playground-chatgpt.md) · [Model API Key](/get-started/desktop-playground-api-key.md) - Midscene Test: [ChatGPT subscription](/get-started/desktop-test-chatgpt.md) · [Model API Key](/get-started/desktop-test-api-key.md) - Rstest / Vitest: [ChatGPT subscription](/get-started/desktop-sdk-chatgpt.md) · [Model API Key](/get-started/desktop-sdk-api-key.md) --- url: /index.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Use the UI like a user Vision-driven E2E testing in natural language A GUI Agent and E2E testing framework for web, mobile, and desktop. [Get started](/get-started)[Create a test project](/midscene-test/use) **15k+**Github Stars [**MIT**Fully open source](https://github.com/web-infra-dev/midscene/blob/main/LICENSE) **#2**No.2 in Github trending ## Back to the essence of E2E testing with vision {#why-vision} E2E testing should verify the interface, not its code structure. Tests tied to UI code structure are inherently fragile — and even more importantly, they cannot tell whether a user can actually understand and use the interface, or whether the UI conveys the right information. In the AI-native era, vision models give us the ability to test closer to the essence of E2E — looking at the screen to act and judge like a user. With accuracy and cost now in balance, the next stage of E2E testing is already here. ## Describe steps and expectations in natural language {#test-intent} Describe what a user wants to do and what they should see. Express the same intent in YAML with Midscene Test, or in your existing JavaScript tests. **YAML · @midscene/test** ```yaml beforeEach: - gotoUrl: https://your-shop.example cases: - name: "Find headphones under $100" steps: - aiAct: "Search for headphones and filter the results to prices under $100" - aiWaitFor: "The filtered search results are visible" - aiAssert: "There are products in the search results, and each costs less than $100" ``` **Rstest + JavaScript** ```javascript import { test } from '@rstest/core'; import { PlaywrightAgent } from '@midscene/web/playwright'; // Model configuration, page setup, and cleanup omitted test("Find headphones under $100", async () => { const agent = new PlaywrightAgent(page); await agent.aiAct("Search for headphones and filter the results to prices under $100"); await agent.aiWaitFor("The filtered search results are visible"); await agent.aiAssert("There are products in the search results, and each costs less than $100"); }, 180_000); ``` **Vitest + JavaScript** ```javascript import { test } from 'vitest'; import { PlaywrightAgent } from '@midscene/web/playwright'; // Model configuration, page setup, and cleanup omitted test("Find headphones under $100", async () => { const agent = new PlaywrightAgent(page); await agent.aiAct("Search for headphones and filter the results to prices under $100"); await agent.aiWaitFor("The filtered search results are visible"); await agent.aiAssert("There are products in the search results, and each costs less than $100"); }, 180_000); ``` ![](/images/backgrounds/section-divider-light.svg)![](/images/backgrounds/section-divider-dark.svg) ## A GUI Agent built for vision-driven testing {#gui-agent} If you already have a test suite, Midscene’s GUI Agent brings visual actions and assertions directly into it. We recommend [Playwright Test](/integrate-with-playwright.md) for web apps and [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for mobile and desktop apps. ### Operate and verify by vision alone {#visual-capabilities} Midscene reads screenshots rather than code, testing the interface the way a user uses it. 1. 01**Plan**Read screenshots and decide the next step 1. 02**Locate & Act**Locate targets on screen and perform the UI action 1. 03**Verify**Assert on what users actually see [See real-world examples](/showcases) your-shop.example01 · Plan headphones < $100 $79 $89 aiAssert · passed ### One API, across platforms {#platforms} Visual localization does not depend on the UI rendering stack or code structure, so the same API works on web, mobile, desktop, and canvas-based interfaces. //Same API`await agent.**aiAct**('Search for headphones')` [**Web**`@midscene/web`](/integrate-with-playwright)[**Android**`@midscene/android`](/platforms/android)[**iOS**`@midscene/ios`](/platforms/ios)[**HarmonyOS**`@midscene/harmony`](/platforms/harmonyos)[**Desktop**`@midscene/computer`](/platforms/desktop)[**Custom interfaces**`@midscene/core`](/integrate-with-any-interface) ### Model options and cost {#model-options} Pure vision testing avoids sending large DOM trees to the model. With today’s vision models, accuracy and API cost reach a practical balance for E2E testing. [![](/images/models/supported-models-light.svg)![](/images/models/supported-models-dark.svg)### Multiple model options Choose from Doubao, DeepSeek, Qwen, GPT, Gemini, Kimi, and more to fit your tasks and budget. View model configuration](/model-selection)[Benchmark example · AppControlBench **$0.59**/ 60 tasks Total model API cost### Low model API cost In this AppControlBench run, Doubao Seed 2.1 Turbo passed 58 of 60 tasks at a total model API cost of $0.59. View benchmark report](/app-control-bench-report) ### Benchmarks {#benchmarks} [**93.1%**AndroidWorldPass@1 · Pass@3 97.4%](/android-world-benchmark-report)[**78.6%**MobileWorldPass@1 · 92 / 117 tasks](/mobile-world-benchmark-report)[**96.7%**AppControlBenchPass@1 · 58 / 60 tasks](/app-control-bench-report) ## Midscene Test: what an E2E framework looks like when tests are pure intent {#midscene-test} Through extensive practice, we found that once vision models handle UI interaction and verification, what remains in a test case is pure intent. At that point, traditional test frameworks built around hand-coded locators and page objects become unnecessary overhead. Midscene Test (`@midscene/test`) starts from that premise to rethink what an AI-native E2E framework should optimize for: expressing test cases as pure intent, encapsulating deterministic business operations as reusable capabilities, and letting engineers and AI agents maintain the same test suite together. [Get started with Midscene Test](/midscene-test/use.md) ### Interactive and business operations in one YAML file {#ai-and-nodes} Each YAML step calls a Node: an AI, platform, or custom business operation. Compose them into a test case. cases/refund.yamlInteractiveBusiness ```` 1beforeEach:2 - order.prepare: { status: paid }Business3 - gotoUrl: ${shopUrl}/orders/latestBusiness45cases:6 - name: A paid order supports a full refund7 steps:8 - aiAct: Apply for a full refund and submitInteractive9 - aiAssert: The page shows that the refund was submittedInteractive10 - order.checkRefund: { status: refunding }Business1112afterEach:13 - clearCookies: {}Business ```` Interactive**Interactive operations**APIs such as aiAct and aiAssert read the screen and follow natural-language instructions. Business**Business operations**Custom Nodes use TypeScript to prepare test data, check APIs, and clean up resources. ### Separate intent from business logic, maintained by people and AI {#nodes-and-spec} Wrap reusable business logic in custom Nodes. Midscene Test generates a Markdown Node Spec listing every Node and its inputs, so QA engineers and AI agents can write cases without reading TypeScript. [Learn how to develop custom Nodes](/midscene-test/extend.md) 1. nodes/order.ts ```typescript defineNode({ name: 'order.prepare', description: "Create a test order", inputSchema: z.strictObject({ status: z.literal('paid'), }), async execute({ input }) { await orders.create(input); }, }); ``` 1. midscene-node-spec.md ````markdown ### order.prepare Create a test order - status: "paid" ```` 1. case.yaml ```yaml steps: - order.prepare: status: paid ``` ### Replay every action in visual reports {#visual-reports} Every run generates an interactive HTML report. Inspect the full lifecycle step tree, drill into each Agent step’s `Plan`, `Locate`, and action timings, and scrub through the screenshot timeline to replay exactly what happened on screen. [Explore reporting](/midscene-test/running.md#output-and-exit-codes) Midscene.js/Overview/PassedFind headphones under $100 10.6s28.5K tokensVisualYAML Steps SETUP · 2 1gotoUrl120ms 2prepareCatalog18ms STEPS · 3 3**aiAct** Search for headphones3.8s 4**aiWaitFor** Filtered results visible1.4s 5**aiAssert** Each item costs < $1002.1s TEARDOWN · 1 6clearCookies4ms #3**aiAct**Passed Type "headphones" in the search box and click Search ExecutionTime Plan1.82s Locate0.42s Input0.96s Tap0.55s Elapsed3.75s Model2.24s RecordPlan · 1.82s 2s 4s 6s 8s Midscene Shop Search products Search Ready to search **Wireless Headphones**$89 Add to cart ### Engineering foundation built for visual agents {#framework-capabilities} Midscene Test ships with the runtime and CI capabilities needed to run visual agents reliably at scale: multi-project orchestration, isolated concurrency, guaranteed teardown, GitHub Actions integration, and machine-readable outputs. [### Multi-project orchestration Run web, Android, iOS, and desktop suites from one config with --project and tag filtering. ](/midscene-test/configuration)[### Concurrency and isolation Run YAML files in parallel via maxConcurrentFiles, each with its own isolated page, Agent, or device. ](/midscene-test/execution#concurrency-and-isolation)[### Lifecycle hooks and cleanup Project, file, and case hooks with reverse-order cleanup that still runs on timeout or Ctrl+C. ](/midscene-test/execution#project-lifecycle)[### Retries and timeouts Rerun failed cases after cleanup, with step timeouts, continue-on-error, and bail. ](/midscene-test/execution#handling-failures)[### CI & GitHub Actions Official midscene-action with PR summaries, #runner-step=last-error deep links, and live badges. ](/midscene-test/running#run-in-github-actions)[### AI-readable outputs & diagnostics Emit summary.json and result.md for scripts and AI agents, with model verify and token tracking. ](/midscene-test/running#output-and-exit-codes) ## Who is using Midscene {#users} [![](/images/icons/bytedance-color.svg)ByteDance](https://www.bytedance.com)[![](/images/users/alibaba-color.svg)Alibaba](https://www.alibaba.com)[![](/images/users/ctrip-color.svg)Ctrip](https://www.ctrip.com)[![AVATR](/images/users/avatr-wordmark.svg)](https://www.avatr.com)[![](/images/users/xiaomi-color.svg)Xiaomi](https://www.mi.com)[![iQIYI](/images/users/iqiyi-color.svg)](https://www.iqiyi.com)[![Bilibili](/images/users/bilibili-color.svg)](https://www.bilibili.com)[![Autel](/images/users/autel-color.svg)](https://autelenergy.com)[![](/images/users/rome-os.svg)Rome OS](https://github.com/rome-os/rome)[![](/images/users/volcengine.png)Volcengine](https://www.volcengine.com)[![](/images/users/douyin-color.svg)Douyin](https://www.douyin.com)[![](/images/users/tiktok-color.svg)TikTok](https://www.tiktok.com)[![](/images/users/lark-color.svg)Lark](https://www.larksuite.com)[![](/images/users/soda-music-color.svg)Soda Music](https://www.douyin.com/qishui)[![](/images/users/doubao-color.png)Doubao](https://www.doubao.com)[![Dongchedi](/images/users/dongchedi-color.svg)](https://www.dongchedi.com) ## Next steps {#next-steps} - **Understand the basics**: Learn how the GUI Agent works and explore its core capabilities in [The Basics](/basics.md) - **Get started**: Answer a few questions in [Get started](/get-started.md) and complete a first run on your platform - **Create a test project**: Write and run YAML test cases with [Midscene Test](/midscene-test/use.md) - **Write tests with code**: Integrate with [Playwright Test](/integrate-with-playwright.md) for web apps or [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for mobile and desktop apps - **Run standalone automation workflows**: [Write scripts with the JavaScript SDK](/sdk/standalone.md) To let AI coding agents operate your UI, explore [Midscene Skills](/skills.md). --- url: /integrate-with-any-interface.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Integrate with any interface You can use Midscene Agent to control any interface—such as IoT devices, in-house apps, and in-vehicle displays—by implementing a UI operation class that conforms to `AbstractInterface`. After implementing the UI operation class, you get the full capabilities of Midscene Agent: - the TypeScript GUI Automation Agent SDK, supporting integration with any interface - the playground for debugging - controlling the interface with YAML scripts - Skills support through CLI commands ## Demo and community project We have prepared a demo project for you to learn how to define your own interface class. It's highly recommended to check it out. - [Demo Project](https://github.com/web-infra-dev/midscene-example/tree/main/custom-interface) - A simple demo project that shows how to define your own interface class - [Android (adb) Agent](https://github.com/web-infra-dev/midscene/blob/main/packages/android/src/device.ts) - This is the Android (adb) Agent for Midscene that implements this feature - [iOS (WebDriverAgent) Agent](https://github.com/web-infra-dev/midscene/blob/main/packages/ios/src/device.ts) - This is the iOS (WebDriverAgent) Agent for Midscene that implements this feature There are also some community projects that use this feature: - [midscene-ios](https://github.com/lhuanyu/midscene-ios) - A project driving the OSX "iPhone Mirroring" app with Midscene ## Set up API keys for model The following example uses `qwen3.7-plus` through Alibaba Cloud: ```bash export MIDSCENE_MODEL_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1" export MIDSCENE_MODEL_API_KEY="your-api-key" export MIDSCENE_MODEL_NAME="qwen3.7-plus" export MIDSCENE_MODEL_FAMILY="qwen3" ``` Replace `your-api-key` with your API Key. > To use another model, such as Doubao, GLM, Gemini, or GPT-5, see [Use a model API key](/model-api-setup.md). For all configuration options, see [Model configuration](/model-config.md). ## Implement your own interface class ### Key concepts - The `AbstractInterface` class: a predefined abstract class that can connect to the Midscene Agent - The **action space**: a set of actions that describe the actions that can be performed on the interface. This will affect how the AI model plans the actions and executes them ### Step 1. Clone and setup from the demo project We provide a demo project that runs all the features of this document below. It's the fastest way to get started. ```bash # prepare the environment git clone https://github.com/web-infra-dev/midscene-example.git cd midscene-example/custom-interface npm install npm run build # run the demo npm run demo ``` ### Step 2. Implement your interface class Define a class that extends the `AbstractInterface` class, and implement the required methods. You can get the sample implementation from the [`./src/sample-device.ts`](https://github.com/web-infra-dev/midscene-example/blob/main/custom-interface/src/sample-device.ts) file. Let's take a glance at it. ```typescript import type { DeviceAction, Size } from '@midscene/core'; import { getMidsceneLocationSchema, z } from '@midscene/core'; import { type AbstractInterface, defineAction, defineActionTap, defineActionInput, // ... other action imports } from '@midscene/core/device'; export interface SampleDeviceConfig { deviceName?: string; width?: number; height?: number; } /** * SampleDevice - A template implementation of AbstractInterface */ export class SampleDevice implements AbstractInterface { interfaceType = 'sample-device'; private config: Required<SampleDeviceConfig>; constructor(config: SampleDeviceConfig = {}) { this.config = { deviceName: config.deviceName || 'Sample Device', width: config.width || 1920, height: config.height || 1080, }; } /** * Required: Take a screenshot and return base64 string */ async screenshotBase64(): Promise<string> { // TODO: Implement actual screenshot capture console.log('📸 Taking screenshot...'); return 'data:image/png;base64,...'; // Your screenshot implementation } /** * Required: Get interface dimensions * The width and height here refer to the logical size of the interface, not considering the device pixel ratio (dpr). The coordinates obtained from actions like defineActionTap are also based on this logical coordinate system. You can convert logical coordinates to physical coordinates in your action implementations if needed. */ async size(): Promise<Size> { return { width: this.config.width, height: this.config.height, }; } /** * Required: Define available actions for AI model */ actionSpace(): DeviceAction[] { return [ // Basic tap action defineActionTap(async (param) => { // TODO: Implement tap at param.locate.center coordinates await this.performTap(param.locate.center[0], param.locate.center[1]); }), // Text input action defineActionInput(async (param) => { // TODO: Implement text input await this.performInput(param.locate.center[0], param.locate.center[1], param.value); }), // Custom action example defineAction({ name: 'CustomAction', description: 'Your custom device-specific action', paramSchema: z.object({ locate: getMidsceneLocationSchema(), // ... custom parameters }), call: async (param) => { // TODO: Implement custom action }, }), ]; } async destroy(): Promise<void> { // TODO: Cleanup resources } // Private implementation methods private async performTap(x: number, y: number): Promise<void> { // TODO: Your actual tap implementation } private async performInput(x: number, y: number, text: string): Promise<void> { // TODO: Your actual input implementation } } ``` The key methods that you need to implement are: - `screenshotBase64()`, `size()`: help the AI model to get the context of the interface - `actionSpace()`: an array of `DeviceAction` objects defining the actions that can be performed on the interface. AI model will use these actions to perform the actions. Midscene has provided a set of predefined action spaces for the most common interfaces and devices. And there is also a method to define any custom action. Use these commands to run the agent: - `npm run build` to rebuild the agent - `npm run demo` to run the agent with javascript - `npm run demo:yaml` to run the agent with yaml script ### Step 3. Test the agent with the playground Attach a playground server to the agent, and you can test the agent in the web browser. ```ts import 'dotenv/config'; // read Midscene environment variables from .env file import { playgroundForAgent } from '@midscene/playground'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // instantiate device and agent const device = new SampleDevice(); await device.launch(); const agent = new Agent(device); // launch playground const server = await playgroundForAgent(agent).launch(); // close playground await sleep(10 * 60 * 1000); await server.close(); console.log('Playground closed!'); ``` ### Step 4. Add Skill support (optional) [Agent Skills](https://github.com/anthropics/skills) let AI coding assistants (Claude Code, Cline, etc.) drive your custom interface through CLI commands. Learn more in the [Skills documentation](/skills.md). Add a CLI entry file to your npm package (e.g., `./src/cli.ts`): ```ts #!/usr/bin/env node import { runSkillCLI } from '@midscene/core/skill'; import { SampleDevice } from './sample-device'; runSkillCLI({ DeviceClass: SampleDevice, scriptName: 'my-device', }); ``` Then add a `bin` field to your `package.json`: ```json { "bin": { "my-device": "./dist/cli.js" } } ``` Once published, AI coding assistants can control your custom interface via `npx my-device`. For Skill authoring guidelines and more examples, see the [midscene-skills](https://github.com/web-infra-dev/midscene-skills) repository. ### Step 5. Release the npm package, and let your users use it The agent and interface class have been exported in `./index.ts` file. Now you can publish it to npm. Fill the `name` and `version` in the `package.json` file, and then run the following command: ```bash npm publish ``` A typical usage of your npm package is like this: ```typescript import 'dotenv/config'; // read Midscene environment variables from .env file import { playgroundForAgent } from '@midscene/playground'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // instantiate device and agent const device = new SampleDevice(); await device.launch(); const agent = new Agent(device); await agent.aiAct('click the button'); ``` ### Step 6. Invoke your class in Midscene CLI and YAML script Write a yaml script with the `interface` section to invoke your class. ```yaml interface: module: 'my-pkg-name' # export: 'MyDeviceClass' # use this if this is a named export config: output: './data.json' ``` This config works same as this: ```typescript import MyDeviceClass from 'my-pkg-name'; const device = new MyDeviceClass(); const agent = new Agent(device, { output: './data.json', }); ``` Other fields in the yaml script are the same as the [yaml script](/automate-with-scripts-in-yaml.md). ## API reference ### Agent constructor ```typescript import { Agent } from '@midscene/core/agent'; import type { AbstractInterface } from '@midscene/core'; ``` Create an agent by pairing your custom `AbstractInterface` implementation with the standard constructor: ```typescript const device = new SampleDevice({ deviceName: 'Demo Panel', width: 1920, height: 1080, }); const agent = new Agent(device, { aiContexts: { aiAct: 'Dismiss pop-ups before every task.', }, generateReport: true, customActions: [], // optional additional custom DeviceAction list }); ``` - `device: AbstractInterface` (required): Any class that fulfills `screenshotBase64`, `size`, and `actionSpace`. This is where you translate Midscene actions into real I/O calls for your hardware or desktop app. - `options?: PageAgentOpt`: Shares the same option bag as the browser and mobile agents described in the [API constructors](/reference.md#common-parameters). Commonly used fields include `generateReport`, `reportFileName`, `aiContexts`, `cacheId`, `modelConfig`, `createOpenAIClient`, `customActions`, and `onTaskStartTip`. For guidance on writing and supplying context, see [Provide application knowledge to a GUI Agent](/provide-application-knowledge-to-gui-agent.md). - The resulting agent instantly unlocks the regular automation surfaces: `aiAct`/`aiTap` APIs, YAML runner (`interface` block), [playground](#playgroundforagent-function), Skills CLI support, and reporting pipeline. ### `AbstractInterface` class ```typescript import { AbstractInterface } from '@midscene/core'; ``` `AbstractInterface` is the key class for the agent to control the interface. These are the required methods that you need to implement: - `interfaceType: string`: define a name for the interface, this will not be provided to the AI model - `screenshotBase64(): Promise<string>`: take a screenshot of the interface and return the base64 string with the `'data:image/` prefix - `size(): Promise<Size>`: the size of the interface, which is an object with the `width` and `height` properties - `actionSpace(): DeviceAction[] | Promise<DeviceAction[]>`: the action space of the interface, which is an array of `DeviceAction` objects. Use predefined actions or define any custom action. Type signatures: ```ts import type { DeviceAction, Size, UIContext } from '@midscene/core'; import type { ElementNode } from '@midscene/shared/extractor'; abstract class AbstractInterface { // Required abstract interfaceType: string; abstract screenshotBase64(): Promise<string>; abstract size(): Promise<Size>; abstract actionSpace(): DeviceAction[] | Promise<DeviceAction[]>; // Optional lifecycle/hooks abstract destroy?(): Promise<void>; abstract describe?(): string; abstract beforeInvokeAction?(actionName: string, param: any): Promise<void>; abstract afterInvokeAction?(actionName: string, param: any): Promise<void>; } ``` These are the optional methods that you can implement: - `destroy?(): Promise<void>`: destroy the interface - `describe?(): string`: describe the interface, this may be used for the report and the playground. But it will not be provided to the AI model. - `beforeInvokeAction?(actionName: string, param: any): Promise<void>`: a hook function before invoking an action in action space - `afterInvokeAction?(actionName: string, param: any): Promise<void>`: a hook function after invoking an action ### The action space Action space is the set of actions that can be performed on the interface. AI model will use these actions to perform the actions. All the descriptions and parameter schemas of the actions will be provided to the AI model. To help you easily define the action space, Midscene has provided a set of predefined action spaces for the most common interfaces and devices. And there is also a method to define any custom action. This is how you can import the utils to define the action space: ```typescript import { type ActionTapParam, defineAction, defineActionTap, } from "@midscene/core/device"; ``` #### The predefined actions These are the predefined action spaces for the most common interfaces and devices. You can expose them to the customized interface by implementing the call method of the action. You can find the parameters of the actions in the type definition of these functions. - `defineActionTap()`: define the tap action. This is also the function to invoke for the `aiTap` method. - `defineActionDoubleClick()`: define the double click action - `defineActionInput()`: define the input action. This is also the function to invoke for the `aiInput` method. This is also the function to invoke for the `aiInput` method. - `defineActionKeyboardPress()`: define the keyboard press action. This is also the function to invoke for the `aiKeyboardPress` method. - `defineActionScroll()`: define the scroll action. This is also the function to invoke for the `aiScroll` method. - `defineActionDragAndDrop()`: define the drag and drop action - `defineActionLongPress()`: define the long press action - `defineActionSwipe()`: define the swipe action #### Define a custom action You can define your own action by using the `defineAction()` function. You can also use this method to define more actions for the [PuppeteerAgent](/integrate-with-puppeteer.md), [AgentOverChromeBridge](/sdk/chrome-bridge.md#constructor), and [AndroidAgent](/sdk/android.md). API Signature: ```typescript import type { ExecutorContext } from "@midscene/core"; import { defineAction } from "@midscene/core/device"; defineAction( { name: string, description: string, paramSchema: z.ZodType<T>; planningFeedbackMaxLength?: number | 'unlimited'; call: ( param: z.infer<z.ZodType<T>>, context?: ExecutorContext, ) => Promise<void>; } ) ``` - `name`: the name of the action, AI model will use this name to invoke the action - `description`: the description of the action, AI model will use this description to understand what the action is doing. For complex actions, you can provide a more detailed example here. - `paramSchema`: the [Zod](https://www.npmjs.com/package/zod) schema of the parameters of the action, AI model will help to fill the parameters according to this schema - `planningFeedbackMaxLength`: optional character limit for `context.task.planningFeedback`. Omit it to use the core default of 500 characters, set a number to use an action-specific limit, or set `'unlimited'` to disable truncation for this action. - `call`: the function to invoke the action, you can get the parameters from the `param` parameter which conforms to the `paramSchema` - `context`: optional execution context. The action's return value populates `task.output` (for your API callers and the report) and is **not** sent to the planner. To pass a planner-facing summary to the next planning round, set `context.task.planningFeedback`; `planningFeedbackMaxLength` controls whether and where it is truncated. Example: ```typescript defineAction({ name: 'MyAction', description: 'My action', paramSchema: z.object({ name: z.string(), }), call: async (param) => { console.log(param.name); }, }); ``` If you want to get a param about the location of some element, you can use the `getMidsceneLocationSchema()` function to get the specific zod schema. A more complex example about defining a custom action: ```typescript import { getMidsceneLocationSchema } from "@midscene/core/device"; defineAction({ name: 'LaunchApp', description: 'A an app on screen', paramSchema: z.object({ name: z.string().describe('The name of the app to launch'), locate: getMidsceneLocationSchema().describe('The app icon to be launched'), }), call: async (param) => { console.log(`launching app: ${param.name}, ui located at: ${JSON.stringify(param.locate.center)}`); }, }); ``` ### `playgroundForAgent` function ```typescript import { playgroundForAgent } from '@midscene/playground'; ``` The `playgroundForAgent` function creates a playground launcher for a specific Agent, allowing you to test and debug your custom interface Agent in a web browser. #### Function signature ```typescript function playgroundForAgent(agent: Agent): { launch(options?: LaunchPlaygroundOptions): Promise<LaunchPlaygroundResult> } ``` #### Parameters - `agent: Agent`: The Agent instance to launch the playground for #### Return value Returns an object containing a `launch` method. #### `launch` method options ```typescript interface LaunchPlaygroundOptions { /** * Port to start the playground server on * @default 5800 */ port?: number; /** * Whether to automatically open the playground in browser * @default true */ openBrowser?: boolean; /** * Custom browser command to open playground * @default 'open' on macOS, 'start' on Windows, 'xdg-open' on Linux */ browserCommand?: string; /** * Whether to show server logs * @default true */ verbose?: boolean; /** * Unique identifier for the playground server instance * Same ID shares playground chat history * @default undefined (generates random UUID) */ id?: string; } ``` #### `launch` method return value ```typescript interface LaunchPlaygroundResult { /** * The playground server instance */ server: PlaygroundServer; /** * The server port */ port: number; /** * The server host */ host: string; /** * Function to close the playground */ close: () => Promise<void>; } ``` #### Usage example ```typescript import 'dotenv/config'; import { playgroundForAgent } from '@midscene/playground'; import { SampleDevice } from './sample-device'; import { Agent } from '@midscene/core/agent'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // Create device and agent instances const device = new SampleDevice(); const agent = new Agent(device); // Launch playground const result = await playgroundForAgent(agent).launch({ port: 5800, openBrowser: true, verbose: true }); console.log(`Playground started: http://${result.host}:${result.port}`); // Close playground when needed await sleep(10 * 60 * 1000); // Wait 10 minutes await result.close(); console.log('Playground closed!'); ``` ## FAQ **My interface-controller is general-purpose; can it be included in this document?** Yes, we are happy to gather creative projects and list them in this document. [Raise an issue](https://github.com/web-infra-dev/midscene/issues) to us when it's ready. --- url: /integrate-with-playwright.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Integrate with Playwright Test With `PlaywrightAiFixture`, you can use Midscene's visual interaction and assertion capabilities directly in an existing Playwright Test project. Playwright Test organizes and runs the tests, while Midscene interacts with the page and generates execution reports. ## Before you begin - **Runtime**: Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. Have an existing Playwright Test project that can run tests with Chromium. - **Model configuration and verification**: Complete [model configuration](/model-api-setup) and [model verification](/model-config#verify-model-connectivity), then save the configuration in the project's `.env` file or shell environment. - **Platform environment**: Install Chromium and make sure the browser can access the target page. - **(Optional) Try Playground first**: Run an action and an assertion against your target interface in the [Chrome extension Playground](/get-started?platform=web&scene=playground) to verify screenshots, interactions, and model behavior. ## 1. Install dependencies and configure the project ```sh [npm] npm install @midscene/web dotenv --save-dev ``` ```sh [yarn] yarn add @midscene/web dotenv --save-dev ``` ```sh [pnpm] pnpm add @midscene/web dotenv --save-dev ``` ```sh [bun] bun add @midscene/web dotenv --save-dev ``` ```sh [deno] deno add npm:@midscene/web npm:dotenv --save-dev ``` Add the following configuration to `playwright.config.ts` (create the file if your project does not have one yet), while keeping your project's other settings and reporters: ```typescript title="playwright.config.ts" import 'dotenv/config'; import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './e2e', timeout: 90_000, use: { browserName: 'chromium' }, reporter: [ ['list'], ['@midscene/web/playwright-reporter'], ], }); ``` `dotenv/config` loads model settings from the project's `.env` file (settings in the Chrome extension Playground are not automatically shared with test runs). Because model calls take longer than standard DOM operations, increase `timeout` as needed for your tests. ## 2. Create a fixture {#step-2-extend-the-test-instance} Create `e2e/fixture.ts` to extend Playwright's `test` with `PlaywrightAiFixture`: ```typescript title="e2e/fixture.ts" import { test as base } from '@playwright/test'; import { PlaywrightAiFixture, type PlayWrightAiFixtureType, } from '@midscene/web/playwright'; export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture(), ); ``` In tests that use Midscene, import `test` from `./fixture` while continuing to import `expect` from `@playwright/test`. ## 3. Write a test ```typescript title="e2e/todo.spec.ts" import { expect } from '@playwright/test'; import { test } from './fixture'; test('add a todo', async ({ page, aiAct, aiAssert }) => { await page.goto('https://todomvc.com/examples/react/dist/'); await expect(page).toHaveTitle(/TodoMVC/); await aiAct('Add a todo named Try Midscene'); await aiAssert('The todo list contains Try Midscene'); }); ``` You can combine Playwright's `page` and `expect` with Midscene's AI methods in the same test. In this example, Playwright opens the page and checks its title, while Midscene adds a todo item and asserts the result on the page. Beyond `aiAct` and `aiAssert`, the fixture also provides `aiTap`, `aiInput`, `aiQuery`, `aiWaitFor`, and more; see the [Agent API reference](/reference/index.md#interaction-methods). ## 4. Run the test and view the report (Optional) Verify your model configuration before running the test: ```bash pnpm dlx @midscene/test@latest model verify ``` Run the test from the project directory: ```bash pnpm exec playwright test e2e/todo.spec.ts ``` After the test finishes, the Midscene reporter prints the report path in the terminal (saved under `midscene_run/report/` by default). Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. ## Common methods | Category | Representative methods | Description | | ------------------ | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | Auto-planning | `aiAct` | Describe a goal in natural language and let the Agent plan and execute multiple steps. | | Direct interaction | `aiTap`, `aiInput` | Locate a UI element by description and perform a single specified action without multi-step planning. | | Data extraction | `aiQuery`, `aiString`, `aiNumber`, `aiBoolean` | Extract structured or primitive data from the current UI for further processing in code. | | Assertions | `aiAssert` | Verify that the current UI meets an expectation; throws an error if it does not. | | Waiting | `aiWaitFor` | Wait until the UI meets a specified condition; throws an error on timeout. | In practice, you typically perform actions with `aiAct` or direct interaction methods and then verify the outcome with `aiAssert`—completing an action does not guarantee that the expected UI state was reached. For full parameter and return value details, see the [Agent API reference](/reference/index.md#interaction-methods). ## Further configuration ### Agent options {#agent-options} Pass Agent options when creating the fixture: ```typescript title="e2e/fixture.ts" import { test as base } from '@playwright/test'; import { PlaywrightAiFixture, type PlayWrightAiFixtureType, } from '@midscene/web/playwright'; export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture({ waitForNetworkIdleTimeout: 2000, replanningCycleLimit: 30, }), ); ``` You can also pass other Agent options such as `waitAfterAction` and `modelConfig`. Test and report metadata (`testId`, `reportFileName`, `groupName`, and `groupDescription`) are automatically derived from the current test info and do not need to be set manually. See [Playwright SDK configuration](/sdk/playwright.md#web-options) for platform options and [shared Agent options](/reference.md#agent-options) for common settings. ### Work with a specific page The AI methods injected by the fixture operate on Playwright's default `page` fixture. To interact with another `Page` instance in the same test (such as one created via `context.newPage()`), use `agentForPage` to get the corresponding Agent: ```typescript import { test } from './fixture'; test('inspect another page', async ({ context, agentForPage }) => { const page = await context.newPage(); await page.goto('https://todomvc.com/examples/react/dist/'); const agent = await agentForPage(page); await agent.aiAssert('The page contains a todo input'); }); ``` For details on new tabs and navigation behavior, see [Web / Playwright SDK](/sdk/playwright.md#about-opening-in-a-new-tab). ### Lifecycle Within a test, the fixture creates one Agent per `Page` and reuses it across AI calls. When a page closes or the test finishes, the fixture automatically calls `agent.destroy()` and collects the report, so you do not need to destroy fixture-managed Agents manually. Browser contexts and pages remain managed by Playwright. If you bypass the fixture and instantiate an Agent directly with `new PlaywrightAgent(page)`, you must call `agent.destroy()` yourself; see [Lifecycle and resource ownership](/sdk/standalone.md#lifecycle-and-resource-ownership). ### Report options Pass options to the reporter in `playwright.config.ts`: ```typescript import { defineConfig } from '@playwright/test'; export default defineConfig({ reporter: [ ['list'], ['@midscene/web/playwright-reporter', { type: 'merged', outputFormat: 'single-html', }], ], }); ``` - `type`: `'merged'` (default) combines all tests into a single report; `'separate'` generates a separate report for each test. - `outputFormat`: `'single-html'` (default) embeds execution data and screenshots in one HTML file for offline viewing; `'html-and-external-assets'` stores execution data and screenshots as external files. When using `'html-and-external-assets'`, keep the HTML file and its asset directory in their relative paths, and preview the report through a local HTTP server (opening it directly via `file://` is not supported): ```bash pnpm dlx serve midscene_run/report ``` Then open the URL printed in the terminal. When sharing or archiving the report, include both the HTML file and its asset directory. For a complete working project, see the [Playwright Test example](https://github.com/web-infra-dev/midscene-example/tree/main/playwright-testing-demo). --- url: /integrate-with-puppeteer.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Web / Puppeteer SDK `@midscene/web/puppeteer` provides Agents bound to a Puppeteer page or Browser. Both inherit the base Agent’s [AI methods](/reference.md#interaction-methods) and accept Web configuration options. ## Imports and API overview ```typescript import { PuppeteerPageAgent, PuppeteerAgent, PuppeteerBrowserAgent, } from '@midscene/web/puppeteer'; ``` | API | Scope | Purpose | | ----------------------- | ------------- | --------------------------------------------------------------------- | | `PuppeteerPageAgent` | One `Page` | Operate on the same page throughout its lifetime | | `PuppeteerAgent` | One `Page` | Compatibility alias for `PuppeteerPageAgent`, with identical behavior | | `PuppeteerBrowserAgent` | One `Browser` | Switch between pages; subsequent AI operations use the active page | In the signatures below, `Page` and `Browser` come from `puppeteer`. Option types come from `@midscene/web/puppeteer`. [](#) [](#) [](#) ## `PuppeteerPageAgent` {#puppeteer-agent} ```typescript new PuppeteerPageAgent(page: Page, options?: PuppeteerPageAgentOpt) ``` - `page`: required, an existing Puppeteer page. Throws when omitted. - `options`: optional, accepts [shared Agent options](/reference.md#agent-options) and [Web options](#web-options). ```typescript const agent = new PuppeteerPageAgent(page, { forceSameTabNavigation: false, }); await agent.aiAct('Click the login button'); ``` The Agent stays bound to the supplied page. By default, `forceSameTabNavigation: true` intercepts `window.open` and links with `target="_blank"` to open them in the current page. Set it to `false` to preserve new tabs; the Agent will not automatically switch to them. ## `PuppeteerBrowserAgent` {#puppeteer-browser-agent} ```typescript new PuppeteerBrowserAgent( browser: Browser, initialPage: Page, options?: PuppeteerBrowserAgentOpt, ) ``` - `browser`: required, the Browser used to listen for, list, and create pages. - `initialPage`: required, the initial active page. Use a page from this browser. - `options`: optional, accepts shared Agent options, Web options, and the dedicated options below. Throws when `browser` or `initialPage` is omitted. Browser Agent does not accept `forceSameTabNavigation`; even passing `false` through JavaScript throws an error. ### `PuppeteerBrowserAgent.create()` ```typescript PuppeteerBrowserAgent.create( browser: Browser, options?: PuppeteerBrowserAgentCreateOpt, ): Promise<PuppeteerBrowserAgent> ``` Creates an Agent asynchronously. The initial page is selected in this order: `options.initialPage` → `(await browser.pages())[0]` → `await browser.newPage()`. ```typescript const agent = await PuppeteerBrowserAgent.create(browser, { autoFollowNewPage: true, }); ``` ### Dedicated options | Option | Type | Default | Description | | ------------------- | --------- | ---------------------- | ------------------------------------------------------- | | `autoFollowNewPage` | `boolean` | `false` | Automatically make newly created browser pages active | | `newPageTimeout` | `number` | `5000` | Default timeout for `waitForNewPage()`, in milliseconds | | `initialPage` | `Page` | Automatically selected | Initial active page; available only in `create()` | ## Page management APIs These properties and methods belong only to `PuppeteerBrowserAgent`. ### `activePage` ```typescript agent.activePage: Page ``` Read-only property returning the Puppeteer page used by current AI operations. Use `setActivePage()` to switch pages. ### `pages()` ```typescript agent.pages(): Promise<Page[]> ``` Returns the pages in the bound browser without changing the active page. ### `newPage()` ```typescript agent.newPage(): Promise<Page> ``` Creates a page in the bound browser’s default BrowserContext, makes it active, and returns it. ### `setActivePage()` ```typescript agent.setActivePage(page: Page): Promise<void> ``` Makes the supplied page active and attempts to bring it to the foreground. Throws for an invalid or closed page. Supply a page from the bound browser. ### `waitForNewPage()` ```typescript agent.waitForNewPage( action?: () => Promise<unknown> | unknown, options?: { timeout?: number }, ): Promise<Page> ``` Registers a browser `targetcreated` listener (for page targets only) before running the optional `action`, then returns the new page it observes. `options.timeout` overrides `newPageTimeout` for this call, in milliseconds. Throws on timeout or if `action` fails. This method does not itself switch the active page. With `autoFollowNewPage: true`, the independent page listener still switches automatically. Keep that option `false` to control switching explicitly: ```typescript const agent = await PuppeteerBrowserAgent.create(browser, { autoFollowNewPage: false, }); const newPage = await agent.waitForNewPage( () => agent.aiTap('Open details'), { timeout: 10000 }, ); await agent.setActivePage(newPage); await agent.aiAssert('The details page is open'); ``` ## Configuration options {#web-options} Both Agents also accept [shared Agent options](/reference.md#agent-options), including model, report, and cache settings. | Option | Type | Default | Description | | -------------------------------- | --------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `forceSameTabNavigation` | `boolean` | `true` | Page Agent only; opens new-tab links in the current page | | `waitForNavigationTimeout` | `number` | `5000` | Timeout for waiting for the page’s `html` element, in milliseconds; `0` skips the check. Execution continues after timeout; this does not guarantee application readiness | | `waitForNetworkIdleTimeout` | `number` | `2000` | Post-action network-idle timeout in milliseconds; requires at most two in-flight requests for `200` consecutive milliseconds. `0` skips the check; execution continues after timeout | | `enableTouchEventsInActionSpace` | `boolean` | `false` | Adds touch gestures to the action space | | `keyboardTypeDelay` | `number` | Unset | Per-character input delay in milliseconds; must be finite and non-negative. In legacy mode, Puppeteer’s `page.keyboard.type` handles positive delays. When unset, uses the underlying driver’s default | | `inputStrategy` | `'legacy' \| 'sequential' \| 'bulk'` | `'legacy'` | Text input strategy; `sequential` sends individual Unicode code points, while `bulk` inserts the full text at once | | `forceChromeSelectRendering` | `boolean` | `true` | Injects `base-select` styling so native `select` options appear in screenshots; requires Puppeteer ≥ `24.6.0` and browser support for this styling | | `customActions` | `DeviceAction[]` | Unset | Adds [custom actions](/integrate-with-any-interface.md) to the planner | | `beforeInvokeAction` | `(actionName: string, param: any) => Promise<void>` | Unset | Callback before an action | | `afterInvokeAction` | `(actionName: string, param: any) => Promise<void>` | Unset | Callback after an action | | `testRunner` | `PuppeteerPageAgentOpt['testRunner']` | Unset | Supplies base URL and cookie settings to Midscene Test’s Puppeteer Nodes | `inputStrategy: 'bulk'` requires `keyboardTypeDelay` to be omitted or set to `0`. Use `'sequential'` for delayed input. To wait for application readiness, use `aiWaitFor()` or Puppeteer’s own waiting APIs. ## Lifecycle {#lifecycle} ```typescript agent.destroy(): Promise<void> ``` Both Agents support `destroy()`: it waits for associated operations, cleans up Agent-owned resources, calls the internal Device’s `destroy()`, and finishes report processing. Browser Agent also removes its `targetcreated` listener for automatic page following. The Puppeteer Device’s `destroy()` does not close the supplied Page, BrowserContext, or Browser, or explicitly disconnect a remote browser. The caller manages these Puppeteer resources. Pages and browsers remain usable after the Agent is destroyed. ```typescript try { await agent.aiAct('Submit the form'); } finally { await agent.destroy(); // The caller closes page, context, or browser according to resource ownership. } ``` ## Browser support and limitations Chrome / Chromium is recommended. Midscene’s Puppeteer integration depends on CDP for touch gestures and some interactions. Support for other browsers or protocols in Puppeteer itself does not imply support in Midscene. ### Remote browsers Agents accept existing Puppeteer pages, with the same construction API as local browsers. For example, after connecting over CDP: ```typescript import puppeteer from 'puppeteer'; import { PuppeteerPageAgent } from '@midscene/web/puppeteer'; const browser = await puppeteer.connect({ browserWSEndpoint: cdpWsUrl }); const page = (await browser.pages())[0] ?? await browser.newPage(); const agent = new PuppeteerPageAgent(page); ``` The caller manages the connection and authentication. Use `browser.disconnect()` to disconnect Puppeteer from a remote browser while leaving the browser process running; `browser.close()` closes the browser. [](#) #### Getting a CDP WebSocket URL {#get-cdp-url} You can get a CDP WebSocket URL from various sources, for example: - **Browser Use**: Get an API key at [https://cloud.browser-use.com](https://cloud.browser-use.com) and connect to `wss://connect.browser-use.com?apiKey=YOUR_API_KEY` - **BrowserBase**: Sign up at [https://browserbase.com](https://browserbase.com) and get your CDP URL - **Browserless**: Use [https://browserless.io](https://browserless.io) or run your own instance - **Local Chrome**: Run Chrome with `--remote-debugging-port=9222` and use `ws://localhost:9222/devtools/browser/...` - **Docker**: Run Chrome in a Docker container with debugging port exposed ## FAQ ### Puppeteer installation is slow or gets stuck Puppeteer downloads a browser binary during `postinstall`. If that download is slow or blocked, installation can appear to hang. ```bash # Skip browser download first so dependency installation can finish PUPPETEER_SKIP_DOWNLOAD=true pnpm install # Then download Chrome from a mirror # This example uses https://registry.npmmirror.com # Different mirror providers may use different base-url rules pnpm exec puppeteer browsers install chrome --base-url="https://registry.npmmirror.com/-/binary/chrome-for-testing" ``` ### Cannot click the dropdown If the dropdown options do not appear in the report screenshot after you click the field, the page is usually using a native `select` element. In that case, the expanded dropdown is rendered by the operating system instead of inside the webpage. Midscene enables `forceChromeSelectRendering` by default to force Chrome to render the dropdown; set it to `false` to opt out. For the detailed explanation and how to confirm the issue, see [Playwright FAQ — Cannot click the dropdown](/sdk/playwright.md#cannot-click-the-dropdown). ### The webpage continues to flash when running in headed mode This is caused by a mismatch between the viewport's `deviceScaleFactor` and the system pixel ratio. Set `deviceScaleFactor` to `0` to automatically use the device pixel ratio: ```typescript await page.setViewport({ width: 1280, height: 720, deviceScaleFactor: 0, }); ``` For more details, see [Playwright FAQ — The webpage continues to flash](/sdk/playwright.md#the-webpage-continues-to-flash-when-running-in-headed-mode). ### Customize the network timeout Use `waitForNavigationTimeout` and `waitForNetworkIdleTimeout` to adjust or disable the built-in checks. See [Configuration options](#web-options). --- url: /llm-txt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # LLMs.txt documentation How to get tools like Cursor, Windstatic, GitHub Copilot, ChatGPT, and Claude to understand Midscene.js. We support LLMs.txt files for making the Midscene.js documentation available to large language models. ## Directory overview The following files are available. - [llms.txt](https://www.midscenejs.com/llms.txt): The main LLMs.txt file - [llms-full.txt](https://www.midscenejs.com/llms-full.txt): The complete documentation for Midscene.js ## Usage ### Cursor Use `@Docs` feature in Cursor to include the LLMs.txt files in your project. [Read more](https://docs.cursor.com/context/@-symbols/@-docs) ### Windstatic Reference the LLMs.txt files using `@` or in your `.windsurfrules` files. [Read more](https://docs.windsurf.com/windsurf/getting-started#memories-and-rules) --- url: /mcp.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # MCP integration has been retired Midscene no longer ships MCP servers. Use [Skills](/skills.md) to let AI coding agents drive Midscene through the platform CLIs. If you still need the MCP server packages, pin Midscene to `1.9.8`. This is the final version that includes MCP support. Remove any agent configuration that references the retired MCP packages: - `@midscene/web-bridge-mcp` - `@midscene/android-mcp` - `@midscene/ios-mcp` - `@midscene/harmony-mcp` - `@midscene/computer-mcp` - `@midscene/mcp` If your previous MCP configuration set `MIDSCENE_MCP_CHROME_PATH`, move that value to `MIDSCENE_CHROME_PATH` for Skills and CLI usage. The old variable is still accepted as a temporary migration alias. For code-level automation, use the JavaScript SDK, YAML runner, or the platform CLIs listed in [Skills](/skills.md). --- url: /midscene-test/builtin-nodes.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Built-in Nodes across platforms Midscene Test refers to each callable capability in YAML test cases and lifecycle hooks as a **Node**. When you register an official Agent in `midscene.config.ts` using `createMidsceneNodes({ agentClass, getAgent })`, the framework injects general AI capabilities and official built-in Nodes for the respective platform. This guide catalogs available built-in Nodes, their input structures, and common usage patterns across platforms. :::info Generating a Node Spec for your project This page lists standard specifications for official built-in capabilities. To inspect the effective list of available Nodes, their JSON input schemas, and custom business Nodes in your project, run `pnpm exec midscene-test nodes` (or pass `--project <name>` for multi-project repositories) to generate `midscene-node-spec.md`. ::: ## Node syntax overview YAML cases support two calling styles: 1. **String shorthand**: When a Node specifies a `stringInputKey`, you can pass a single string directly: ```yaml steps: - gotoUrl: https://bing.com - aiAct: Search for Midscene and open the official website - aiAssert: The page title contains Midscene ``` 2. **Object mapping**: When providing multiple fields or optional configuration, supply key-value pairs; for Nodes without parameters, pass `{}`: ```yaml steps: - setViewportSize: width: 1440 height: 900 - back: {} ``` *** ## Universal Nodes All testing targets (Web, Android, iOS, HarmonyOS, and Desktop) support core AI action and assertion Nodes. ### Core AI Nodes In typical test authoring, the most essential and recommended Nodes are: | Node | String shorthand | Description | Key parameters | | ----------- | ---------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `aiAct` | `prompt` | Plans and executes composite actions from natural-language intent. | `prompt` (action goal; supports reference images), `options` (such as `deepThink`) | | `aiAssert` | `prompt` | Asserts that the current interface satisfies expected conditions; fails the step and halts the case if unmet. | `prompt` (assertion condition), `message` (custom failure message), `options` | | `aiWaitFor` | `prompt` | Polls until a natural-language condition is satisfied; throws on timeout. | `prompt` (wait condition), `options` (`timeoutMs`, `checkIntervalMs`) | ```yaml filename=Example: Core AI workflow cases: - name: Search for products and verify results steps: - aiAct: Type "mug" into the search box and tap search - aiWaitFor: The search results list finishes loading - aiAssert: The results list displays at least one mug ``` ### Other atomic actions and advanced Nodes Other atomic interaction methods available on the GUI Agent SDK (such as `aiTap`, `aiHover`, `aiInput`, `aiKeyboardPress`, `aiScroll`, `aiDragAndDrop`, etc.) can also be called directly as Nodes in YAML. However, **for test case robustness, avoid overly fine-grained step-by-step orchestration in YAML**: - Breaking a flow down into many granular clicks, focus changes, and swipes makes YAML files brittle and verbose, increasing maintenance cost when the UI layout evolves; - Prefer `aiAct` to describe the user's business intent (for example, "Type mug into the search box and tap search"), allowing the visual model to plan the underlying actions adaptively. The runtime also injects several auxiliary and advanced capabilities: - **Data extraction and queries**: `aiQuery` (structured data extraction), `aiBoolean` / `aiString` / `aiNumber` / `aiAsk` (interface content extraction and Q\&A). - **Context guidance and reporting**: `setAIContext` (injects domain guidance or modal dismissal rules for subsequent AI steps), `recordToReport` (appends custom notes or snapshots to reports). - **Waiting and execution**: `wait` (framework-level cancellable wait with `{ duration, unit }`), `sleep` (Agent-level wait), `javascript` (evaluates scripts). To inspect input parameters for these advanced Nodes, generate your project's Node Spec with `pnpm exec midscene-test nodes`. *** ## Web built-in Nodes Web project templates run on Playwright or Puppeteer and provide browser session management alongside universal capabilities: | Node | String shorthand | Description | Key parameters | | ----------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `gotoUrl` | `url` | Navigates the current page to an absolute URL or a path relative to `baseURL`. | `url` (target URL), `waitUntil` (`domcontentloaded`, `load`, `networkidle`, `commit`), `timeoutMs` (defaults to 60000) | | `setViewportSize` | No | Sets the viewport dimensions of the current browser window. | `width` (CSS pixels), `height` (CSS pixels) | | `setCookies` | No | Loads cookies into the current browser context from an environment variable, profile, or storage-state file without leaking sensitive values into logs. | `cookiesEnv` (env var name), `profile`, `storageStatePath` (file path) | | `clearCookies` | No | Clears cookies from the browser context, optionally matching specific name, domain, or path filters. | `name`, `domain`, `path`; pass `{}` to clear all cookies | ```yaml filename=Example: Web workflow beforeEach: - setViewportSize: width: 1280 height: 800 - clearCookies: {} - gotoUrl: https://todo.example.com cases: - name: Add a todo item steps: - aiAct: Type "Buy milk" into the input box and press enter - aiAssert: '"Buy milk" appears in the list' ``` *** ## Mobile built-in Nodes Mobile testing targets rely on device lifecycles and physical/system keys. Midscene provides standardized system controls and platform bridges for Android, iOS, and HarmonyOS. ### Android (`@midscene/android`) | Node | String shorthand | Description | Key parameters | | ------------- | ---------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | `launch` | `uri` | Launches an app by package name, DeepLink URL, or configured alias. | `uri` (package name, URL, or app name) | | `terminate` | `uri` | Force-stops an application. | `uri` (package name or app name) | | `back` | No | Triggers the Android system back button or gesture. | `{}` (no parameters) | | `home` | No | Triggers the Android system Home button. | `{}` (no parameters) | | `recentApps` | No | Opens the Android recent applications overview. | `{}` (no parameters) | | `runAdbShell` | `command` | Executes a raw ADB shell command and returns standard output. Do not include an `adb shell` prefix. | `command` (shell command string), `options` (`timeout` in milliseconds) | ```yaml filename=Example: Android workflow beforeEach: - launch: com.example.shop - wait: duration: 3 unit: s cases: - name: View product details and return steps: - aiAct: Tap the first recommended product on the home screen - aiAssert: Product details page is open with a Buy Now button - back: {} - aiAssert: Returned to the shop home screen ``` ### iOS (`@midscene/ios`) | Node | String shorthand | Description | Key parameters | | --------------- | ---------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `launch` | `uri` | Launches an app by bundle identifier, URL scheme, or configured alias. | `uri` (bundle identifier or URL) | | `terminate` | `uri` | Terminates an application. | `uri` (bundle identifier or app name) | | `home` | No | Triggers the iOS system Home action. | `{}` (no parameters) | | `appSwitcher` | No | Opens the iOS App Switcher overview. | `{}` (no parameters) | | `runWdaRequest` | No | Sends an HTTP request directly to WebDriverAgent on the device and returns JSON output. | `request`: `{ method: 'GET' \| 'POST' \| 'DELETE' \| 'PUT', endpoint: string, data?: object }` | ```yaml filename=Example: iOS workflow beforeEach: - launch: com.apple.Preferences cases: - name: Open Settings and return to Home steps: - aiAssert: Settings root list is visible - home: {} ``` ### HarmonyOS (`@midscene/harmony`) | Node | String shorthand | Description | Key parameters | | ------------- | ---------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------- | | `launch` | `uri` | Launches an application, Ability target, or DeepLink URI. | `uri` (bundle name, Ability target, or URI) | | `terminate` | `uri` | Terminates an application. | `uri` (bundle name or app name) | | `back` | No | Triggers the HarmonyOS system back action. | `{}` (no parameters) | | `home` | No | Triggers the HarmonyOS system Home action. | `{}` (no parameters) | | `recentApps` | No | Opens the HarmonyOS recent tasks overview. | `{}` (no parameters) | | `runHdcShell` | `command` | Executes an HDC shell command on the device and returns stdout. Do not include an `hdc shell` prefix. | `command` (shell command string) | ```yaml filename=Example: HarmonyOS workflow beforeEach: - launch: com.example.notes cases: - name: Create a new note steps: - aiTap: New note button in the lower right corner - aiInput: prompt: Note body input field value: Prepare test fixtures - back: {} - aiAssert: '"Prepare test fixtures" appears in the notes list' ``` *** ## Desktop (Computer) Desktop automation (macOS, Windows, Linux) leverages the full suite of [universal Nodes](#universal-nodes): - Use `aiAct`, `aiTap`, `aiDoubleClick`, and `aiRightClick` to inspect and interact with native application windows, system menus, and modal dialogs. - Use `aiKeyboardPress` to issue keyboard shortcuts (such as focus switching or save shortcuts). - For complex system-level setup or platform utilities, implement [custom Nodes](/midscene-test/extend.md) to call native shell scripts or system commands. *** ## Next steps - [Write YAML cases](/midscene-test/writing.md): Learn workflow document structures, variable bindings, tag filtering, and lifecycle hooks. - [Develop custom Nodes](/midscene-test/extend.md): Encapsulate domain APIs, backend fixtures, and private tooling. - [Configure test projects](/midscene-test/configuration.md): Manage project settings, platform drivers, and multi-project workspaces. --- url: /midscene-test/configuration.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Configure test projects `midscene.config.ts` is the project configuration file for Midscene Test. Use it to configure browser or device initialization, register Nodes for test cases to call, and set execution options such as concurrency and timeouts. This guide covers configuration structure, Agent and platform integration, multiple execution projects, and file resource isolation. ## Configuration structure Use `defineTestProject()` to define and export your project configuration. An Execution Project selects cases and supplies their runtime environment. Midscene Test supports the following configuration files: | How the configuration is selected | Supported file | Loading behavior | | --------------------------------------------------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | Automatic discovery, when no configuration path is provided | `midscene.config.ts` or `midscene.config.mjs` | `.ts` is transformed from TypeScript; `.mjs` is loaded by Node.js as native ESM | | An explicit path passed through the CLI's `--config <path>` option or `loadTestProject(path)` | `.ts` or `.mjs` | `.ts` is transformed from TypeScript; `.mjs` is loaded by Node.js as native ESM without TypeScript transformation | Midscene Test loads `midscene.config.ts` or `midscene.config.mjs` by default. If both files exist, it reports a conflict instead of choosing one silently; use `--config <path>` to select the intended file explicitly. Prepare shared project resources in `setup`, prepare resources for each file in `fileSetup`, and register the corresponding Agent Nodes through `nodes`. | Field | Purpose | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `setup` | Prepares browser or device resources shared by a project. | | `fileSetup` | Prepares an environment for each YAML file, in both sequential and concurrent runs. | | `nodes` | Registers Nodes shared by all execution projects. | | `projects` | Declares named execution projects with their own resources and case selection. Place `setup` and `fileSetup` inside each project when declared; otherwise, top-level settings apply to the default project. | | `test` | Sets concurrency, the failure threshold, and the default step timeout. | | `output` | Sets the report output directory. | The example below starts with a single execution project. To manage multiple execution projects or register different Nodes for each project, see [Configure multiple execution projects](#configure-multiple-execution-projects). ## Configure the runtime environment ### Complete example: Playwright This sequential configuration uses only `setup`: all files in the execution project share one page. Add [`fileSetup`](#isolate-resources-with-filesetup) when each file needs its own environment, even without concurrency. To add Midscene Test to an existing project manually, first install `@midscene/test`, `@midscene/web`, and `playwright` (`pnpm add -D @midscene/test @midscene/web playwright`), then run `pnpm exec playwright install chromium` to install the browser. Before running tests, follow [Model configuration](/model-api-setup.md) to set the required environment variables, including your API Key. For a handwritten configuration, load `.env` explicitly (for example, install `dotenv`, import `dotenv/config` at the top, and run from the project root), or supply shell/CI variables. See [Environment loading](/midscene-test/running.md#environment-loading). ```ts filename=midscene.config.ts import { defineProjectSetup, defineTestProject, } from '@midscene/test/config'; import { createMidsceneNodes } from '@midscene/test/midscene'; import { PlaywrightAgent } from '@midscene/web/playwright/agent'; import { chromium, type Browser, type Page } from 'playwright'; interface ProjectContext { browser: Browser; page: Page; agent?: PlaywrightAgent; } const midsceneNodes = createMidsceneNodes<ProjectContext>({ agentClass: PlaywrightAgent, getAgent: ({ context }) => { context.agent ??= new PlaywrightAgent(context.page); return context.agent; }, }); // Define browser environment setup and cleanup const playwrightSetup = defineProjectSetup<ProjectContext>({ name: 'playwright', async setup({ onTeardown }) { const browser = await chromium.launch({ headless: true }); onTeardown(() => browser.close()); const browserContext = await browser.newContext(); const page = await browserContext.newPage(); const context: ProjectContext = { browser, page }; onTeardown(async () => { await context.agent?.destroy(); }); return context; }, }); // Export the project configuration export default defineTestProject<ProjectContext>({ projects: [ { name: 'chromium', setup: playwrightSetup, files: { include: ['cases/**/*.{yaml,yml}'] }, }, ], nodes: midsceneNodes, }); ``` The configuration connects these parts: - `setup` creates the browser and page and registers cleanup functions through `onTeardown()`. - `context` holds runtime resources. Nodes obtain the Agent through `getAgent`, which creates an instance on first use and stores it in `context.agent` for subsequent calls. Playwright Nodes use that Agent’s page. - `nodes` registers common AI operations and Playwright operations for YAML cases to call. - `projects` declares an execution project named `chromium`, connecting its `setup` to the YAML files under `cases/`. You can now [write YAML test cases](/midscene-test/writing.md) and [run tests](/midscene-test/running.md#run-tests). The next section explains how these resources are shared and cleaned up. ### Create and clean up shared resources with setup `defineProjectSetup()` defines project preparation, assigned through the `setup` field. During a test run, each execution project calls its `setup()` function once. The example above returns a browser and page for the project's Nodes to share. For file isolation, define per-file preparation with `defineFileSetup()` and assign it through `fileSetup`. It receives the project setup's return value and creates resources for the current file. See [Isolate resources with fileSetup](#isolate-resources-with-filesetup) for the relationship and an example. Shared resources are not automatically recreated before each case. To reset pages, cookies, or business state, call the appropriate Nodes through YAML [lifecycle hooks](/midscene-test/execution.md#yaml-lifecycle-hooks). For reading and updating shared data in custom Nodes, see [Share context across Nodes](/midscene-test/extend.md#share-context-across-nodes). After creating a browser, Agent, or other resource, immediately register its cleanup function with `onTeardown()`. The framework attempts the registered cleanup functions when the project finishes, even if setup or test execution fails. Cleanup runs in reverse registration order: in the Playwright example above, the Agent is destroyed before the browser closes. The `onTeardown()` callbacks registered here run when the project finishes. Cleanup functions registered inside Nodes have their own [execution scope](/midscene-test/extend.md#resource-lifecycle-and-cleanup). ### Isolate resources with fileSetup Use `setup` for shared project resources and `fileSetup` for resources owned by each file. Web tests can share one Browser while creating a separate BrowserContext, Page, and Agent per file to isolate cookies and other browser state. ```ts filename=midscene.config.ts import { defineFileSetup, defineProjectSetup, defineTestProject, } from '@midscene/test/config'; import { createMidsceneNodes } from '@midscene/test/midscene'; import { PlaywrightAgent } from '@midscene/web/playwright/agent'; import { chromium, type Browser } from 'playwright'; type SharedContext = { browser: Browser }; type FileContext = { agent: PlaywrightAgent }; const setup = defineProjectSetup<SharedContext>({ name: 'browser', async setup({ onTeardown }) { const browser = await chromium.launch(); onTeardown(() => browser.close()); return { browser }; }, }); const fileSetup = defineFileSetup<FileContext, SharedContext>({ name: 'page', async setup({ projectContext, signal, onTeardown }) { if (!projectContext) throw new Error('Browser setup did not complete'); const session = await projectContext.browser.newContext(); onTeardown(() => session.close()); signal.throwIfAborted(); const page = await session.newPage(); const agent = new PlaywrightAgent(page); onTeardown(() => agent.destroy()); return { agent }; }, }); export default defineTestProject<FileContext, SharedContext>({ test: { maxConcurrentFiles: 3 }, projects: [ { name: 'web', setup, fileSetup, maxConcurrentFiles: 2, files: { include: ['cases/web/**/*.yaml'] }, }, ], nodes: createMidsceneNodes<FileContext>({ agentClass: PlaywrightAgent, getAgent: ({ context }) => context.agent, }), }); ``` The YAML uses the prepared Agent: `beforeAll` sets the viewport, and `beforeEach` opens the home page for every case: ```yaml filename=cases/web/search.yaml beforeAll: - setViewportSize: width: 1280 height: 720 beforeEach: - gotoUrl: https://your-shop.example cases: - name: Search for mugs steps: - aiAct: Search for mugs - aiAssert: The search results include mugs ``` This example creates the Agent in `fileSetup`. File cleanup destroys the Agent and then closes the BrowserContext. The shared Browser closes after all file cleanup. The type parameters in `defineFileSetup<FileContext, SharedContext>` describe the file return value and the project return value, respectively. `fileSetup` returns the complete file context; it is not automatically merged with `projectContext`. Explicitly return shared fields that Nodes need. The preparation function receives these arguments: | Argument | Purpose | | ----------------- | ------------------------------------------------------------------------------------ | | `projectContext` | The project `setup` return value, or `undefined` when no project setup is configured | | `project`, `file` | Current project configuration, plus the file's `sourcePath` and execution IDs | | `env`, `signal` | Environment variables and cancellation notifications | | `onTeardown()` | Registers cleanup to run when the file finishes | For a single configuration, omit `projects` and put `setup` and `fileSetup` at the top level. If a file can prepare all its resources itself, configure only `fileSetup`. On Android, iOS, and other device platforms, allocate an exclusive device to each concurrent file and create a separate Device/Agent. Each Device instance belongs to one Agent, and `Agent.destroy()` destroys that Device; return the device allocation after destroying the Agent. Project code supplies the device pool and business-state reset. With one phone or one desktop, set that project's limit to `1`; multiple Agents operating the same device still interfere with each other. See [Project lifecycle](/midscene-test/execution.md#project-lifecycle) for context scope and cleanup order, and [Handling failures](/midscene-test/execution.md#handling-failures) for preparation failures. Nodes or `fileSetup` must explicitly report shared-resource failures; Browser closure messages alone do not establish ownership. See [Asynchronous operations, errors, and cancellation](/midscene-test/extend.md#asynchronous-operations-errors-and-cancellation) for how to report them. ## Register official Nodes ### Common AI operations and Agent integration The Midscene Test kernel does not register Nodes implicitly. Configuration generated by `midscene-test create` calls `createMidsceneNodes()` from `@midscene/test/midscene` to register official Nodes for the selected platform. In handwritten configuration, explicitly add the returned definitions to top-level `nodes` or `projects[].nodes`. `createMidsceneNodes()` returns the common and platform Node definitions declared by `agentClass.getTestRunnerNodeDefinitions()`, plus the Test-provided `wait` Node. Common capabilities cover AI operations, assertions and extraction, interface location, and report recording. Platform Agents add browser or device operations. The website does not maintain a duplicate exhaustive list; use the current Project's generated [Node Spec](/midscene-test/writing.md#generate-the-current-projects-node-spec) for exact names and inputs. When calling `createMidsceneNodes()`, use `agentClass` to specify the platform-specific Midscene GUI Agent class and a `getAgent` callback to supply the Agent instance at runtime: ```ts import { createMidsceneNodes } from '@midscene/test/midscene'; import { PlaywrightAgent } from '@midscene/web/playwright/agent'; const midsceneNodes = createMidsceneNodes<ProjectContext>({ agentClass: PlaywrightAgent, getAgent: ({ context }) => { context.agent ??= new PlaywrightAgent(context.page); return context.agent; }, }); ``` `createMidsceneNodes()` does not mutate a global registry; its Nodes become available only after the returned array is included in project configuration. `agentClass` is the sole source of Agent-backed Node definitions, while `getAgent` describes how execution obtains an Agent instance from the current context. The factory throws during registration if the class does not expose `getTestRunnerNodeDefinitions()`. PlaywrightAgent, PlaywrightPageAgent, PlaywrightBrowserAgent, PuppeteerAgent, PuppeteerPageAgent, PuppeteerBrowserAgent, AndroidAgent, IOSAgent, and HarmonyAgent provide common and platform Node definitions together. The base Agent and ComputerAgent only provide common Agent Nodes. #### Name Nodes for multiple Midscene Agents When one workflow uses multiple Midscene Agents, set `namespace` to register their Nodes under different names. Have your setup return separate Midscene Agent instances in the context, then register both sets in the same Project: ```ts import { Agent } from '@midscene/core/agent'; import { createMidsceneNodes } from '@midscene/test/midscene'; interface MultiAgentContext { mobile: Agent; web: Agent; } const nodes = [ ...createMidsceneNodes<MultiAgentContext>({ namespace: 'mobile', agentClass: Agent, getAgent: ({ context }) => context.mobile, }), ...createMidsceneNodes<MultiAgentContext>({ namespace: 'web', agentClass: Agent, getAgent: ({ context }) => context.web, }), ]; ``` Add `nodes` to your Project configuration. YAML calls the registered names: ```yaml cases: - name: Complete a Todo across devices steps: - mobile.aiAct: Create a Todo titled "Buy milk". - web.aiWaitFor: The Todo "Buy milk" is visible. - web.aiTap: the checkbox beside "Buy milk" ``` The namespace prefixes every returned Node, including common AI operations, platform operations, and `wait`. For example, this registration provides `mobile.aiAct` and `mobile.wait`; it does not also register the unprefixed names. Omit `namespace` to keep the original names. A namespace must be a non-empty string without whitespace, leading or trailing dots, or empty dot-separated segments. Nested namespaces such as `checkout.mobile` are supported. Invalid values fail during registration, before an Agent is acquired. Namespaces only change Node names. `getAgent` or `agentProvider.getAgent` still selects the runtime Agent, and execution traces remain associated with the corresponding Steps. Namespaces do not create resources or provide concurrency isolation. Separate Projects can register the same Node names without a namespace. For an Android/iOS registration example, see [Configure multiple execution projects](#configure-multiple-execution-projects). When integrating an Agent on device platforms such as Android or iOS, observe resource ownership. Each device instance belongs to one Agent. `Agent.destroy()` also destroys its device. Create separate resources for each execution project, and do not reuse a device after its Agent is destroyed. Register each platform through `createMidsceneNodes()`: specify its Agent class with `agentClass` and supply the instance through `getAgent`. You can choose your own field names for the project `context`. Once registered, these Nodes can be called from YAML. See [Calling other Nodes](/midscene-test/writing.md#calling-other-nodes) for parameter syntax, and consult the project-generated Node Spec for specific fields. ### Playwright Use `createMidsceneNodes({ agentClass: PlaywrightAgent, getAgent })` to automatically register `gotoUrl`, `setCookies`, `clearCookies`, and `setViewportSize`. Before using these Nodes, install `playwright` in your project. It is a peer dependency of `@midscene/web`: ```bash pnpm add -D playwright ``` Cookies are read from `process.env` by default. Only configure Agent `testRunner` options such as `getEnv`, `getCookieProfile`, or `resolveStorageStatePath` when you need custom cookie sources. The `context` in these callbacks is the current Agent. `setCookies` does not accept cookie values in YAML. Midscene Test persists every Node input in the run result. An inline cookie would be copied into that record. Use exactly one of `cookiesEnv`, `profile`, or `storageStatePath` as a cookie reference. The Node resolves the actual cookies only at execution time and passes them directly to the Playwright BrowserContext. On success, the result records the reference name and cookie count. On failure, the underlying error may contain cookie values. An environment variable may contain a Cookie header, a JSON cookie array, or Playwright storage-state JSON. Relative storage-state paths resolve from the current working directory by default; use `resolveStorageStatePath` when a project needs a different root. Protect the environment variable, profile, or storage-state file. Do not commit storage-state files containing real cookies. ```yaml beforeEach: - clearCookies: {} - setCookies: cookiesEnv: E2E_COOKIES url: https://example.com - setViewportSize: width: 1440 height: 900 - gotoUrl: url: https://example.com/chat waitUntil: domcontentloaded ``` See the [current project's Node Spec](/midscene-test/writing.md#generate-the-current-projects-node-spec) for navigation inputs. ### Puppeteer Puppeteer exposes the same `gotoUrl`, `setCookies`, `clearCookies`, and `setViewportSize` Node names. Install the `puppeteer` peer dependency and pass `PuppeteerAgent` (or `PuppeteerBrowserAgent`) to `createMidsceneNodes()`: ```bash pnpm add -D puppeteer ``` ```ts import { PuppeteerAgent } from '@midscene/web/puppeteer'; import { createMidsceneNodes } from '@midscene/test/midscene'; const midsceneNodes = createMidsceneNodes<ProjectContext>({ agentClass: PuppeteerAgent, getAgent: ({ context }) => { context.agent ??= new PuppeteerAgent(context.page, { testRunner: { baseURL: 'https://example.com' }, }); return context.agent; }, }); ``` The Playwright and Puppeteer integrations use the same Web Node schemas and execution implementation. Browser-specific code is limited to a driver adapter. For portable YAML, use `domcontentloaded`, `load`, or `networkidle` for `gotoUrl.waitUntil`; the Puppeteer adapter maps `networkidle` to `networkidle0`. Existing engine-specific values remain supported: Playwright accepts `commit`, while Puppeteer accepts `networkidle0` and `networkidle2`. Using one of those values with the other driver produces an explicit error. Both integrations accept the same cookie references. Relative URLs resolve against `testRunner.baseURL`, then against the current HTTP(S) page URL. ### Android To use the device presets below, declare an `agent` of the corresponding platform type in `ProjectContext` and include that instance in the object returned by `setup`. Each platform example is independent; choose the one you need. Use `createMidsceneNodes({ agentClass: AndroidAgent, getAgent })` to register `launch`, `terminate`, `runAdbShell`, `back`, `home`, and `recentApps`. The supplied Agent must provide the methods these Nodes call: ```ts import { AndroidAgent } from '@midscene/android'; import { createMidsceneNodes } from '@midscene/test/midscene'; const androidNodes = createMidsceneNodes<ProjectContext>({ agentClass: AndroidAgent, getAgent: ({ context }) => context.agent, }); ``` ```yaml beforeEach: - runAdbShell: command: pm clear com.example.app options: timeout: 5000 - launch: uri: com.example.app ``` The complete response from `runAdbShell` is saved in the Node result. ### iOS Use `createMidsceneNodes({ agentClass: IOSAgent, getAgent })` to register `launch`, `terminate`, `runWdaRequest`, `home`, and `appSwitcher`: ```ts import { IOSAgent } from '@midscene/ios'; import { createMidsceneNodes } from '@midscene/test/midscene'; const iosNodes = createMidsceneNodes<ProjectContext>({ agentClass: IOSAgent, getAgent: ({ context }) => context.agent, }); ``` ```yaml steps: - launch: uri: com.example.app - runWdaRequest: request: method: GET endpoint: /status - terminate: uri: com.example.app ``` The complete response from `runWdaRequest` is saved in the Node result. ### HarmonyOS Use `createMidsceneNodes({ agentClass: HarmonyAgent, getAgent })` to register `launch`, `terminate`, `runHdcShell`, `back`, `home`, and `recentApps`: ```ts import { HarmonyAgent } from '@midscene/harmony'; import { createMidsceneNodes } from '@midscene/test/midscene'; const harmonyNodes = createMidsceneNodes<ProjectContext>({ agentClass: HarmonyAgent, getAgent: ({ context }) => context.agent, }); ``` ```yaml steps: - runHdcShell: command: bm dump -a - home: {} ``` The complete response from `runHdcShell` is saved in the Node result. ## Configure execution projects An execution project connects a runtime environment to its cases. Even a single execution project can configure case selection, variables, and retries. Declare multiple execution projects to run across browsers, devices, or environments. ### Select cases and control execution | Setting | Meaning | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `projects[].files` | `include` selects YAML files; `exclude` removes matches. Patterns are relative to the test directory. | | `projects[].tags` | Includes or excludes cases by tag. | | `projects[].variables` | Supplies values for YAML `${variable}` references. | | `projects[].retry` | Number of retries for a failed case; defaults to `0`. | | `test.testTimeout` | Default timeout for each step in milliseconds; defaults to `120000`. A step's `$` timeout overrides it. | | `test.bail` | Stops scheduling new work when the failed-case threshold is reached; `0` disables the threshold. | | `output.reportDir` | Optional report directory override, relative to the Test project. Defaults to `report/` under the artifact root (`midscene_run/report/` by default). | | `output.reportFormat` | `'single-html'` (default) includes execution data and images in one HTML file for direct offline viewing. `'html-and-external-assets'` writes a directory report that requires HTTP preview. | See [Run tests](/midscene-test/running.md#run-tests) for CLI project selection and configuration file options, and [Configure timeouts and error handling](/midscene-test/writing.md#configure-timeouts-and-error-handling) for step overrides. The scaffold generates a configuration that selects `cases/**/*.{yaml,yml}` by default. Without a `files` configuration, Midscene Test recursively searches for `**/*.{yaml,yml}` under the test directory. Selected files are deduplicated and sorted by path. See [Project lifecycle](/midscene-test/execution.md#project-lifecycle) for execution order and retry scope, and [Concurrency and isolation](/midscene-test/execution.md#concurrency-and-isolation) for concurrency settings. Native Test always generates a combined report. The CLI prints its path after the run. See [Run tests](/midscene-test/running.md) for report outputs and archiving. ### Configure multiple execution projects To run tests across different browsers or devices, configure multiple Execution Projects with `defineTestProject()`. Nodes registered in the top-level `nodes` field apply to every Project; the field defaults to `[]` when omitted. Within an individual Project, you can also register local Nodes using the `nodes` field alongside `setup` and `files`. A local Node applies only to that Project and replaces the entire global definition with the same name. Other global Nodes remain available. Duplicate names within the same registration layer cause an error. When configuring both Android and iOS projects, register each platform Agent's official Nodes within its Project. The example below imports two independent setups from `./setup`, each managing its own resources and returning `{ agent }`. It imports shared business Nodes from `./nodes`: ```ts filename=midscene.config.ts import { AndroidAgent } from '@midscene/android'; import { IOSAgent } from '@midscene/ios'; import { defineTestProject } from '@midscene/test/config'; import { createMidsceneNodes, type MidsceneUIAgent } from '@midscene/test/midscene'; import { sharedNodes } from './nodes'; import { androidSetup, iosSetup } from './setup'; interface ProjectContext { agent: MidsceneUIAgent; } export default defineTestProject<ProjectContext>({ nodes: sharedNodes, projects: [ { name: 'android-smoke', setup: androidSetup, nodes: createMidsceneNodes<ProjectContext>({ agentClass: AndroidAgent, getAgent: ({ context }) => context.agent, }), files: { include: ['cases/**/*.{yaml,yml}'], exclude: ['cases/**/*.draft.yaml'], }, tags: { include: ['smoke'], exclude: ['manual'] }, retry: 1, variables: { appUri: 'com.example.app' }, }, { name: 'ios-smoke', setup: iosSetup, nodes: createMidsceneNodes<ProjectContext>({ agentClass: IOSAgent, getAgent: ({ context }) => context.agent, }), files: { include: ['cases/**/*.{yaml,yml}'] }, variables: { appUri: 'com.example.ios' }, }, ], test: { maxConcurrentProjects: 1, // Maximum number of active Execution Projects bail: 0, // Stop scheduling new tasks after this many failed cases when > 0 testTimeout: 120_000, }, }); ``` Both Projects can use the same YAML file. During case collection, input validation, and test execution, `launch` and other platform Nodes use the definitions that apply to the current Project. A Project's local Nodes do not affect other Projects. ### Generate a Node Spec for each Project Run `midscene-test nodes` to generate a Node Spec of the available Nodes. Use `--project` to select an execution project and list the Nodes available after combining its global and local registrations: ```bash pnpm exec midscene-test nodes --project android-smoke ``` When `projects` is declared, omitting `--project` generates a separate Spec for each Execution Project, even when their Node definitions are identical. For filenames, output rules, Spec contents, and command options, see [Generate the current Project's Node Spec](/midscene-test/writing.md#generate-the-current-projects-node-spec). ## Programmatic APIs You can also use APIs to integrate Midscene Test into other tools, such as a local test panel with a graphical interface. The following APIs let you load project configuration, run an entire project, or execute an individual case: ```ts import { loadTestProject, runTestProject } from '@midscene/test/config'; import { CaseRunner, createCaseRunner, runWorkflowDocument, } from '@midscene/test'; ``` - **`loadTestProject(path)`**: asynchronously loads an explicitly provided TypeScript (`.ts`) or JavaScript ESM (`.mjs`) project configuration. Without `--config`, the CLI discovers `midscene.config.ts` or `midscene.config.mjs`; if both exist, it asks you to select one explicitly. Midscene Test does not support synchronous loading. - **`runTestProject()`**: asynchronously discovers, runs, and summarizes the entire project. - **`CaseRunner` / `createCaseRunner()`**: directly runs one test case represented as a plain object, without file parsing or lifecycle management. - **`runWorkflowDocument()`**: runs the complete lifecycle and every Case in one document. Run a complete project and preserve its failure exit status: ```ts import { runTestProject } from '@midscene/test/config'; try { const result = await runTestProject({ projectRoot: process.cwd(), configPath: './midscene.config.ts', resultDir: './test-results', }); console.log(result.summaryPath, result.reportPath); process.exitCode = result.exitCode; } catch (error) { console.error(error); process.exitCode = 1; } ``` ## Next steps - [Execution lifecycle and concurrency](/midscene-test/execution.md): resource sharing, retries, concurrency, timeouts, and cancellation. - [Run tests and CLI reference](/midscene-test/running.md): targets, paths, and environment variables. --- url: /midscene-test/execution.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Execution lifecycle and concurrency ## Project lifecycle ### setup, fileSetup, and beforeAll They run in the order `setup → fileSetup → beforeAll → cases`. Unconfigured parts are skipped. | Setting | Location | Frequency | Purpose | | ----------- | --------------------- | ---------------------------- | --------------------------------------------------------------- | | `setup` | Project configuration | Once per project | Prepare shared resources, such as a Browser | | `fileSetup` | Project configuration | Once per file | Create an independent page and Agent; return the Node `context` | | `beforeAll` | YAML | Once before the file's cases | Use `context` to log in or prepare test data | In a normal run of two YAML files, `setup` runs once, while `fileSetup` and `beforeAll` each run twice. Concurrency limits do not change these counts. Configure `fileSetup` once for all files; declare `beforeAll` in each file. Custom Nodes in `beforeAll` can also create resources, but this does not make the framework create an independent file context. ### YAML lifecycle hooks {#yaml-lifecycle-hooks} Lifecycle hooks prepare the environment, reset state, or clean up data around test cases. All four hooks are optional and appear at the same level as `cases`. Their steps use the same Node call syntax as case `steps`. | Hook | When it runs | Common uses | | ------------ | --------------------------------------------------------------- | ------------------------------------------- | | `beforeAll` | Once before all cases in the current YAML file | Prepare data shared by the file's cases | | `beforeEach` | Before every execution of a case, including retries | Open a page or reset case state | | `afterEach` | After every execution of a case, including failures and retries | Clean up data created during that execution | | `afterAll` | Once after all cases in the current YAML file | Clean up data shared by the file's cases | This Web example opens the store home page before each case and clears cookies afterward. `data.prepare` and `data.cleanup` are custom Nodes your project must implement and register to prepare and remove test products. `gotoUrl`, `clearCookies`, `aiAct`, and `aiAssert` are official Nodes registered by the Web scaffold: ```yaml filename=cases/search.yaml beforeAll: - data.prepare: Prepare mug and kettle test products beforeEach: - gotoUrl: https://your-shop.example cases: - name: Search for mugs steps: - aiAct: Search for mugs - aiAssert: The search results include mugs - name: Search for kettles steps: - aiAct: Search for kettles - aiAssert: The search results include kettles afterEach: - clearCookies: {} afterAll: - data.cleanup: Delete the test products prepared for this file ``` ### Project, file, and case lifecycle When running tests through the CLI or `runTestProject()`, each execution project has its own lifecycle. The following shows normal sequential execution for a project with two YAML files. YAML hooks that are not declared are skipped: ```text Execution project starts ├─ setup → returns the shared project context ├─ File A │ ├─ fileSetup (when configured) → returns the file context │ ├─ beforeAll │ ├─ Case 1: beforeEach → steps → afterEach → Node cleanup for this attempt │ ├─ Case 2: beforeEach → steps → afterEach → Node cleanup for this attempt │ ├─ afterAll │ └─ File-scoped Node cleanup → cleanup registered in fileSetup ├─ File B │ └─ Runs its own hooks, cases, and cleanup in the same order └─ Project cleanup: onTeardown() callbacks registered in setup ``` `beforeAll` and `afterAll` each run once per YAML file; `beforeEach` and `afterEach` surround every case attempt. With file concurrency enabled, files can advance together, while each file follows the order shown above. Case retries reuse the file environment and repeat only `beforeEach → steps → afterEach → Node cleanup for this attempt`. Project `setup`, `fileSetup`, and `beforeAll` do not rerun. See [Handling failures](/midscene-test/execution.md#handling-failures) for retry conditions and skip rules. The scope of `onTeardown()` depends on where it is registered: | Registration location | Cleanup timing | | ---------------------------------------------- | ----------------------------------------------------------------------------- | | Project `setup` | At project completion, after cleanup of all files that ran | | `fileSetup` | After the current file's `afterAll` and file-scoped Node cleanup | | Nodes in `beforeAll` or `afterAll` | After the current file's `afterAll` | | Nodes in `beforeEach`, `steps`, or `afterEach` | After the current attempt's `afterEach`, with separate cleanup for each retry | Within each scope, callbacks run in reverse registration order. If one throws, remaining callbacks are still attempted; if it has not finished, later cleanup waits for it. See [Resource lifecycle and cleanup](/midscene-test/extend.md#resource-lifecycle-and-cleanup) for implementing Node cleanup. ### Context sharing scope The configuration determines which `context` Nodes receive: | Configuration | Source of `context` | Shared by | | -------------------- | ------------------------------------------------------ | ----------------------------------------------------------- | | Project `setup` only | The return value of `setup` | All files in the current project | | With `fileSetup` | The return value of that file's `fileSetup` invocation | Hooks and cases in the current file, including case retries | Nodes within the same sharing scope receive the same object. A value written to `context.orderId` can remain visible to later cases. The framework does not reset the context, page, or login state between cases or retries; restore the required initial state in `beforeEach`. Create resources and the returned object inside the `setup()` function. Projects or files invoke the function separately even when they reference the same definition; returning a mutable object from module scope would still share state. See [Share context across Nodes](/midscene-test/extend.md#share-context-across-nodes) for a data-passing example. ### Handling failures | Failure location | What happens next | | ---------------------------- | ---------------------------------------------------------------------------- | | Project `setup` | Skip the project's files and attempt registered project cleanup | | `fileSetup` | Skip the current file's hooks and cases, and attempt registered file cleanup | | `beforeAll` | Mark the file's cases as `not-run`, but still run `afterAll` | | `beforeEach` or case `steps` | Skip the current case's remaining body steps, but still run `afterEach` | | `afterEach` or `afterAll` | Record a failure; cleanup-step errors are not ignored | A failed step skips the remaining steps in its phase by default. Set [`continue-on-error`](/midscene-test/writing.md#configure-timeouts-and-error-handling) to continue, while keeping the failed result. Cleanup Nodes should handle partially completed preparation. A failed case does not prevent the next case from running by default. Set `test.bail` to skip later cases and retries after a failed-case threshold; the current attempt finishes before cleanup. Cancelling the run instead requests that running operations stop. Keep dependent business steps in the same case. Resource failures or failed or unfinished registered cleanup stop retries and later cases in the current file. Whether other files continue depends on the sharing scope: | Situation | Affected scope | | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | A file's exclusive device fails, and operations and cleanup have finished | With `fileSetup`, other independent files can continue, subject to `bail` | | An explicitly reported shared project resource failure | Stop other files in that project; without `fileSetup`, resource failures or cleanup problems also stop the project | | Operations or cleanup remain unfinished | Stop starting all new files | An ordinary `afterEach` step failure remains a case failure and can be retried after operations and registered cleanup finish. Run infrastructure errors, such as result publication failures, cancel the entire run. See [Create and clean up shared resources with setup](/midscene-test/configuration.md#create-and-clean-up-shared-resources-with-setup) for resource configuration, and [Resource lifecycle and cleanup](/midscene-test/extend.md#resource-lifecycle-and-cleanup) for cleanup inside Nodes. ## Concurrency and isolation Two limits apply together: `maxConcurrentFiles` limits files across the whole run, and `maxConcurrentProjects` limits projects whose preparation has started but whose cleanup has not finished. Each defaults to `1` independently. Set either to `null` to remove that limit; numeric values must be positive integers. | `test` configuration | Behavior | | ----------------------------------------------------------- | -------------------------------------------------------------------------------- | | Omitted | Finish one project at a time, running its files sequentially | | `{ maxConcurrentFiles: 4 }` | One project at a time, with up to 4 files running together | | `{ maxConcurrentProjects: 2 }` | Files remain globally sequential; up to 2 project environments may stay open | | `{ maxConcurrentFiles: null, maxConcurrentProjects: 1 }` | Finish one project at a time, without a global file limit | | `{ maxConcurrentFiles: null, maxConcurrentProjects: null }` | Remove both global limits; local file limits and available resources still apply | Execution is asynchronous within one Node.js process. Raising only the project limit does not raise file concurrency. Removing limits does not guarantee a faster run: browser capacity, devices, and model service quotas still matter. ### File concurrency with maxConcurrentFiles | Configuration | Meaning | | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `test.maxConcurrentFiles` | Total active files across all projects; default `1`, `null` for unlimited | | `test.maxConcurrentProjects` | Projects from the start of preparation through completed cleanup; default `1`, `null` for unlimited | | `projects[].maxConcurrentFiles` | Positive integer file limit for this project; inherits the global file limit when omitted and cannot raise it | | `projects[].fileSetup` | Prepares an independent environment for each file; required when the effective project file limit exceeds `1`, including unlimited, even if only one file is selected | For example, with `test: { maxConcurrentFiles: 3, maxConcurrentProjects: 2 }` and Web and Android file limits of `2` each, two Web files and one Android file can run together, or one Web file and two Android files. The project count does not multiply the global file limit. A file occupies a slot from preparation through completed cleanup, including device waits and case retries. Starting a new project claims both a project slot and its first file slot before `setup`; other files in that project wait for initialization without taking additional slots. Eligible projects take turns admitting files. A project keeps its slot between files, even when none is currently running. Its last file retains a file slot through project cleanup; the project slot is released only when cleanup actually finishes. With `maxConcurrentProjects: 1`, the next project starts after the previous one is fully cleaned up. Setting only `maxConcurrentFiles: 1` allows files from different projects to interleave if the project limit permits it. After cancellation or `bail`, cleanup for initialized projects with no active files is also scheduled within the global file limit. See [Timeouts and cancellation](#timeouts-and-cancellation). ### Existing configurations `test.maxConcurrency` has been removed; loading an old configuration reports an error with a migration example. It controlled project concurrency, so simply renaming it to `maxConcurrentFiles` changes behavior. To preserve an old limit of `2`, set `test: { maxConcurrentProjects: 2, maxConcurrentFiles: 2 }` and each project's `maxConcurrentFiles` to `1`. Without explicit `projects`, keep the global file limit at `1`. `fileSetup`, project file limits, and preparation/cleanup timeouts can be configured without explicitly setting either global limit. When a project's effective file limit is `1`, `fileSetup` is optional and its files can share the `setup` return value. Cases are not automatically divided between projects. If two projects select the same YAML file, each runs it once. Use non-overlapping `files` or `tags` rules to split the work. Legacy `tasks/flow` YAML still runs through `midscene`. Its `concurrent` / `--concurrent`, setup-file behavior, and browser reuse remain unchanged; those settings are handled separately from native Test's `setup` and `fileSetup`. See [Migrate to Midscene Test](/migrate-to-midscene-test.md). ## Timeouts and cancellation ### Timeout settings | Configuration | Scope | Default | | ---------------------- | ---------------------------------------------------------------------------------- | ----------- | | `test.testTimeout` | One step; overridden by the step's `$` settings | `120000` ms | | `test.setupTimeout` | Each project `setup` or `fileSetup`, including device waits | `120000` ms | | `test.teardownTimeout` | Each cleanup scope, including hooks, waiting for operations, and cleanup callbacks | `30000` ms | Preparation and cleanup limits also apply when concurrency settings are omitted. After cancellation or `bail`, cleanup scopes share a shutdown deadline based on `teardownTimeout`. ### Cancellation and cleanup A step timeout aborts that step's `signal`. The CLI cancels the run on `SIGINT` (such as Ctrl+C) or `SIGTERM`. Nodes must pass `signal` to APIs that support cancellation or check its state; asynchronous operations do not stop automatically. See [Asynchronous operations, errors, and cancellation](/midscene-test/extend.md#asynchronous-operations-errors-and-cancellation). After interruption, the framework still attempts cleanup. Nodes in `afterEach` and `afterAll` use a cleanup signal that has not been aborted. Step timeouts still apply, and cleanup cannot overlap an unfinished operation on the same Agent. Cleanup Nodes should handle partially completed preparation. Callbacks registered with `onTeardown()` do not receive a new signal. Avoid reusing the original step's signal, which may already be aborted. Timeouts bound the wait for results. If operations or cleanup remain unfinished, the framework records `cleanup pending`, keeps tracking resources, and releases them after operations actually finish. No new files start in this state. See [Handling failures](/midscene-test/execution.md#handling-failures) for the full rules. ## Usage notes - **Configure what you need.** Use only `fileSetup` when there are no shared resources. With an effective file limit of `1`, omit it to share the `setup` result across files. - **Concurrent files need isolation.** An effective file limit above `1`, including unlimited, requires `fileSetup`, even if only one file is selected. Use separate pages, Agents, and devices; isolate backend accounts and data separately. - **Retries do not repeat preparation.** `setup`, `fileSetup`, and `beforeAll` do not rerun. Reset state needed for each attempt in `beforeEach`. - **Register cleanup immediately.** Call `onTeardown()` after creating each resource. File cleanup precedes shared project cleanup; cleanup code must tolerate partial preparation. --- url: /midscene-test/extend.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Develop custom Nodes Custom Nodes turn business operations into steps that test authors can call from YAML. This guide covers defining and validating inputs, sharing data between Nodes, and handling execution and cleanup. For platform setup, Agent integration, and execution settings, see [Configure test projects](/midscene-test/configuration.md). - [Register a Node](#register-custom-business-nodes): define an operation, call it from YAML, and verify registration through the generated Node Spec. - [Node execution arguments](#node-execution-arguments): distinguish business inputs from framework step settings. - [Share context across Nodes](#share-context-across-nodes): create, read, and reset shared test data. - [Advanced usage](#advanced-usage): return results, handle errors and cancellation, and clean up resources. ## Register custom business Nodes A custom Node receives parameters from YAML and performs an operation. This example creates a test user fixture and saves it as a JSON file for a test service or data import step to load. ### 1. Define and register the Node Create `midscene.config.ts`: ```ts filename=midscene.config.ts import { randomUUID } from 'node:crypto'; import { mkdir, writeFile } from 'node:fs/promises'; import { defineNode, z } from '@midscene/test'; import { defineTestProject } from '@midscene/test/config'; const createUser = defineNode({ name: 'user.create', description: 'Create a test user fixture.', inputSchema: z.strictObject({ name: z.string().min(1).describe('Test user name.'), email: z.string().email().describe('Test user email.'), }), async execute({ input }) { const user = { id: randomUUID(), name: input.name, email: input.email }; const filePath = `fixtures/users/${user.id}.json`; await mkdir('fixtures/users', { recursive: true }); await writeFile(filePath, JSON.stringify(user, null, 2)); }, }); export default defineTestProject({ nodes: [createUser], }); ``` `name` is the operation name used in YAML. `inputSchema` defines its parameters, and `execute({ input })` receives the validated values. Add the Node to `nodes` to make it available to test cases. In an existing project, append it to the existing `nodes` array. `inputSchema` is optional, but defining it lets Midscene Test validate parameters before calling `execute()`. In this example, `z.string().min(1)` requires a non-empty name, `.email()` validates the email format, and `z.strictObject()` rejects unknown fields. Invalid input produces a `NodeInputValidationError`. TypeScript infers the type of `input` from the schema. Field descriptions written with `.describe()` appear in the generated Node Spec. ### 2. Call the Node from YAML Create `cases/user.yaml`: ```yaml filename=cases/user.yaml cases: - name: Create test user data steps: - user.create: name: Alice email: alice@example.com ``` Midscene Test reads the YAML, finds the Node named `user.create`, and calls its `execute()` with `input` set to `{ name: "Alice", email: "alice@example.com" }`. The Node does not need to parse the YAML itself. The example uses `async execute({ input })` and `await` to wait for the file write. A failed write throws an error and fails the Node. This creates a local fixture; to create a user in your application, replace the file write with your test data API or database call. ### 3. Generate a Node Spec to verify registration After saving the configuration, generate the Node Spec: ```bash pnpm exec midscene-test nodes ``` The command loads the project configuration and writes `midscene-node-spec.md` to the current directory. When `projects` is declared, it generates `midscene-node-spec.<project-name>.md` for each Project instead. Check that the Spec includes: - `user.create` in the available Nodes. - The description “Create a test user fixture.” - The `name` and `email` input fields and their descriptions. This verifies that the Node is registered and its input schema can be exported; it does not execute the Node or create user data. After changing Node definitions or registrations, you can regenerate the Spec for case authors and AI Agents to consult. For complete usage, see [Generate the current Project's Node Spec](/midscene-test/writing.md#generate-the-current-projects-node-spec). ### Declare string shorthand Set `stringInputKey` to the input field populated by a string value. Other required fields must still satisfy the schema, so shorthand works well for a single required string input: ```ts const logMessage = defineNode({ name: 'message.log', stringInputKey: 'message', inputSchema: z.strictObject({ message: z.string() }), execute({ input }) { return { summary: input.message }; }, }); ``` ```yaml steps: - message.log: Checkout started ``` Register `logMessage` in `nodes` and regenerate the Spec. Omitting `stringInputKey` or setting it to `false` disables shorthand; callers must use object inputs. ## Node execution arguments Midscene Test calls `execute()` with an object containing the parameters and runtime information for the current invocation. Use destructuring, such as `execute({ input, $, context })`, to access the fields you need. ### Business inputs and step settings `input` contains the business parameters defined by the Node's `inputSchema`. `$` contains step settings handled by the framework, such as timeout and whether to continue after an error. For example, add step settings to the `user.create` invocation above: ```yaml steps: - user.create: name: Alice email: alice@example.com $: timeout: 30000 continue-on-error: true ``` The framework separates `$` from the business inputs and normalizes its field names. Inside `execute({ input, $ })`, the fields have these values: ```ts input.name; // 'Alice' input.email; // 'alice@example.com' $.timeoutMs; // 30000 $.continueOnError; // true ``` `inputSchema` only needs to declare `name` and `email`; `$` is not included in `input`. The framework enforces the timeout and continuation policy. `continue-on-error` allows later steps in the current phase to run after a failure, subject to [resource safety checks](/midscene-test/execution.md#handling-failures), but the failed step still makes the case fail. ### Available execution fields The argument object passed to `execute()` contains these commonly used fields: - `input`: business parameters passed from YAML and validated by Zod. - `$`: general Step properties controlled by Midscene Test, such as `timeoutMs` and `continueOnError`. - `signal`: an `AbortSignal` triggered by a timeout or cancellation. Use it in asynchronous requests or long-running tasks to exit early and cleanly. - `context`: the file environment returned by `fileSetup`, or the project `setup` return value when no `fileSetup` is configured. - `onTeardown()`: registers cleanup functions for resources created by the current Node. Cleanup can use attempt or Document scope and runs in LIFO order. - `scope`: identifies the current Node execution boundary as either `case` or `document`. - `case` or `document`: detailed runtime information for the current execution position. The `context` field provides access to runtime resources and test state. The next section explains how to use it to share data between Nodes. ## Share context across Nodes Each Node execution is a separate invocation; the framework does not automatically pass the result of one invocation to the next. When a workflow spans several Nodes, they may need to use the same test data. An order refund test, for example, creates an order, opens its refund page, and deletes the order after the case finishes. The following example follows that data through the workflow. ### Create the shared context This example uses only `fileSetup` to create a Browser, page, and `context` shared by each file's Nodes. With no shared resources, it needs no `setup`. To share a Browser, see the [resource isolation example](/midscene-test/configuration.md#isolate-resources-with-filesetup). The imported `orderService` is your own test data service implementing `create` and `remove`. Replace the application URL with your test environment URL. ```ts filename=setup.ts import { defineFileSetup } from '@midscene/test/config'; import { chromium, type Page } from 'playwright'; import { orderService } from './order-service'; export interface Context { appBaseUrl: string; page: Page; orderId?: string; // Share test state across Nodes orderService: { create(input: { status: 'paid' }): Promise<{ id: string }>; remove(orderId: string): Promise<void>; }; } export const fileSetup = defineFileSetup<Context, undefined>({ name: 'refund', async setup({ onTeardown }) { const browser = await chromium.launch(); onTeardown(() => browser.close()); const page = await browser.newPage(); const context: Context = { page, appBaseUrl: 'https://yoursite.com', orderService, }; return context; }, }); ``` Each file has its own `context`. A later Node writes `orderId` after creating the order. ### Write data to the context Next, create `nodes.ts`. `order.prepare` uses the order service in `context` to create an order, then writes its ID to `context.orderId` for later Nodes: ```ts filename=nodes.ts import { defineNode, z } from '@midscene/test'; import type { Context } from './setup'; const emptyInputSchema = z.strictObject({}); const prepareOrderInputSchema = z.strictObject({ status: z.literal('paid').describe('Status of the order to create.'), }); // 1. Prepare the order environment const prepareOrder = defineNode< typeof prepareOrderInputSchema, { orderId: string }, Context >({ name: 'order.prepare', description: 'Call the order service to create a test order.', inputSchema: prepareOrderInputSchema, async execute({ input, context, onTeardown }) { const order = await context.orderService.create(input); context.orderId = order.id; // Save the ID in the context onTeardown(async () => { await context.orderService.remove(order.id); delete context.orderId; }); return { summary: `Created test order ${order.id}`, data: { orderId: order.id }, }; }, }); ``` `context.orderId = order.id` updates the shared object so later Nodes can read the ID. Returning `data` does not write it to `context` automatically. After creating the order, `onTeardown()` registers a callback that deletes this order and clears the saved ID. The callback captures `order.id`, so it cleans up the order created by this invocation. Creation and cleanup stay in the same Node; YAML does not need a separate cleanup step. ### Read data in a later Node `browser.openRefundPage` reads the saved ID to navigate to the refund page. It reports an error if the order ID is missing. ```ts filename=nodes.ts const getOrderId = (context: Context) => { if (!context.orderId) { throw new Error('The test order has not been created.'); } return context.orderId; }; // 2. Access the saved order state const openRefundPage = defineNode< typeof emptyInputSchema, unknown, Context >({ name: 'browser.openRefundPage', description: "Open the current test order's refund page.", inputSchema: emptyInputSchema, async execute({ context }) { const orderId = getOrderId(context); await context.page.goto(`${context.appBaseUrl}/orders/${orderId}/refund`); }, }); export const refundNodes = [prepareOrder, openRefundPage]; ``` Register `fileSetup` and the Nodes together so each Node receives the current file's returned object as `context`: ```ts filename=midscene.config.ts import { defineTestProject } from '@midscene/test/config'; import { refundNodes } from './nodes'; import { fileSetup, type Context } from './setup'; export default defineTestProject<Context, undefined>({ fileSetup, nodes: refundNodes, }); ``` In YAML, call `order.prepare` from `beforeEach`, then use the saved order ID in the case steps: ```yaml beforeEach: - order.prepare: status: paid cases: - name: Open the refund page steps: - browser.openRefundPage: {} ``` The registered callback runs after the case's `afterEach` phase, even when no `afterEach` steps are declared. If a later preparation step or case step fails, the framework still runs the registered cleanup. Each retry has its own cleanup scope. If order creation fails before the callback is registered, there is no cleanup callback for that invocation. For Agent integration and platform resources, see [Configure test projects](/midscene-test/configuration.md). ## Advanced usage This section covers execution results, errors, cancellation, and cleanup within a Node. ### Record execution results The order preparation Node also returns `summary` and `data`. `summary` describes the operation for the report, while `data` holds structured output. Both are optional; a Node can finish without returning a result. These values are saved in the run result, independently of the shared `context`. ### Asynchronous operations, errors, and cancellation Use `async execute()` and `await` for asynchronous work. Throw an error when an operation fails. Midscene Test passes an `AbortSignal` as `signal` when executing a Node. Pass it to APIs that support cancellation, such as `fetch(url, { signal })`. For long-running loops, check `signal.throwIfAborted()` between iterations. This lets the operation stop when the step times out or the run is cancelled. With file concurrency, a Node or `fileSetup` that confirms a shared project resource has failed must explicitly report `PROJECT_RESOURCE_ERROR` to stop other files in that project. Throw `WorkflowError` from `@midscene/test` with this `code`, either directly or nested in `cause` or `AggregateError.errors`. A Browser can belong to one file or be shared by the project; the framework does not infer ownership from closure messages. Unclassified Browser errors are treated as file errors. See [Handling failures](/midscene-test/execution.md#handling-failures) for the affected scope. ### Resource lifecycle and cleanup When a Node creates a resource, register its cleanup with `onTeardown()`. The execution phase determines when that cleanup runs. Cleanup has these lifetimes: - Cleanup registered by Nodes in `beforeEach`, case `steps`, or `afterEach` runs after that execution's `afterEach`. Each retry has its own cleanup scope. - Cleanup registered by Nodes in `beforeAll` or `afterAll` runs after the current file's `afterAll`. Within each scope, cleanup functions run in reverse registration order, or LIFO (last in, first out). Nodes can use them to release resources they created or finalize reports. Registering cleanup does not automatically create a new Agent or reset caches; those behaviors depend on the project implementation. If a Node times out but has not stopped, registered resource cleanup is deferred to avoid disposing of resources still in use. If a cleanup callback throws, remaining callbacks are still attempted; if a callback does not finish, subsequent callbacks wait for it. The framework bounds the wait for cleanup results and returns a `pending` snapshot if the limit is exceeded. Resources remain quarantined rather than being treated as cleaned up. See [Timeouts and cancellation](/midscene-test/execution.md#timeouts-and-cancellation) for the waiting limits. When a test run is interrupted, the framework still attempts to run `afterEach`, `afterAll`, and cleanup functions registered with `onTeardown()`. See [Timeouts and cancellation](/midscene-test/execution.md#timeouts-and-cancellation) for details. Project-level browser and Agent cleanup is covered in [Create and clean up shared resources with setup](/midscene-test/configuration.md#create-and-clean-up-shared-resources-with-setup). --- url: /midscene-test/overview.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Midscene Test overview Through extensive practice, we found that once vision models handle UI interaction and verification, what remains in a test case is pure intent. At that point, traditional test frameworks built around hand-coded locators and page objects become unnecessary overhead. Midscene Test (`@midscene/test`) starts from that premise to rethink what an AI-native E2E framework should optimize for: expressing test cases as pure intent, encapsulating deterministic business operations as reusable capabilities, and letting engineers and AI agents maintain the same test suite together. [Get started with Midscene Test](/midscene-test/use.md) ## Interactive and business operations in one YAML file {#ai-and-nodes} Each YAML step calls a Node: an AI, platform, or custom business operation. Compose them into a test case. cases/refund.yamlInteractiveBusiness ```` 1beforeEach:2 - order.prepare: { status: paid }Business3 - gotoUrl: ${shopUrl}/orders/latestBusiness45cases:6 - name: A paid order supports a full refund7 steps:8 - aiAct: Apply for a full refund and submitInteractive9 - aiAssert: The page shows that the refund was submittedInteractive10 - order.checkRefund: { status: refunding }Business1112afterEach:13 - clearCookies: {}Business ```` Interactive**Interactive operations**APIs such as aiAct and aiAssert read the screen and follow natural-language instructions. Business**Business operations**Custom Nodes use TypeScript to prepare test data, check APIs, and clean up resources. ## Separate intent from business logic, maintained by people and AI {#nodes-and-spec} Wrap reusable business logic in custom Nodes. Midscene Test generates a Markdown Node Spec listing every Node and its inputs, so QA engineers and AI agents can write cases without reading TypeScript. [Learn how to develop custom Nodes](/midscene-test/extend.md) 1. nodes/order.ts ```typescript defineNode({ name: 'order.prepare', description: "Create a test order", inputSchema: z.strictObject({ status: z.literal('paid'), }), async execute({ input }) { await orders.create(input); }, }); ``` 1. midscene-node-spec.md ````markdown ### order.prepare Create a test order - status: "paid" ```` 1. case.yaml ```yaml steps: - order.prepare: status: paid ``` ## Replay every action in visual reports {#visual-reports} Every run generates an interactive HTML report. Inspect the full lifecycle step tree, drill into each Agent step’s `Plan`, `Locate`, and action timings, and scrub through the screenshot timeline to replay exactly what happened on screen. [Explore reporting](/midscene-test/running.md#output-and-exit-codes) Midscene.js/Overview/PassedFind headphones under $100 10.6s28.5K tokensVisualYAML Steps SETUP · 2 1gotoUrl120ms 2prepareCatalog18ms STEPS · 3 3**aiAct** Search for headphones3.8s 4**aiWaitFor** Filtered results visible1.4s 5**aiAssert** Each item costs < $1002.1s TEARDOWN · 1 6clearCookies4ms #3**aiAct**Passed Type "headphones" in the search box and click Search ExecutionTime Plan1.82s Locate0.42s Input0.96s Tap0.55s Elapsed3.75s Model2.24s RecordPlan · 1.82s 2s 4s 6s 8s Midscene Shop Search products Search Ready to search **Wireless Headphones**$89 Add to cart ## Engineering foundation built for visual agents {#framework-capabilities} Midscene Test ships with the runtime and CI capabilities needed to run visual agents reliably at scale: multi-project orchestration, isolated concurrency, guaranteed teardown, GitHub Actions integration, and machine-readable outputs. [### Multi-project orchestration Run web, Android, iOS, and desktop suites from one config with --project and tag filtering. ](/midscene-test/configuration)[### Concurrency and isolation Run YAML files in parallel via maxConcurrentFiles, each with its own isolated page, Agent, or device. ](/midscene-test/execution#concurrency-and-isolation)[### Lifecycle hooks and cleanup Project, file, and case hooks with reverse-order cleanup that still runs on timeout or Ctrl+C. ](/midscene-test/execution#project-lifecycle)[### Retries and timeouts Rerun failed cases after cleanup, with step timeouts, continue-on-error, and bail. ](/midscene-test/execution#handling-failures)[### CI & GitHub Actions Official midscene-action with PR summaries, #runner-step=last-error deep links, and live badges. ](/midscene-test/running#run-in-github-actions)[### AI-readable outputs & diagnostics Emit summary.json and result.md for scripts and AI agents, with model verify and token tracking. ](/midscene-test/running#output-and-exit-codes) ## Next steps - [Create a test project](/midscene-test/use.md): create, run, change a case, and inspect results. - [Write YAML cases](/midscene-test/writing.md): author and maintain cases. - [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md): inspect universal AI capabilities and platform-specific built-in operations. - [Configure test projects](/midscene-test/configuration.md): manage environment variables, case files, and execution projects. - [Develop custom Nodes](/midscene-test/extend.md): encapsulate reusable business operations. - [Run tests](/midscene-test/running.md) and [lifecycle and concurrency](/midscene-test/execution.md): control execution modes, concurrency strategies, and inspect test reports and diagnostics. - [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions): connect to CI workflows. :::info Migrating from the legacy YAML runner The legacy `tasks/flow` YAML runner is in maintenance mode, receiving compatibility updates and necessary fixes. Use Midscene Test for new projects and cases. Existing projects can continue using the `midscene` command; see [Migrate to Midscene Test](/migrate-to-midscene-test.md) when switching to `midscene-test`. ::: --- url: /midscene-test/running.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Run tests ## Basic usage {#run-tests} Run YAML test cases from the project root: ```bash pnpm exec midscene-test ``` ### Specify a test case directory or file With a config, a file or directory argument filters the selected cases. Full-suite, single-file, and subdirectory runs share the same project configuration. Run these commands from the project root: ```bash pnpm exec midscene-test pnpm exec midscene-test ./cases/order.yaml pnpm exec midscene-test ./cases/smoke ``` They share the configured Nodes, Execution Projects, and default output location. **Configuration and path resolution** | Input | Resolution rule | | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | Default config | Search cwd only for `midscene.config.ts` or `midscene.config.mjs`. | | `--config` | Resolve relative paths from cwd; absolute paths are also supported. | | Test root | Use the config directory, or cwd when no config is found. | | File or directory argument | Resolve from cwd. Filter configured cases when a config exists; otherwise discover and collect cases from the selected file or directory. | | Paths in config | Resolve `files.include`, `files.exclude`, and `output.reportDir` from the test root. | | `--result-dir` | Resolve relative paths from cwd. | Default discovery checks cwd only. When running from a child directory, select the project config explicitly: ```bash cd cases pnpm exec midscene-test ./order.yaml --config ../midscene.config.ts ``` The parent directory containing the config becomes the test root. Default output remains in that directory's `midscene_run`. Without a config, a file argument collects the selected YAML, and a directory argument discovers YAML files in that directory. Paths outside cwd are supported. With no argument, discovery starts at cwd. Configs beside the selected input are not loaded. Default artifacts stay under `cwd/midscene_run`. Without a config, no Nodes are registered. YAML that references Nodes still needs a config that registers them. Legacy `tasks/flow` YAML is run with `midscene`, not `midscene-test`. **File and tag selection** Scaffolded projects use `files.include` to select `.yaml` and `.yml` files under `cases/`. Without `files`, the framework discovers YAML files recursively under the test root, ignoring `node_modules`, `.git`, and run artifact directories. When a config is loaded, the positional path further narrows the selection. `--project`, file inclusion/exclusion rules, and tags still apply, including to explicitly named files. With a positional path, the command fails with a selection error if no Project has matching cases. An empty selection in one Project does not prevent other Projects from running. Without a positional path, existing behavior is preserved: if files exist but tags exclude every case, the command can succeed. Other errors, such as failure to discover files, still fail the run. **Switching projects and SDK calls** To run another project, change into its directory or select its config with `--config`. A directory argument does not change config discovery. The SDK accepts these options: - `projectRoot`: the default config discovery directory; defaults to `cwd`. - `testPath`: a file or directory filter, resolved relative to `cwd`. - `configPath`: an explicit config, resolved relative to `cwd`. Its directory becomes the test root. These rules apply to test runs. The `nodes` subcommand retains its existing directory and config resolution rules. ### Migrate config discovery Default config discovery checks the current working directory (cwd) only. It does not search parent directories or switch configs when you specify a test directory. If an existing command relies on a directory argument to load another project's config: ```bash pnpm exec midscene-test ./other-project ``` Select that config explicitly: ```bash pnpm exec midscene-test --config ./other-project/midscene.config.ts ``` Alternatively, change into `other-project` and run `pnpm exec midscene-test`. To run one file from the original working directory: ```bash pnpm exec midscene-test ./other-project/cases/order.yaml --config ./other-project/midscene.config.ts ``` Check these paths when upgrading: - `files.include`, `files.exclude`, and `output.reportDir` resolve from the config directory. If your config is in `config/` and your tests are in a sibling `cases/` directory, move the config to their common parent and set `files.include` to `['cases/**/*.yaml']`. - Default artifacts go to `midscene_run` inside the config directory. Update CI artifact collection paths, or move the config to the project root. - A relative `--config` path now resolves from cwd, even when you specify a test file or directory. Relative test input and `--result-dir` paths also resolve from cwd. Without a config, YAML discovery and collection remain available, but referenced Nodes must be registered through a config. This does not enable arbitrary YAML execution without configuration. ### Filter execution targets and configuration files If a project defines multiple platforms or environments, you can use `--project` to run specific Execution Projects, or use `--config` to specify a custom configuration file: ```bash # Run only the android-smoke and ios-regression Execution Projects pnpm exec midscene-test --project android-smoke --project ios-regression # Run tests with a specific configuration file pnpm exec midscene-test --config ./config/midscene.config.ts ``` When generating the Node Spec for a specific Execution Project, you can also use `--project`: ```bash pnpm exec midscene-test nodes --project android-smoke ``` ## Output and exit codes ### Terminal output mode By default, the terminal prints summarized execution results grouped by Case. To view detailed step diagnostics, use the `verbose` reporter. Run `--help` to view all supported CLI options: ```bash # Show detailed step diagnostics pnpm exec midscene-test --reporter verbose # View all CLI options pnpm exec midscene-test --help ``` ### Result files and report paths Each run generates two types of output artifacts. Their exact paths are printed at the end of the terminal output as `Summary:` and `Report:`: - **Result files**: Saved in `midscene_run/test-results/<runId>/` by default, including the readable `result.md`, machine-readable `summary.json`, and diagnostic records. Set `--result-dir` to change the results root; relative paths use the command's working directory: ```bash pnpm exec midscene-test --result-dir ./test-results ``` - **HTML report**: Saved in `midscene_run/report/` by default. Open it directly in a browser to inspect case outcomes, screenshots, errors, and replay. Set `output.reportDir` to change the report directory; relative paths use the Test project as their base. Keep the complete results directory for troubleshooting or programmatic analysis. Use the `summary.json` fields produced by your installed version. ### Artifact directory {#unified-artifact-root-and-migration} The default artifact directory is `midscene_run/` in the Test project. Reports are in `report/`; results and diagnostic records are in `test-results/`. Set the `MIDSCENE_RUN_DIR` environment variable to change the artifact directory. Relative paths use the Test project as their base: ```bash MIDSCENE_RUN_DIR="./artifacts" pnpm exec midscene-test ``` In CI: - Update collection rules from `.midscene/test-results` to `midscene_run/test-results`, or your configured results directory. - With the [Midscene GitHub Action](https://github.com/web-infra-dev/midscene-action), set `run-directory` or `MIDSCENE_RUN_DIR`. Execution and artifact collection use the same directory. - Collect files using the printed `Summary:` / `Report:` paths or the SDK's `summaryPath`, `markdownPath`, and `reportPath`. See below for sharing reports. ### Exit codes You can determine the overall outcome of a test run from the CLI exit code: - `0`: All selected cases and lifecycle hooks executed successfully. - `1`: An error occurred during execution (including case step failures, YAML parsing or collection errors, and project-level or file-level lifecycle errors). Even if all case steps pass, the exit code is still `1` if an exception occurs during the cleanup phase. ## Report archiving and URL deep links ### Report archiving Reports default to a single HTML file: `midscene_run/report/midscene-e2e-<runId>.html`. To choose the delivery format, set `output.reportFormat` in `midscene.config.ts`: ```ts output: { reportFormat: 'single-html', // default: open the HTML directly, including offline // reportFormat: 'html-and-external-assets', } ``` When using `html-and-external-assets`, preserve the entire report directory when archiving or uploading, and view it over HTTP. See [Run in GitHub Actions](#run-in-github-actions) for CI artifact configuration. ### Link to a specific step (URL hash) When sharing reports in CI notifications, chat bots, or PR comments, use the `runner-step` URL hash parameter to jump directly to a target Step. Beyond explicit Step IDs, reports support portable selectors: | Selector | Target | | ------------- | -------------------------------------------------------------------- | | `first` | Earliest started Step | | `last` | Most recently completed Step | | `first-error` | Earliest started failed Step, including failed retry attempts | | `last-error` | Most recently completed failed Step, including failed retry attempts | Example: Jump directly to the last failed Step in a report: ```text https://example.com/report/index.html#runner-step=last-error ``` If the Step includes Agent visual replay, append `runner-trace=page` to open the Agent trace in full-screen view: ```text https://example.com/report/index.html#runner-step=last-error&runner-trace=page ``` To limit selection to a specific case, combine with `runner-page=case`, `runner-project=<projectId>`, and `runner-case=<caseKey>`. Use the report's internal `projectId` and the composite Case Key `<projectId>:<documentId>:<caseId>`. URL-encode each parameter value, for example with `URLSearchParams`. To obtain these values, open the target case in the report and copy its URL, then add `runner-step` and, if needed, `runner-trace`. ## Environment loading {#environment-loading} Midscene Test reads model configurations and runtime parameters from system environment variables (`process.env`). You can provide environment variables based on your workflow: ### Local development with .env files - **Scaffolded projects (ready out of the box)**: Projects created via `midscene-test create` already load the `.env` file from the configuration directory in `midscene.config.ts`. Simply create a `.env` file in the project root to get started. - **Handwritten configuration**: When writing a configuration file manually, import `dotenv` at the top of `midscene.config.ts`: ```ts import 'dotenv/config'; ``` When loaded through `dotenv`, existing environment variables in your shell take precedence over values in the `.env` file by default. ### CI / CD environments In continuous integration (such as GitHub Actions) or automated pipelines, you do not need a `.env` file. Simply inject API keys or credentials directly as pipeline environment variables. ### Model connectivity check (model verify) When running `midscene-test model verify` to test model connectivity, the command automatically reads `.env` from the current working directory. To facilitate quick local checks, it prioritizes values in `.env` over matching shell environment variables. When troubleshooting, ensure the settings in `.env` match the model configuration used during test runs. ## Run in GitHub Actions Midscene provides [midscene-action](https://github.com/marketplace/actions/midscene-action) to run Midscene Test in GitHub Actions. - Automatically add test results to the workflow **Summary**. - Save HTML reports and test data as **artifacts** for download. - Optionally publish reports to **Cloudflare Workers** for online previews. For setup instructions, configuration parameters, and complete examples, see [midscene-action on GitHub Marketplace](https://github.com/marketplace/actions/midscene-action). ### Show test results with a badge The official [Midscene Test badge service](https://badge.midscenejs.com) renders pass/fail counts as an SVG badge that can be embedded in any Markdown file, such as your repository README: ```md ![Midscene Test: 42 passed, 3 failed](https://badge.midscenejs.com/e2e?pass=42&fail=3) ``` ![Midscene Test: 42 passed, 3 failed](https://badge.midscenejs.com/e2e?pass=42\&fail=3) A two-line card style is also available, with light and dark themes: ![Midscene Test: 42 passed, 3 failed](https://badge.midscenejs.com/e2e?pass=42\&fail=3\&style=card\&theme=light) The counts come entirely from the `pass` and `fail` query parameters; the service does not read CI data or reports, so you update the URL or generate it in your workflow after each run. When running inside GitHub Actions, the job Summary already includes a badge generated from the current run's results, and the same line appears in `result.md`, ready to copy. For all supported parameters and styles — including `flat`, `large`, `card`, the dark theme, and the static "E2E by Midscene.js" attribution badge — see the [badge service homepage](https://badge.midscenejs.com), which provides live previews and ready-to-paste Markdown. --- url: /midscene-test/use.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Create a Midscene Test E2E project Create a project, run the TodoMVC example, then change a case. This guide follows the Web starter; mobile and desktop users can select their platform template. For a first run on a specific platform, [Get started](/get-started.md?scene=test) walks you through device, model, and project setup for your combination and ends with a passing example. ## Create a project ### 1. Generate the project and install dependencies Prepare Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm, then run: ```bash pnpm dlx @midscene/test create my-tests --platform web --package-manager pnpm cd my-tests ``` Follow the installation prompt. To choose a platform interactively, run `pnpm dlx @midscene/test create`, then enter the selected directory. See the [create command reference](#create-command-reference) for other options. The main files are: ```text my-tests/ ├── cases/todo.yaml # TodoMVC cases ├── nodes/todo.ts # Web custom Nodes for setup, checks, and capture ├── midscene.config.ts # Platform configuration and Node registration ├── midscene-node-spec.web.md # Node Spec generated after installation ├── package.json ├── tsconfig.json ├── .env.example ├── README.md └── README.zh.md ``` This step only generates project files and the spec file without running any tests, so you do not need a model API Key, browser, or device yet. The generated README in the project folder provides more details on platform-specific setup. ### 2. Configure the model and runtime environment Copy `.env.example` to `.env` and follow [Use a model API key](/model-api-setup.md) to set your model name, service URL, and API Key. To use a ChatGPT subscription instead, follow [Use a ChatGPT subscription](/chatgpt-subscription.md#cli--sdk): sign in once, then set `MIDSCENE_MODEL_AUTH_MODE`, `MIDSCENE_MODEL_NAME`, and `MIDSCENE_MODEL_FAMILY` and leave the base URL and API Key empty. Verify model connectivity and Midscene compatibility before running tests: ```bash pnpm exec midscene-test model verify pnpm exec midscene-test model verify --help ``` The command reads `.env` from the current working directory and overrides existing shell environment variables. It does not require a browser or device. See [Model advanced configuration and debugging](/model-config.md#verify-model-connectivity) for details. For Web, also install Chromium: ```bash pnpm exec playwright install chromium ``` If you targeted a platform other than Web during project creation, please complete its respective runtime prerequisites below before running your tests: | Platform | Argument value | Runtime prerequisites | Environment setup guide | | --------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | | Android | `android` | Connect a device. Optionally select it with `ANDROID_DEVICE_ID`. | [Setup guide](/platforms/android.md) | | iOS | `ios` | Start WebDriverAgent. Use `WDA_HOST` and `WDA_PORT` for direct access, or `WDA_BASE_URL` for a gateway. Set `WDA_MJPEG_URL` for a remote video stream, or `WDA_MJPEG_PORT` for a direct connection. | [Setup guide](/platforms/ios.md) | | HarmonyOS | `harmony` | Check the connection with `hdc list targets`. Optionally set `HARMONY_DEVICE_ID`; set `HDC_HOME` if HDC is not on PATH. | [Setup guide](/platforms/harmonyos.md) | | Desktop | `computer` | Install dependencies and grant permissions. Optionally set `COMPUTER_DISPLAY_ID`. Headless Linux also requires Xvfb and `MIDSCENE_COMPUTER_HEADLESS_LINUX`. | [Setup guide](/platforms/desktop.md) | ### 3. Run the example and inspect results ```bash pnpm test ``` The example uses the public React TodoMVC page, which must be reachable from the browser or device. The terminal prints results and a `Report:` path. Open that HTML report and select a case and step to inspect screenshots, inputs, outputs, and errors. Reports default to `midscene_run/report/`. If installation fails, retry `pnpm install`. Resolve model verification errors before testing; use the platform guides above for device connection issues. For test execution options and report sharing, see [Run tests](/midscene-test/running.md). ## Change a case Open `cases/todo.yaml`. The Web starter resets and seeds three todos in `beforeEach`. Keep the setup and cleanup hooks, and replace `cases` with: ```yaml cases: - name: Complete a todo steps: - aiAct: Mark the Todo named "Learn JS today" as completed. - aiAssert: The Todo named "Learn JS today" has a checked checkbox and strikethrough text. ``` Run `pnpm test` again and confirm that the case passes in the report. `aiAct` describes the operation; `aiAssert` explicitly checks its result. Mobile and desktop starters prepare state differently. Preserve their initial-state requirements and follow the generated README when editing those examples. ## Move from the example to your own tests Each YAML operation is a Node. Installation generates `midscene-node-spec.web.md`, listing the operations and inputs available in this project; other platforms use their own filenames. After adding operations or changing configuration, run `pnpm run nodes` to refresh the Spec. An AI assistant can read the current Node Spec and `cases/todo.yaml`, then use your target page, actions, and expected results to draft cases using registered Nodes. Review its steps, assertions, and test data before running them and checking the report. If an operation is missing, implement and register a Node, then regenerate the Spec. Continue according to your task: - [Write YAML cases](/midscene-test/writing.md): inputs, variables, tags, hooks, and case design. - [Configure test projects](/midscene-test/configuration.md): runtime resources, Nodes, files, and execution projects. - [Develop custom Nodes](/midscene-test/extend.md): business APIs and test data operations. - [Run tests and CLI reference](/midscene-test/running.md): targets, diagnostics, and result files. - [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions): connect the project to CI. ## Create command reference Show creation options and more examples | Argument | Description | | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `[directory]` | Project directory, relative to the current directory or an absolute path. Use `.` for the current directory. If omitted, the command prompts for it. Existing files are not overwritten. | | `--platform <value>` | Platform: `web` (Playwright), `android`, `ios`, `harmony` (HarmonyOS), or `computer` (desktop). If omitted, the command prompts for it. | | `--package-manager <value>` | Package manager: `npm` or `pnpm`. If omitted, the command prompts in an interactive terminal; otherwise, it detects the invoking package manager and falls back to `npm`. | | `--yes`, `-y` | Disable prompts and install dependencies. You must supply the directory and `--platform`. Combine with `--skip-install` to generate files only. | | `--skip-install` | Generate files without installing dependencies or generating a Node Spec. Run the install command later to generate the Spec. | | `--help`, `-h` | Show command help and examples. | Each platform currently has one starter, selected with `--platform`. All starters use native `cases/steps` Test files. In a non-interactive environment such as CI, you must supply the directory and `--platform`; dependencies are installed unless `--skip-install` is set. Common examples: ```bash # Create an iOS project and install dependencies without prompts pnpm dlx @midscene/test create my-ios-tests --platform ios --package-manager pnpm --yes # Generate Web project files only pnpm dlx @midscene/test create my-web-tests --platform web --package-manager pnpm --skip-install # Show all arguments pnpm dlx @midscene/test create --help ``` --- url: /midscene-test/writing.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Author YAML cases ## A typical YAML file A YAML file can contain multiple test cases, along with setup or cleanup steps. Here is a typical example of a store search workflow: it opens the home page before each Case, searches for a product, and verifies the results. Replace the URL and product name with your actual application details: ```yaml filename=cases/search.yaml beforeEach: - gotoUrl: https://your-shop.example cases: - name: Search for a product steps: - aiAct: Enter "mug" in the search box and click the Search button - aiAssert: The search results include mugs ``` In Midscene Test, we follow these terminology definitions: - **Workflow Document**: The entire YAML file. - **Case**: An individual test case listed under `cases`. - **Step**: A single operation within `steps` (or within lifecycle hooks), which invokes exactly one Node. - **Hook**: Life cycle steps (`beforeAll`, `beforeEach`, `afterEach`, `afterAll`) that run around Cases. This example uses string shorthand: text after `gotoUrl` becomes `url`, while text after `aiAct` and `aiAssert` becomes `prompt`. To supply additional parameters, use the object form shown below. Check the project Node Spec for shorthand support. ## Test case design conventions {#test-case-design-conventions} Midscene Test uses sequential execution and explicit state sharing to make each Node's inputs, execution context, and dependencies clear. YAML cases follow these design choices: - **Execute in declaration order**: YAML describes a linear sequence of test steps, without DAG, branch, or loop syntax. For scenarios that require complex orchestration, we recommend building YAML script generation at a higher layer. That layer resolves the orchestration into an explicit sequence of steps for Midscene Test to execute. - **Each statement (step) is stateless and independent**: Each step is a fully self-contained Node invocation, without any implicit state or output propagation between steps (there is no syntax to reference previous step outputs in YAML). Each step relies solely on its declared inputs and the project-level `context`. If you need to share data explicitly across steps, implement custom Nodes that read and write to the project's shared `context`. For example, the following assertion incorrectly refers to "the icon from the previous step", relying on the previous instruction to identify its target: ```yaml steps: - aiAct: Click the favorite star on the product details page to activate it # ❌ Incorrect: the assertion does not inherit the previous instruction's context, so "the icon from the previous step" does not identify its target. - aiAssert: The icon from the previous step is active ``` Name the target and its expected state explicitly so the assertion expresses the complete check on its own: ```yaml steps: - aiAct: Click the favorite star on the product details page to activate it - aiAssert: The favorite star on the product details page is active ``` The interface retains the effects of previous actions, but each Node's instruction should describe its target independently, without references such as "the previous step" or "that item". ## Use Nodes Midscene Test calls each capability you can invoke from YAML a **Node**. Nodes can be called from Case `steps` or from [lifecycle hooks](/midscene-test/execution.md#yaml-lifecycle-hooks) such as `beforeEach` and `afterEach`, using the same syntax. Midscene Test injects capabilities from the Midscene GUI Agent: `aiAct` operates the interface from natural-language instructions, `aiAssert` checks an expected result, and `aiWaitFor` waits for an observable condition; it also includes the framework-provided `wait` to pause for a specified duration. Alongside these GUI Agent capabilities, Midscene provides platform-specific operations. For example: - **Web**: `gotoUrl` opens a page, `setCookies` sets cookies, and `setViewportSize` adjusts the browser viewport. - **Android**: `launch` starts an app, `back` goes back, `home` returns to the home screen, and `runAdbShell` executes an ADB shell command. The project scaffold explicitly registers the official Nodes for the selected platform. A handwritten `midscene.config.ts` does not register any Nodes implicitly. For the complete list of official operations across platforms and their parameters, see [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md). Developers can also add custom operations, such as preparing a test order through a business API. See [Register custom business Nodes](/midscene-test/extend.md#register-custom-business-nodes). ### Common Nodes Most test steps rely on `aiAct` to perform actions and `aiAssert` to check expected outcomes: | Node | Purpose | What to write | | ---------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | `aiAct` | Perform interface operations from natural language, including multiple actions. | Describe what to do, such as "Search for mugs and add the first product to the cart". | | `aiAssert` | Check whether the interface matches an expectation; fail the step if it does not. | Describe an observable result, such as "The cart contains one mug". | Completing an action does not establish that the test passed. Always use `aiAssert` to check the expected result explicitly. To provide a custom assertion failure message, expand the parameters into an object: ```yaml steps: - aiAct: Search for mugs and add the first product to the cart - aiAssert: prompt: The cart contains one mug message: The cart contents do not match the expected result ``` If you need to supply background knowledge or guidelines (such as test account rules or dialog dismissals) for subsequent AI operations, call `setAIContext` to set or clear context. ### Calling other Nodes Platform operations and custom business Nodes use the same structure: **put parameters beneath the Node name**. Here are examples showing calls with multiple parameters and with no parameters. Place these inside a Case's `steps`: ```yaml steps: - setViewportSize: width: 1440 height: 900 - clearCookies: {} ``` `setViewportSize` takes a parameter object; `clearCookies` takes no parameters, so use `{}`. Both Nodes are provided by Web projects. Consult your project's Node Spec for available mobile, desktop, and custom Nodes and their inputs. For example, if your team registers an `order.create` Node, you can call it as follows. This is a business extension example that must be implemented and registered in your project before use: ```yaml steps: - order.create: sku: midscene-mug quantity: 2 ``` Parameters can also contain nested objects or arrays. When passing a reference image to `aiAct`, the text and images form one `prompt` value, while `options` is a separate field: ```yaml steps: - aiAct: prompt: prompt: Match the page to the reference image images: - name: target state url: ./fixtures/target.png options: deepLocate: true ``` ### Generate the current Project's Node Spec {#generate-the-current-projects-node-spec} The Nodes registered by different platforms, Execution Projects, and package versions can differ. Do not infer the current project's capabilities from another project's examples. `midscene-test nodes` generates Node Specs from the effective registry. The Spec lists available Nodes, their JSON Schema inputs (converted from Zod), string shorthand rules, and matching case files, serving as the source of truth for both people and AI Agents when writing YAML cases. Show an example excerpt of a generated Node Spec ````markdown filename=midscene-node-spec.md # Midscene Test Node Spec ## Available Nodes | Node | Description | | --- | --- | | aiAct | Perform interface operations from natural language. | | aiAssert | Check whether the interface matches an expectation. | | gotoUrl | Navigate the current browser Page to an absolute HTTP(S) URL or a relative path. | ## Node Details ### `gotoUrl` Navigate the current browser Page to an absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL. **String shorthand:** Maps to `{ url: value }`. #### Input Schema ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "url": { "type": "string", "description": "Navigation URL target." } }, "required": [ "url" ] } ``` ```` The scaffold generates the Spec after dependency installation. Regenerate it after changing `agentClass`, top-level `nodes`, `projects[].nodes`, or a Node schema, and after upgrading relevant Midscene packages: ```bash pnpm run nodes ``` You can also run the command directly and specify a test directory, configuration file, or Execution Project: ```bash pnpm exec midscene-test nodes ./e2e --config ../config/midscene.config.ts pnpm exec midscene-test nodes --project android-smoke ``` The command loads project configuration and Node definitions only. It does not run setup or cases and does not call `getAgent`, so it does not need to start a browser, connect a device, or call a model. The Spec is generated output; do not edit it manually. Regenerate it after configuration changes. ## Case configuration and parameters ### Configure timeouts and error handling Use `$` for Step parameters controlled by Midscene Test. Midscene Test does not include these parameters in the Node's `input`. ```yaml steps: - order.create: sku: midscene-mug quantity: 1 $: timeout: 30000 continue-on-error: true ``` The following fields are supported: - `timeout`: Step timeout in milliseconds. - `continue-on-error`: when set to `true`, allows subsequent Steps in the current phase to run after this Step fails. The default is `false`. Unfinished operations or resource cleanup problems still stop execution. `continue-on-error` controls only whether execution continues. If any Step fails, the Case's final status is `failed`. A timeout does not mean the underlying operation has stopped. Before continuing with subsequent Steps in the same phase, the framework waits for cancelled operations to finish, for up to 30 seconds by default. If they remain unfinished, later Steps do not start. This wait is recorded separately and does not consume the next Step's timeout budget. Once the operation finishes, the Agent can be used again, but the case must still verify or reset page and business state. See [Timeouts and cancellation](/midscene-test/execution.md#timeouts-and-cancellation). ### Use Project variables and environment variables Midscene Test recursively resolves Node input before execution: ```yaml steps: - launch: uri: ${appUri} - api.createOrder: baseURL: ${{TEST_API_BASE_URL}} payload: count: ${orderCount} ``` - `${name}` reads a value from the current Execution Project's `variables`. When the placeholder occupies the entire scalar, it preserves the original JSON type. - `${{ENV_NAME}}` reads an environment variable. The result is always a string. - `${{ NAME }}` may include spaces around the name, as in GitHub Actions. Any other `${{ ... }}` content, such as `${{ env.NAME }}`, fails during collection with a hint showing the supported forms. - An object or array variable can be used as a complete value, but it cannot be embedded in a longer string. - An undefined variable fails during collection. Variables are resolved only in Node input, not in `$`. See [Test case design conventions](#test-case-design-conventions) for details on stateless and independent step execution. ### Filter Cases with tags ```yaml cases: - name: Android smoke test for placing an order tags: [smoke, android] steps: - aiAct: Complete the order ``` Framework maintainers configure `tags.include` and `tags.exclude` for each Execution Project. Exclusions always take precedence. When the include list is not empty, a Case is selected if it matches any included tag. ## Next steps - [Execution lifecycle and concurrency](/midscene-test/execution.md): understand the complete execution mechanism of `beforeAll` and `beforeEach`, retry rules, and concurrency strategies. - [Develop custom Nodes](/midscene-test/extend.md): encapsulate reusable business operations. - [Run tests](/midscene-test/running.md): execute cases, inspect diagnostic output, and share reports. --- url: /migrate-to-midscene-test.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Migrate to Midscene Test Legacy YAML and native Midscene Test share the same underlying execution kernel and report page, but they have separate user-facing entries. The `midscene` command owns legacy `tasks/flow` files, YAML batch configuration, and legacy CLI options. The `midscene-test` command owns native `cases/steps` files, TypeScript or JavaScript project configuration, lifecycle hooks, and Nodes. :::info What “legacy YAML” means In this guide, “legacy YAML” specifically means the YAML automation protocol from `@midscene/cli`, not every YAML file. It typically has these characteristics: the workflow has top-level `tasks` and sequences actions through `tasks[].flow`; platform, Agent, and output configuration is written directly in workflow YAML; batch execution uses YAML configuration with fields such as `files`, `setup`, `concurrent`, and `retry`; and the entry command is `midscene`. A file with top-level `cases/steps` and lifecycle hooks that runs through `midscene-test` is native Test YAML, not legacy YAML. The legacy path receives compatibility maintenance and necessary fixes only. It will not receive new syntax, capabilities, configuration fields, or CLI options. Use native Midscene Test for new projects, new cases, and future capability development; existing legacy projects can continue to run and migrate gradually. ::: There are two migration paths: - **Upgrade in place**: keep legacy cases, batch configuration, directory layout, and the `midscene` command unchanged. This adopts the shared execution kernel and new report without changing the input contract. - **Native migration**: rewrite complete files as Test Documents, Cases, and Steps; replace batch YAML with project configuration; then switch those files to `midscene-test`. The complete legacy field reference remains available in [YAML script runner](/yaml-script-runner.md) and [Workflow in YAML format](/automate-with-scripts-in-yaml.md) for maintaining and migrating existing projects. ## Path 1: upgrade legacy execution in place If the project already uses `@midscene/cli`, upgrade it and keep the existing command. `midscene` preserves the legacy input contract while executing through the shared kernel and generating the new report page: ```bash pnpm exec midscene ./flow.yaml pnpm exec midscene --config ./batch.yaml ``` Platform configuration, `agent`, environment interpolation, task continuation, whole-file retries, output files, and summary retain their legacy semantics. Reports use the new Test page; existing HTML files need no conversion, so rerun to regenerate them. Legacy `agent.generateReport: false` remains respected. Legacy flags such as `--files`, `--setup`, `--concurrent`, `--retry`, `--continue-on-error`, `--summary`, `--headed`, `--keep-window`, `--share-browser-context`, `--dotenv-override`, `--dotenv-debug`, `--<target>.<field>`, and `--no-<target>.<field>` remain accepted by `midscene`. They are not `midscene-test` options and do not appear in its help. :::info Command and file boundaries - `midscene` accepts only legacy `tasks/flow` workflow files and YAML batch configuration. - `midscene-test` accepts only native `cases/steps` workflow files and TypeScript or JavaScript project configuration. - A YAML file cannot mix legacy `tasks` with native `cases` or lifecycle hooks. - One command invocation cannot select both formats. During gradual migration, keep them in separate directories or file selections and run two commands. - `--project`, `--result-dir`, and `midscene-test nodes` apply only to native Test projects. Legacy scheduling and platform flags remain on `midscene`. Both commands validate this boundary before creating browser, device, or Agent resources. They report the wrong-format files and point to the matching command instead of silently rerouting them. ::: ## Path 2: migrate to a native Test project Use the following order so each step can be run and compared independently: 1. Run the existing project with `midscene` and save its exit status, summary, and new report as a baseline. 2. Use `pnpm dlx @midscene/test create` to create a Test project for the target platform. Start with the generated `midscene.config.ts` and setup. 3. Map the legacy batch configuration to an Execution Project: put shared resources in `setup`, per-file pages, devices, and Agents in `fileSetup`, and business prerequisites in YAML `beforeAll` or `beforeEach`. 4. Convert one complete `tasks/flow` file to `cases/steps`, move it into the native file selection, and run it with `midscene-test`. Keep unconverted files on `midscene`. 5. Run `pnpm exec midscene-test nodes --project <name>` to generate the current Project's Node Spec, then validate action names, inputs, and string shorthand against it. 6. After all files are converted, remove the legacy batch configuration, legacy command, and legacy-only command-line options. ### Case structure mapping Legacy YAML: ```yaml web: url: https://example.com tasks: - name: Search for a product continueOnError: true flow: - ai: Search for a mug - aiAssert: The results contain a mug errorMessage: The expected product was not found ``` Native Test: ```yaml beforeEach: - gotoUrl: https://example.com cases: - name: Search for a product steps: - aiAct: Search for a mug - aiAssert: prompt: The results contain a mug message: The expected product was not found ``` | Legacy field | Native Test field or mechanism | Notes | | ------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `tasks` | `cases` | One legacy task becomes one Case. | | `tasks[].name` | `cases[].name` | Preserve the name. | | `tasks[].flow` | `cases[].steps` | One flow item becomes one Step. | | `tasks[].continueOnError: true` | Native Case continuation default | `midscene` preserves legacy task continuation. Native Test continues to the next Case by default. | | Omitted `continueOnError` | Legacy failure policy | `midscene` stops the legacy file. There is no native `onFailure` option: put shared prerequisites in `beforeAll` or dependent steps in one Case. | | Initial page or app in a top-level platform field | `setup` / `fileSetup` plus lifecycle Nodes | Create resources according to their sharing scope. Use `gotoUrl`, `launch`, or another Node in `beforeEach` when every Case must return to an initial state. | | No legacy equivalent | `beforeAll`, `beforeEach`, `afterEach`, `afterAll` | Native file and Case lifecycle hooks. | | No legacy equivalent | `cases[].tags` | Select Cases per Execution Project. | Keeping old files unchanged preserves their failure policy. Rewriting them as native Cases adopts native semantics; it is not an exact scheduling equivalence. Step `$: { continue-on-error: true }` continues later Steps in that phase, not later legacy tasks, and does not make a failed Case pass. ### Flow action mapping The legacy runtime keeps accepting the fields in the left column and adapts them internally to the shared kernel. That internal adaptation is not a native Test input contract. When migrating a file, write the native form in the right column and use the Nodes registered in the project's `midscene-node-spec.md` as the source of truth. | Legacy flow field | Native Test Node / input | Migration notes | | ------------------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ai`, `aiAction`, `aiAct`, `instruction` | `aiAct.prompt` | Use `aiAct`; move remaining settings into `options`. | | `aiAssert` | `aiAssert.prompt` | Rename `errorMessage` to `message`; move extraction settings into `options`. | | `aiQuery`, `aiNumber`, `aiString`, `aiBoolean`, `aiAsk`, `aiLocate` | Same-name Node with `prompt` | Place images and extraction settings under `prompt` or `options` as described by the Node Spec. | | `aiWaitFor` | `aiWaitFor.prompt` | Legacy `timeout` maps to `options.timeoutMs` in the Node input. | | `aiTap` | `aiTap.prompt` | Normalize legacy `locate`, images, and locate settings into `prompt` and `options`. | | `aiScroll` | `aiScroll` | Use the locate description as `prompt` and scrolling settings as `options`. | | `aiInput` | `aiInput.value` and `aiInput.prompt` | Move the entered value to `value` and the locate description to `prompt`. | | `aiKeyboardPress` | `aiKeyboardPress.keyName` and optional `prompt` | Use the inputs described by the project Node Spec. | | `sleep` | `sleep.ms` | For example, change `sleep: 1000` to `sleep: { ms: 1000 }`. New cases can also use the common `wait` Node. | | `javascript` | `javascript.script` | Its return value is recorded in the Step result. | | `recordToReport`, `logScreenshot` | `recordToReport` | Map the title to `title` and `content` to `options.content`. | | `runGherkinScenario` | `runGherkinScenario.scenario` | Legacy execution disables caching for this action. | | `runAdbShell` | `runAdbShell` | Map the command to `command`; preserve legacy `timeout` as Node input. | | `Finalize` | Legacy-only planning marker | Accepted by the legacy runtime; omit it when writing native Cases. It is not a public Node. | | Other platform and custom actions | A registered same-name Node, or the generic `action` Node | Run `midscene-test nodes` first and rewrite inputs according to the target platform's Node Spec. | | Flow item `name` | Structured Node result | `midscene` still writes named legacy outputs. Native Test has no named cross-Step result expression; share data through custom Nodes and the project `context`. | ### Concrete example: migrate one order-submission Case The following legacy case fills in a recipient, waits for the submit button, submits the order, and records the result. It uses task failure policy, an action alias, locate input, action timeout, an assertion message, a fixed wait, and report recording: ```yaml filename=flows/submit-order.yaml web: url: https://shop.example.com/checkout tasks: - name: Submit an order continueOnError: true flow: - aiInput: Alice locate: Recipient name input - aiWaitFor: The submit order button is enabled timeout: 10000 - ai: Click the submit order button - aiAssert: The page shows that the order was submitted errorMessage: No success message appeared after submission - sleep: 500 - recordToReport: Order submission result content: The checkout flow completed ``` The same Case in native Test YAML is: ```yaml filename=cases/submit-order.yaml beforeEach: - gotoUrl: https://shop.example.com/checkout cases: - name: Submit an order steps: - aiInput: prompt: Recipient name input value: Alice - aiWaitFor: prompt: The submit order button is enabled options: timeoutMs: 10000 - aiAct: Click the submit order button - aiAssert: prompt: The page shows that the order was submitted message: No success message appeared after submission - wait: duration: 500 unit: ms - recordToReport: title: Order submission result options: content: The checkout flow completed ``` The conversion has several parts: 1. `web.url` no longer sits beside case content. Preparation functions in the project configuration create the browser and page. Because every Case must start on the checkout page, `gotoUrl` in `beforeEach` owns the URL. 2. The task becomes a Case. Native Test already continues after a failed Case, so this example needs no continuation option. 3. The `aiInput` value and locate description move from legacy sibling fields to the Node's `value` and `prompt`. 4. `aiWaitFor.timeout` limits that wait operation, so it becomes `options.timeoutMs`. To limit the complete Step instead, use `$: { timeout: 10000 }`. 5. `ai` becomes `aiAct`, and `aiAssert.errorMessage` becomes `aiAssert.message`. 6. The fixed delay uses the native common `wait` Node. The report title and body move to `recordToReport.title` and `options.content`. This example changes the input structure without changing business execution order. During a real migration, run `pnpm exec midscene-test nodes --project <name>` to generate the current Project's `midscene-node-spec.<project-name>.md`. Use this Node Spec—not examples from another platform—to confirm whether `gotoUrl`, `aiInput`, `aiWaitFor`, and the other referenced Nodes are available and how to provide their inputs. ### Script and Agent configuration mapping `midscene` continues to read top-level legacy YAML configuration. In a native migration, move these fields out of Case YAML and into `midscene.config.ts`, `setup` / `fileSetup`, or Nodes. Use `setup` for shared resources, `fileSetup` for each file's resources, and YAML hooks for business prerequisites. See [setup, fileSetup, and beforeAll](/midscene-test/execution.md#setup-filesetup-and-beforeall). | Legacy script field | Native Test configuration or mechanism | Notes | | ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `target` | Web `setup` / `fileSetup` | This field is deprecated. Do not carry it into new configuration; configure the actual Playwright, Puppeteer, or bridge runtime. | | `page`, `browser`, `web` | Web `setup` / `fileSetup` plus Web Nodes | Put the shared Browser in `setup` and independent pages in `fileSetup`. Put repeatable navigation and Cookie operations in lifecycle Nodes. | | `android` | Android `setup` / `fileSetup` plus Android Nodes | Use device ID, screenshot, and input settings to create the Device and Agent. Put `launch` and other case actions in `beforeEach` or `steps`. | | `ios` | iOS `setup` / `fileSetup` plus iOS Nodes | Put WDA connection and Device/Agent creation in `setup` or `fileSetup`. Use registered Nodes for application launch and interaction. | | `harmony` | HarmonyOS `setup` / `fileSetup` plus HarmonyOS Nodes | Put HDC connection, device settings, and application mappings in `setup` or `fileSetup`. Use registered Nodes for application and shell actions. | | `computer` | Computer `setup` / `fileSetup` plus Computer Nodes | Put display and device settings in `setup` or `fileSetup`. Use registered Nodes for UI actions. | | `interface` | Custom `setup` / `fileSetup` plus `createMidsceneNodes()` | Import and create the custom Interface, Device, and Agent in `setup` or `fileSetup`, then expose the Agent to Nodes. | | `agent.generateReport` | Legacy report setting | Old YAML can disable its report. Native Test always generates a combined report. | | `agent.reportFileName`, `agent.testId` | Legacy Agent artifact settings | Open the report using the path printed by the CLI or the report link in the summary. `testId` remains deprecated. | | `agent.groupName`, `agent.groupDescription` | Project and Case names plus report structure | There is no same-name native field. Express grouping through Project names, Case names, or tags. | | `agent.replanningCycleLimit`, `agent.aiContexts`, `agent.aiActContext`, `agent.aiActionContext`, `agent.cache`, `agent.screenshotShrinkFactor` | Agent construction options | Continue passing the relevant options when creating the Agent instead of placing them in Case YAML. | | `agent.outputFormat`, `agent.persistExecutionDump`, `agent.autoPrintReportMsg` | Test reporting or Agent options | Prefer the combined Test report. Preserve an option when creating the Agent only when its Agent-specific behavior is still required. | | `config.output`, or `output` under a platform field | Test structured results | `midscene` still writes legacy output files. Native Test uses `--result-dir`, `summary.json`, and the report. Return business data from custom Nodes or write it to external storage. | | `config.unstableLogContent` | Test report and structured results | There is no same-name native field. Migrate consumers away from the legacy experimental log-content file. | | `tasks` | Native Workflow Document | Map it to `cases` and lifecycle hooks as described above. | See [Configure the runtime environment](/midscene-test/configuration.md#configure-the-runtime-environment) for complete preparation and platform Node registration examples. ### Batch configuration mapping Legacy `batch.yaml`: ```yaml files: - flows/cases/**/*.yaml setup: flows/setup.yaml concurrent: 2 retry: 1 continueOnError: false summary: result.json headed: true ``` Native Test moves execution settings into `midscene.config.ts`: ```ts filename=midscene.config.ts import { defineTestProject } from '@midscene/test/config'; import { nodes, setup } from './test-runtime'; export default defineTestProject({ nodes, projects: [ { name: 'default', setup, files: { include: ['flows/cases/**/*.yaml'], }, retry: 1, }, ], test: { bail: 1, }, output: { reportDir: './midscene_run/report', }, }); ``` | Legacy batch setting | Native Test configuration or mechanism | Notes | | ----------------------------------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `files` | `projects[].files.include` | `midscene` preserves old order and repeated invocations. Native selection is sorted and deduplicated, with no `files.order` switch. | | `setup` | `setup` / `fileSetup` / YAML `beforeAll` | Legacy execution runs a prerequisite YAML file first. Native preparation functions create resources according to sharing scope, and `beforeAll` runs file prerequisites; there is no `setupFile` option. | | `concurrent` | `test.maxConcurrentFiles` + `fileSetup` | Explicitly enable file concurrency and prepare an independent environment for each file. | | `retry` | Legacy whole-file retry; native `projects[].retry` | Native retries only a failed Case. Keep legacy files on `midscene` when whole-file replay is required; there is no `retryScope` switch. | | `continueOnError: false` | `test.bail: 1` | Stop scheduling new files or Cases when the failure threshold is reached. Concurrent work that has already started still completes cleanup. | | `continueOnError: true` | `test.bail: 0` | Disable global failure-threshold stopping. `midscene` separately preserves old task continuation; native Cases continue by default. | | `summary` | Test `summary.json`, report, and programmatic APIs | `midscene` still writes the legacy summary. Native Test has no same-name setting; migrate consumers and use `--result-dir` to select the structured result directory. | | `shareBrowserContext` | Project `setup` and `fileSetup` | Native Test can share a Browser in setup and create a separate BrowserContext per file in fileSetup; this changes the legacy shared-session behavior. | | `headed` | Browser or device setup launch settings | For example, Playwright uses `chromium.launch({ headless: false })`. | | `keepWindow` | setup cleanup policy | Use only for local debugging; the project must decide whether to delay or skip browser teardown. | | `dotenvOverride`, `dotenvDebug` | Project environment-loading policy | Native Test reads `process.env`. If you rely on an `.env` file, load it explicitly in the config or launch script and configure precedence and debugging there. | | `web`, `android`, `ios`, `harmony`, `computer`, `interface` | `setup` / `fileSetup`, `variables`, and registered platform Nodes | Prepare resources according to sharing scope; keep serializable environment differences in `variables`. | The native example above migrates file selection, case retries, and the failure threshold; it does not preserve legacy setup-file behavior or file concurrency. For concurrency, add `test.maxConcurrentFiles` and `fileSetup` as shown in [File concurrency](/midscene-test/execution.md#file-concurrency-with-maxconcurrentfiles). To keep existing cases and batch configuration, continue using `midscene`; legacy `concurrent` / `--concurrent` and setup-file behavior remain unchanged. The `midscene` entry preserves legacy output naming: explicit flow `name` values, numeric keys for unnamed extracted results, and the existing overwrite behavior for duplicate names. ## Validate the migration Run the legacy version with `midscene` and the converted version with `midscene-test`, then compare at least: - Process exit status and continuation after a failure. - Whether retries apply to one Case or the complete file. - Environment variables, platform connection settings, and initial page state. - AI action inputs, timeouts, and assertion failure messages. - Business output consumers and Step results in the new Test report. - Page, Agent, device, and test-data isolation during concurrent execution. - Lifecycle hooks and resource cleanup after failures, timeouts, and Ctrl+C interruption. After migration, write new cases with `cases/steps`. Keep `tasks/flow` only in files that have not yet been migrated so the compatibility format does not expand into new code. --- url: /mobile-world-benchmark-report.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Midscene MobileWorld Benchmark Report This is Midscene's test report for the MobileWorld benchmark. In this run, Midscene evaluated only 117 `GUI-ONLY` tasks and achieved **Pass\@1 78.63% (92/117)**. :::info About MobileWorld [MobileWorld](https://github.com/Tongyi-MAI/MobileWorld) is an Android Agent benchmark designed for realistic mobile scenarios. It covers cross-app workflows, long-horizon tasks, user interaction, and tool-augmented tasks, with reproducible Android environments used to validate Agent execution results. ::: ## Run configuration | Field | Value | | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | Test date | 2026-07-28 | | Model Name | `Gemini-3.6-Flash` | | Midscene version | `1.10.3` | | Device | `DockerEmulator` | | Task scope | `GUI-ONLY` tasks only | | Number of tasks | 117 | | `MIDSCENE_REPLANNING_CYCLE_LIMIT` | 50 | | MobileWorld setup | MobileWorld used a Midscene benchmark adapter that delegates Agent execution through Midscene RPC while retaining MobileWorld task setup and validation. | | Validation notes | A MobileWorld validator was aligned with the task intent. The affected case is listed below. | ## Validation Condition Updates The following MobileWorld validation check was adjusted for this benchmark: | Change | Affected case | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | The previous validator required a full five-day interval between `created_at` and `expires_at`. For example, if the start date is the 16th, “five days later” is the 21st; however, differences in the converted time of day can make the interval shorter than 5 × 24 hours, causing the previous rule to fail. The validator now accepts intervals longer than 4 days and no longer than 5 days. | `MastodonNewFilterTask` | ## Report files The detailed reports for all 117 `GUI-ONLY` tasks are listed below. Each report is a compressed, self-contained HTML file. Select “report” to open the corresponding execution trace in a new page. Round 1 (117 reports · 92 PASS · 25 FAIL) | # | Task | Status | Report | | --- | ---------------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | AcceptMeetingTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-1-AcceptMeetingTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 2 | AdjustBrightnessMaximumTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-2-AdjustBrightnessMaximumTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 3 | AdjustBrightnessMinimumTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-3-AdjustBrightnessMinimumTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 4 | AdjustFontIconMaximumTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-4-AdjustFontIconMaximumTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 5 | AdjustFontIconMinimumTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-5-AdjustFontIconMinimumTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 6 | BidFileRenameTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-6-BidFileRenameTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 7 | CVEmailTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-7-CVEmailTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 8 | CancelMeetingTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-8-CancelMeetingTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 9 | CartInfoNotificationTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-9-CartInfoNotificationTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 10 | CartManagementTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-10-CartManagementTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 11 | ChangeWallpaperTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-11-ChangeWallpaperTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 12 | CheckCartPriceTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-12-CheckCartPriceTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 13 | CheckConferenceAndSendSmsTask1 | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-13-CheckConferenceAndSendSmsTask1__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 14 | CheckConferenceAndSendSmsTask2 | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-14-CheckConferenceAndSendSmsTask2__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 15 | CheckConferenceDurationTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-15-CheckConferenceDurationTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 16 | CheckConferenceLocationTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-16-CheckConferenceLocationTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 17 | CheckDeduplicatedEventsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-17-CheckDeduplicatedEventsTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 18 | CheckDepartTimeTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-18-CheckDepartTimeTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 19 | CheckEventTimeTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-19-CheckEventTimeTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 20 | CheckGithubInfoTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-20-CheckGithubInfoTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 21 | CheckInterviewTimesTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-21-CheckInterviewTimesTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 22 | CheckInvoiceTask1 | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-22-CheckInvoiceTask1__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 23 | CheckInvoiceTask2 | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-23-CheckInvoiceTask2__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 24 | CheckInvoiceTask3 | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-24-CheckInvoiceTask3__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 25 | CheckPuchasedItem | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-25-CheckPuchasedItem__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 26 | CheckRegistrationTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-26-CheckRegistrationTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 27 | CheckSetMeetTimeTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-27-CheckSetMeetTimeTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 28 | ChromeSearchBeijingWeatherTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-28-ChromeSearchBeijingWeatherTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 29 | CloseFlightModeTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-29-CloseFlightModeTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 30 | CountFileLinesTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-30-CountFileLinesTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 31 | DownloadSendReceiptTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-31-DownloadSendReceiptTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 32 | GoogleMapsAlibabaPhoneContactTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-32-GoogleMapsAlibabaPhoneContactTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 33 | GoogleMapsAlibabaSouthNeighborTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-33-GoogleMapsAlibabaSouthNeighborTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 34 | GraduationMassEmailTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-34-GraduationMassEmailTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 35 | InvoiceReceiptCopyAskUserTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-35-InvoiceReceiptCopyAskUserTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 36 | InvoiceReceiptCopyTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-36-InvoiceReceiptCopyTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 37 | ItemCheckoutTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-37-ItemCheckoutTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 38 | LocalFileManagementTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-38-LocalFileManagementTask__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 39 | LocalFileManagementTask2 | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-39-LocalFileManagementTask2__group-0-b3c13bb1-7b21-4fbf-8d3f-65fcdeb309e0-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 40 | MastodonAddBookmarkTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-40-MastodonAddBookmarkTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 41 | MastodonAddFeaturedHashtagsTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-41-MastodonAddFeaturedHashtagsTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 42 | MastodonAdjustTootsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-42-MastodonAdjustTootsTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 43 | MastodonCalendarMultiMemosTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-43-MastodonCalendarMultiMemosTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 44 | MastodonChangeHeaderTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-44-MastodonChangeHeaderTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 45 | MastodonChangeLanguageTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-45-MastodonChangeLanguageTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 46 | MastodonConditionalFavoTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-46-MastodonConditionalFavoTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 47 | MastodonCreateListTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-47-MastodonCreateListTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 48 | MastodonCreateMemoTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-48-MastodonCreateMemoTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 49 | MastodonExportFollowsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-49-MastodonExportFollowsTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 50 | MastodonFavoriteTootsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-50-MastodonFavoriteTootsTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 51 | MastodonFilterLanguageTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-51-MastodonFilterLanguageTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 52 | MastodonFollowTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-52-MastodonFollowTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 53 | MastodonGetServerInfoTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-53-MastodonGetServerInfoTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 54 | MastodonImportMutedUsersTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-54-MastodonImportMutedUsersTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 55 | MastodonInviteTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-55-MastodonInviteTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 56 | MastodonMallPurchaseCommodityTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-56-MastodonMallPurchaseCommodityTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 57 | MastodonMallShareOrderTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-57-MastodonMallShareOrderTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 58 | MastodonManageHashtagsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-58-MastodonManageHashtagsTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 59 | MastodonManageMultiListTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-59-MastodonManageMultiListTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 60 | MastodonMattermostPostNoticeTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-60-MastodonMattermostPostNoticeTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 61 | MastodonMultiInviteTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-61-MastodonMultiInviteTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 62 | MastodonNewFilterTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-62-MastodonNewFilterTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 63 | MastodonNewPostTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-63-MastodonNewPostTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 64 | MastodonOpenAutomatedDeletionTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-64-MastodonOpenAutomatedDeletionTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 65 | MastodonPinTootsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-65-MastodonPinTootsTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 66 | MastodonPostEditedPhotoTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-66-MastodonPostEditedPhotoTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 67 | MastodonPostPollTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-67-MastodonPostPollTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 68 | MastodonRemoveBookmarkTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-68-MastodonRemoveBookmarkTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 69 | MastodonReplyTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-69-MastodonReplyTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 70 | MastodonReportTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-70-MastodonReportTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 71 | MastodonRevisePhotoAltTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-71-MastodonRevisePhotoAltTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 72 | MastodonRevisePollTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-72-MastodonRevisePollTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 73 | MastodonSavePhotosTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-73-MastodonSavePhotosTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 74 | MastodonServerInfoReportTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-74-MastodonServerInfoReportTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 75 | MastodonShareLocationTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-75-MastodonShareLocationTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 76 | MastodonUnfollowTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-76-MastodonUnfollowTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 77 | MastodonUpdateContactsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-77-MastodonUpdateContactsTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 78 | MattermostBudgetApprovalPipelineTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-78-MattermostBudgetApprovalPipelineTask__group-1-0a3fa62d-94f0-4f16-ba4d-7ac1fb2a8596-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 79 | MattermostCreateChannelTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-79-MattermostCreateChannelTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 80 | MattermostCustomerFeedbackAnalysisTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-80-MattermostCustomerFeedbackAnalysisTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 81 | MattermostDeadlineReconciliationTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-81-MattermostDeadlineReconciliationTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 82 | MattermostEmailTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-82-MattermostEmailTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 83 | MattermostIncidentEscalationTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-83-MattermostIncidentEscalationTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 84 | MattermostProjectHandoverTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-84-MattermostProjectHandoverTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 85 | MattermostProjectStatusReportTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-85-MattermostProjectStatusReportTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 86 | MattermostReadingGroupTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-86-MattermostReadingGroupTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 87 | MattermostReplyToMessageTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-87-MattermostReplyToMessageTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 88 | MattermostResourceConflictResolutionTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-88-MattermostResourceConflictResolutionTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 89 | MattermostSendFileTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-89-MattermostSendFileTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 90 | MattermostShiftCoverageTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-90-MattermostShiftCoverageTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 91 | MattermostTechnicalDebtTriageTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-91-MattermostTechnicalDebtTriageTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 92 | MattermostVisualInstructionResponseTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-92-MattermostVisualInstructionResponseTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 93 | OpenFlightModeTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-93-OpenFlightModeTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 94 | PhotoManagementTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-94-PhotoManagementTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 95 | ReadQwen3PaperTask1 | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-95-ReadQwen3PaperTask1__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 96 | ReadQwen3PaperTask2 | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-96-ReadQwen3PaperTask2__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 97 | ReadQwen3PaperTask3 | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-97-ReadQwen3PaperTask3__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 98 | ReadQwen3PaperTask4 | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-98-ReadQwen3PaperTask4__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 99 | ReadQwen3PaperTask5 | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-99-ReadQwen3PaperTask5__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 100 | RecentTotalExpenseTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-100-RecentTotalExpenseTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 101 | RequestCarpoolingTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-101-RequestCarpoolingTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 102 | ReviewPaperEmailTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-102-ReviewPaperEmailTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 103 | SMSManagement | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-103-SMSManagement__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 104 | ScheduleCoffeeTimeViaSmsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-104-ScheduleCoffeeTimeViaSmsTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 105 | ScheduleLunchViaSmsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-105-ScheduleLunchViaSmsTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 106 | SearchItemAndCheckoutTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-106-SearchItemAndCheckoutTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 107 | SendFormsTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-107-SendFormsTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 108 | SendInterviewEmailTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-108-SendInterviewEmailTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 109 | SendInterviewInvitationTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-109-SendInterviewInvitationTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 110 | SendWaiverTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-110-SendWaiverTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 111 | SetAlarmTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-111-SetAlarmTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 112 | SharePhotosTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-112-SharePhotosTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 113 | SuggestPaperTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-113-SuggestPaperTask__group-0-b91cc3df-394d-47e4-8a5b-f61c5beddb79-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 114 | SumFileLinesTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-114-SumFileLinesTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 115 | TakeSelfieTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-115-TakeSelfieTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 116 | TextArrivalTimeTask | <span className="benchmark-status benchmark-status-fail">FAIL</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-116-TextArrivalTimeTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Fail.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | | 117 | ThanksgivingPrepTask | <span className="benchmark-status benchmark-status-pass">PASS</span> | <a href="https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/benchmark/MobileWorld/20260728/20260728/Task-117-ThanksgivingPrepTask__group-2-6f07b306-f600-41bd-a7b0-f5cd7a21335d-Pass.html" className="benchmark-report-link" target="_blank" rel="noreferrer" title="Open report in a new page">report</a> | --- url: /model-api-setup.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Use a model API key Connect Midscene using an API key from a model provider. This guide covers model configuration and connection verification. If you already have a ChatGPT subscription, you can also follow [Use a ChatGPT subscription](/chatgpt-subscription.md). The model configuration shown on this page consists of environment variables. Provide it according to how you use Midscene: - In Playground, paste the configuration text from this page directly into the settings page. - With the SDK or CLI, load the configuration as described in [Set environment variables](#set-environment-variables). For advanced parameter definitions, see [Model advanced configuration and debugging](/model-config.md). ## Supported models For an overview of supported models and connection methods, see the [Model Selection Guide](/model-selection.md). Configuration examples for each model follow. Each configuration requires a Base URL, API key, model name, and `MIDSCENE_MODEL_FAMILY`. The model family (`MIDSCENE_MODEL_FAMILY`) selects the model adapter, which determines coordinate handling, supported API protocols, and how reasoning and output parameters are sent. Use the family listed for your model below. ### Doubao Seed Series {#doubao-seed-model} Doubao-Seed-2.1 Turbo View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | ------------------------------------------------------------------------------- | ----------------------------------------- | ----------------- | | **2.x series**<br />`doubao-seed-2-1-pro-260915` `doubao-seed-2-1-turbo-260628` | `doubao-seed` | — | | **1.x series**<br />`Doubao-Seed-1.6-Vision` `Doubao-Seed-1.8` | `doubao-seed` | Older generation. | Configuration example (`doubao-seed-2-1-turbo-260628`): **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` If your Volcano Engine account has Fast Tier quota enabled, add the extra request body below to use it. This usually improves model response speed by about 30%-50%. ```bash MIDSCENE_MODEL_EXTRA_BODY_JSON={"service_tier":"fast"} ``` ### Qwen Series {#qwen} Qwen3.7 Plus View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | -------------------------------------------------------------------- | ----------------------------------------- | ---------------------------------------------------------------- | | **Qwen4 series**<br />`qwen4-max` | `qwen4` | | | **Qwen3.x series**<br />`qwen3.7-plus` `qwen3.5-plus` `qwen3.6-plus` | `qwen3` | The previous `qwen3.5` and `qwen3.6` families remain compatible. | | **Qwen3-VL series**<br />`qwen3-vl-plus` | `qwen3-vl` | Older generation. | | **Qwen2.5-VL series**<br />`qwen-vl-max-latest` | `qwen2.5-vl` | Older generation. | Configuration example (`qwen3.7-plus`): **Alibaba Cloud** ([Get API key](https://modelstudio.console.alibabacloud.com/ap-southeast-1/settings/api-key)) ```bash MIDSCENE_MODEL_BASE_URL="https://dashscope-intl.aliyuncs.com/compatible-mode/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="qwen3.7-plus" MIDSCENE_MODEL_FAMILY="qwen3" # If you use another Qwen version, replace this with the corresponding model family ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="qwen/qwen3.7-plus" MIDSCENE_MODEL_FAMILY="qwen3" # If you use another Qwen version, replace this with the corresponding model family ``` The Alibaba Cloud example uses the Singapore region. The API key, Base URL, and model must belong to the same region. For other regions, see [Regions and endpoints](https://www.alibabacloud.com/help/en/model-studio/regions). ### DeepSeek Series {#deepseek} Midscene supports DeepSeek starting from v1.12.0. DeepSeek V4.1 Flash View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------- | | **DeepSeek V4 series**<br />`deepseek-flash` (V4.1 Flash) `deepseek-v4-flash-vision-exp` (V4 Flash Vision) | `deepseek` | DeepSeek-V4-Pro does not support visual input and cannot be used with Midscene. | Configuration example (`deepseek-flash`): **DeepSeek** ([Get API key](https://platform.deepseek.com/api_keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://api.deepseek.com" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="deepseek-flash" MIDSCENE_MODEL_FAMILY="deepseek" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="deepseek/deepseek-v4.1-flash" MIDSCENE_MODEL_FAMILY="deepseek" ``` ### Google Gemini Series {#gemini} Gemini 3.5 Flash View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | ---------------------------------------------------------------------- | ----------------------------------------- | ----- | | **Gemini 4 Argon**<br />`gemini-4-argon` | `gemini` | — | | **Gemini 3.x series**<br />`gemini-3.5-flash` `gemini-3-flash-preview` | `gemini` | — | Configuration example (`gemini-3.5-flash`): **Google AI Studio** ([Get API key](https://aistudio.google.com/apikey)) ```bash MIDSCENE_MODEL_BASE_URL="https://generativelanguage.googleapis.com/v1beta/openai/" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="gemini-3.5-flash" MIDSCENE_MODEL_FAMILY="gemini" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="google/gemini-3.5-flash" MIDSCENE_MODEL_FAMILY="gemini" ``` ### OpenAI GPT Series {#gpt} GPT-6 Sol View configurationHide configuration :::info To connect using your ChatGPT subscription, see [Use a ChatGPT subscription](/chatgpt-subscription.md). ::: | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | -------------------------------------------------------------------------------------- | ----------------------------------------- | ----------------- | | **GPT-6 series**<br />`gpt-6-astra` `gpt-6-sol` `gpt-6-luna` | `gpt-6` | — | | **GPT-5 series**<br />`gpt-5.4` `gpt-5.5` `gpt-5.6-sol` `gpt-5.6-terra` `gpt-5.6-luna` | `gpt-5` | Older generation. | **Use an API Key** Configuration example (`gpt-6-sol`): **OpenAI** ([Get API key](https://platform.openai.com/api-keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://api.openai.com/v1" # Or your compatible endpoint MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="openai/gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` **Enable Fast mode (`service_tier="fast"`)** GPT-6 Astra supports Fast mode. Add the `service_tier` request body parameter to enable it: ```bash MIDSCENE_MODEL_NAME="gpt-6-astra" MIDSCENE_MODEL_FAMILY="gpt-6" MIDSCENE_MODEL_EXTRA_BODY_JSON='{"service_tier":"fast"}' ``` According to OpenAI, Fast mode can deliver up to 2–2.5× the speed at twice the Standard rate. Refer to the [official documentation](https://developers.openai.com/api/docs/guides/fast-mode) for current speed, pricing, and usage restrictions. To reuse a Codex CLI session, see [Use Codex App Server](/chatgpt-subscription.md#use-codex-app-server-oauth-no-api-key). **When using GPT, note the following:** - In the computer use guide, OpenAI says they observe good performance around `1440x900` and `1600x900`. We recommend adjusting screenshot sizes accordingly. In Midscene, you can control screenshot compression with `screenshotShrinkFactor` in the agent options. For browser automation, you can also control the page size and scale through the browser `viewport`. - Azure OpenAI's Chat Completions API may not handle `"detail": "original"` correctly, causing click-coordinate offsets. If you encounter this issue, you can switch to the Responses API. See [Clicks are offset when using Azure OpenAI](/faq.md#clicks-are-offset-when-using-azure-openai). ### Moonshot Kimi Series {#kimi} Kimi K3 View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | -------------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | **K3 series**<br />`kimi-k3` | `kimi3` | According to the Kimi documentation, K3 always has reasoning enabled and cannot be disabled. Its reasoning effort defaults to `max`. | | **K2.x series**<br />`kimi-k2.5` `kimi-k2.6` | `kimi` | — | Configuration example (`kimi-k3`): **Moonshot AI** ([Get API key](https://platform.kimi.com/)) ```bash MIDSCENE_MODEL_BASE_URL="https://api.moonshot.cn/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="kimi-k3" MIDSCENE_MODEL_FAMILY="kimi3" # For kimi-k2.6, use "kimi" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="moonshotai/kimi-k3" MIDSCENE_MODEL_FAMILY="kimi3" # For kimi-k2.6, use "kimi" ``` ### Xiaomi MiMo Series {#xiaomi-mimo} MiMo V2.6 Pro View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | --------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------- | | **V2.x series**<br />`mimo-v2.6-pro` `mimo-v2.6-flash` `mimo-v2.6-pro-ultraspeed` `mimo-v2.5` | `xiaomi-mimo` | All 2.6 models support multimodal input; for 2.5, only the Omni series supports multimodal input. | Configuration example (`mimo-v2.6-pro`): **Xiaomi MiMo** ([Get API key](https://platform.xiaomimimo.com/)) ```bash MIDSCENE_MODEL_BASE_URL="https://api.xiaomimimo.com/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="mimo-v2.6-pro" MIDSCENE_MODEL_FAMILY="xiaomi-mimo" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="xiaomi/mimo-v2.6-pro" MIDSCENE_MODEL_FAMILY="xiaomi-mimo" ``` ### Zhipu GLM-V Series {#glm-v} GLM-5V-Turbo View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | ------------------------------------- | ----------------------------------------- | -------------------------- | | **GLM-5V series**<br />`glm-5v-turbo` | `glm-v` | — | | **GLM-4.6 series**<br />`glm-4.6v` | `glm-v` | `glm-4.6v` is open-source. | Configuration example (`glm-5v-turbo`): **Z.AI (Global)** ([Get API key](https://z.ai/manage-apikey/apikey-list)) ```bash MIDSCENE_MODEL_BASE_URL="https://api.z.ai/api/paas/v4" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="glm-5v-turbo" MIDSCENE_MODEL_FAMILY="glm-v" ``` **BigModel (CN)** ([Get API key](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)) ```bash MIDSCENE_MODEL_BASE_URL="https://open.bigmodel.cn/api/paas/v4" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="glm-5v-turbo" MIDSCENE_MODEL_FAMILY="glm-v" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="z-ai/glm-5v-turbo" MIDSCENE_MODEL_FAMILY="glm-v" ``` **Learn more about the open-source GLM-4.6V model** - Github: [https://github.com/zai-org/GLM-V](https://github.com/zai-org/GLM-V) - Hugging Face: [https://huggingface.co/zai-org/GLM-4.6V](https://huggingface.co/zai-org/GLM-4.6V) ### StepFun {#stepfun} Step 3.7 Flash View configurationHide configuration **StepFun** ([Get API key](https://platform.stepfun.ai/)) ```bash MIDSCENE_MODEL_BASE_URL="https://api.stepfun.ai/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="step-3.7-flash" MIDSCENE_MODEL_FAMILY="step" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="stepfun/step-3.7-flash" MIDSCENE_MODEL_FAMILY="step" ``` ### Ant Ling {#ant-ling} Ling-3.2-flash View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | ----------------------------------------------------------- | ----------------------------------------- | ----- | | **Ling 3 series**<br />`Ling-3.2-flash` `Ling-3.0-flash-VL` | `ant-ling` | — | Configuration example (`Ling-3.2-flash`): **Ant Ling** ([Get API key](https://developer.ant-ling.com/)) ```bash MIDSCENE_MODEL_BASE_URL="https://api.ant-ling.com/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="Ling-3.2-flash" MIDSCENE_MODEL_FAMILY="ant-ling" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="inclusionai/ling-3.2-flash" MIDSCENE_MODEL_FAMILY="ant-ling" ``` :::info Screenshot dimensions We observed that `Ling-3.0-flash-VL` may locate elements less accurately when the longest image edge exceeds 2000 pixels. Use the Agent's `screenshotShrinkFactor` option to resize images. We did not observe this issue with `Ling-3.2-flash`. ::: ### Tencent HY {#tencent-hy} Hy4 View configurationHide configuration | Model<br />`MIDSCENE_MODEL_NAME` | Model family<br />`MIDSCENE_MODEL_FAMILY` | Notes | | ------------------------------------- | ----------------------------------------- | ----- | | **Hy4 series**<br />`hy4` `hy4-flash` | `tencent-hy` | — | Configuration example (`hy4`): **Tencent Cloud TokenHub** ([Get API key](https://console.cloud.tencent.com/tokenhub/apikey)) ```bash MIDSCENE_MODEL_BASE_URL="https://tokenhub.tencentmaas.com/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="hy4" MIDSCENE_MODEL_FAMILY="tencent-hy" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="tencent/hy4" MIDSCENE_MODEL_FAMILY="tencent-hy" ``` ### Jev (experimental) {#jev} Jev is a model for making choices. You can use it to select the next action, locate UI elements, and evaluate whether a condition holds. It is fast and inexpensive, but is not suitable for tasks that require complex reasoning. Midscene support for Jev is experimental. Copy the following configuration to use Jev for Planning, Locate, and Insight: Jev 1.14.0 View configurationHide configuration **TypeSafe** ([Get API key](https://console.typesafe.ai/)) ```bash # Planning MIDSCENE_PLANNING_MODEL_BASE_URL="https://api.typesafe.ai/v1" MIDSCENE_PLANNING_MODEL_API_KEY="......" MIDSCENE_PLANNING_MODEL_NAME="jev-1.14.0" MIDSCENE_PLANNING_MODEL_FAMILY="jev" # Locate MIDSCENE_LOCATE_MODEL_BASE_URL="https://api.typesafe.ai/v1" MIDSCENE_LOCATE_MODEL_API_KEY="......" MIDSCENE_LOCATE_MODEL_NAME="jev-1.14.0" MIDSCENE_LOCATE_MODEL_FAMILY="jev" # Insight MIDSCENE_INSIGHT_MODEL_BASE_URL="https://api.typesafe.ai/v1" MIDSCENE_INSIGHT_MODEL_API_KEY="......" MIDSCENE_INSIGHT_MODEL_NAME="jev-1.14.0" MIDSCENE_INSIGHT_MODEL_FAMILY="jev" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash # Planning MIDSCENE_PLANNING_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_PLANNING_MODEL_API_KEY="......" MIDSCENE_PLANNING_MODEL_NAME="typesafe/jev-router" MIDSCENE_PLANNING_MODEL_FAMILY="jev" # Locate MIDSCENE_LOCATE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_LOCATE_MODEL_API_KEY="......" MIDSCENE_LOCATE_MODEL_NAME="typesafe/jev-router" MIDSCENE_LOCATE_MODEL_FAMILY="jev" # Insight MIDSCENE_INSIGHT_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_INSIGHT_MODEL_API_KEY="......" MIDSCENE_INSIGHT_MODEL_NAME="typesafe/jev-router" MIDSCENE_INSIGHT_MODEL_FAMILY="jev" ``` When the corresponding model role is configured to use Jev, tasks are handled as follows: - **Locate**: Jev performs element localization. - **Insight**: Jev evaluates `aiBoolean`, `aiAssert`, and `aiWaitFor`. The general-purpose default model handles `aiQuery`, `aiString`, `aiNumber`, and `aiAsk`. - **Planning**: In `aiAct`, Jev plans simple actions such as clicking, double-clicking, and going back. The default model plans complex actions such as input and scrolling. Model selection is based on the capabilities required by each task. Failed Jev requests do not automatically switch to the default model. Jev uses TypeSafe's System One protocol, not an OpenAI protocol. Some OpenAI model settings do not apply, such as temperature, native reasoning, response format, and streaming output. :::info Notes - **Request URL**: When using Base URL, include `/v1`, for example `https://api.typesafe.ai/v1`. Midscene automatically appends `/systemone`. If your endpoint does not use the `/systemone` path, set the full request URL through the model's Endpoint setting, for example `MIDSCENE_LOCATE_MODEL_ENDPOINT="https://example.com/custom/decision"`. Endpoint takes precedence over Base URL, and Midscene does not append any path. - **Image input limits**: The latest version of Jev currently limits the longest edge of an image to 1568 pixels. Use the Agent's `screenshotShrinkFactor` option to control screenshot dimensions. To avoid image quality degradation from repeated resizing and accommodate image dimension requirements in future Jev versions, Midscene does not automatically resize images to match the limits of a specific Jev version. ::: ## Set environment variables Midscene reads model configuration from environment variables. Choose the method that matches how you use Midscene, or keep using your project's existing environment-management approach. ### Set environment variables in the current shell The following example works in Bash and Zsh. These variables are available only to the current shell session and its child processes. ```bash # Replace every value with the configuration for your selected model provider export MIDSCENE_MODEL_BASE_URL="https://replace-with-your-model-service-url/v1" export MIDSCENE_MODEL_API_KEY="replace-with-your-api-key" export MIDSCENE_MODEL_NAME="replace-with-your-model-name" export MIDSCENE_MODEL_FAMILY="replace-with-the-family-for-your-model" ``` ### Configure through a `.env` file Scaffolded Midscene Test configuration loads `.env` beside the configuration file, preserving existing environment variables by default. Handwritten configuration must load it explicitly or use shell/CI variables; see [Environment loading](/midscene-test/running.md#environment-loading). The [legacy YAML script runner](/yaml-script-runner.md) (`@midscene/cli`) automatically loads `.env` from the working directory. For Midscene Test, copy `.env.example` to `.env` in the generated test project directory, fill in the model configuration, then run `pnpm test`. See [Create a test project](/midscene-test/use.md) for details. For the legacy YAML script runner, create `.env` in the directory where you run `midscene`. Example `.env` contents: ```bash # Replace every value with the configuration for your selected model provider MIDSCENE_MODEL_BASE_URL="https://replace-with-your-model-service-url/v1" MIDSCENE_MODEL_API_KEY="replace-with-your-api-key" MIDSCENE_MODEL_NAME="replace-with-your-model-name" MIDSCENE_MODEL_FAMILY="replace-with-the-family-for-your-model" ``` Do not add `export` at the beginning of each line. With the legacy YAML script runner, existing shell variables take precedence over matching values in `.env`; use `--dotenv-override` to prefer values from the file. :::info JavaScript SDK The Midscene SDK reads model configuration from `process.env`. When writing test scripts, you can install [dotenv](https://www.npmjs.com/package/dotenv) in your own test project, store model configuration in a `.env` file at the project root, and add `import 'dotenv/config'` to your script entry point. Run the script from the project root and load the configuration before creating an Agent. ::: ## Other compatible models The following smaller models are also compatible with Midscene and designed for automation. They require less deployment hardware but may struggle with complex tasks or large screenshots. Evaluate them against your tasks and deployment constraints before choosing one. ### Zhipu AutoGLM Series {#auto-glm} Zhipu AutoGLM is an open-source mobile UI automation model (9B parameters) from Zhipu AI. After obtaining an API key from [Z.AI (Global)](https://z.ai/manage-apikey/apikey-list) or [BigModel (CN)](https://bigmodel.cn/usercenter/proj-mgmt/apikeys), configure: ```bash MIDSCENE_MODEL_BASE_URL="https://api.z.ai/api/paas/v4" # Or https://open.bigmodel.cn/api/paas/v4 MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="autoglm-phone" MIDSCENE_MODEL_FAMILY="auto-glm" # Or "auto-glm-multilingual" ``` **About `MIDSCENE_MODEL_FAMILY` Configuration** AutoGLM provides two model versions, distinguished by `MIDSCENE_MODEL_FAMILY`: - `auto-glm` - Corresponds to AutoGLM-Phone-9B, optimized for **Chinese mobile applications** - `auto-glm-multilingual` - Corresponds to AutoGLM-Phone-9B-Multilingual, supports **English and other languages** Choose the appropriate version based on your application language. :::info AutoGLM is best suited for mobile interaction. APIs such as `aiAssert` and `aiQuery` require page understanding. When using these APIs, configure a separate Insight model with the `MIDSCENE_INSIGHT_MODEL_...` environment variables. See [Model Selection Guide](/model-selection.md) for details. ::: **Learn more about Zhipu AutoGLM** - Github: [https://github.com/zai-org/Open-AutoGLM](https://github.com/zai-org/Open-AutoGLM) - Hugging Face: [https://huggingface.co/zai-org/AutoGLM-Phone-9B](https://huggingface.co/zai-org/AutoGLM-Phone-9B) AutoGLM-Phone-9B View configurationHide configuration ### UI-TARS Series {#ui-tars} Use the deployed `doubao-1.5-ui-tars` on [Volcano Engine](https://volcengine.com): ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="...." MIDSCENE_MODEL_NAME="ep-2025..." # Inference endpoint ID or model name from Volcano Engine MIDSCENE_MODEL_FAMILY="vlm-ui-tars-doubao-1.5" ``` **About `MIDSCENE_MODEL_FAMILY`** This variable selects the UI-TARS version. Supported values: - `vlm-ui-tars` – for the 1.0 release - `vlm-ui-tars-doubao` – for the 1.5 release deployed on Volcano Engine (equivalent to `vlm-ui-tars-doubao-1.5`) - `vlm-ui-tars-doubao-1.5` – for the 1.5 release deployed on Volcano Engine :::info The legacy configurations `MIDSCENE_USE_VLM_UI_TARS=DOUBAO` or `MIDSCENE_USE_VLM_UI_TARS=1.5` are still supported but deprecated. Please migrate to `MIDSCENE_MODEL_FAMILY`. Migration mapping: - `MIDSCENE_USE_VLM_UI_TARS=1.0` → `MIDSCENE_MODEL_FAMILY="vlm-ui-tars"` - `MIDSCENE_USE_VLM_UI_TARS=1.5` → `MIDSCENE_MODEL_FAMILY="vlm-ui-tars-doubao-1.5"` - `MIDSCENE_USE_VLM_UI_TARS=DOUBAO` → `MIDSCENE_MODEL_FAMILY="vlm-ui-tars-doubao"` ::: UI-TARS 1.5 View configurationHide configuration ## Next steps - [Verify model connectivity](/model-config.md#verify-model-connectivity) — Check that your configured models work with Midscene. - [Configure models by intent](/model-config.md#dedicated-models) — Use dedicated models for planning, localization, or page understanding, with an expandable configuration example. - [Common configuration errors](/model-config.md#common-configuration-errors) — Resolve model family, endpoint, or model name errors. - [When model results are unreliable](/model-config.md#when-model-results-are-unreliable) — Investigate incorrect actions, missed targets, or misinterpreted pages. --- url: /model-config.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Model advanced configuration and debugging This page covers advanced model settings, connection troubleshooting, logs, and tracing. ## Verify model connectivity {#verify-model-connectivity} Check whether your configured models can connect and work with Midscene: ```bash pnpm dlx @midscene/test@latest model verify ``` The command uses your environment variables and optionally loads `.env` from the current directory. Values in `.env` override matching environment variables. **Example success output (excerpt)** ```text Model role Check Result Requests Time planning Text response PASS 1 820 ms insight Image understanding PASS 1 1250 ms locate AI locate PASS 1 1460 ms default Text response PASS 1 760 ms Requests sent: 4. Checks: 4 passed, 0 failed. ✅ Model verify passed. ``` **Example failure output (excerpt)** ```text Requests sent: 4. Checks: 3 passed, 1 failed. ❌ Model verify failed with messages: ──────────────────────────────────────── [Vision check - ep-vision (insight)]: 404 Not Found ──────────────────────────────────────── ``` :::info Troubleshoot a failed connection If verification fails with a connection error, you can test the model service directly to help isolate the problem. Optional: test the model API with curl The following `curl` request checks whether the Base URL, API key, and model name work. It only verifies basic model API connectivity. It does not check whether the model meets Midscene's compatibility requirements. ```bash MIDSCENE_MODEL_BASE_URL='replace with your baseUrl' MIDSCENE_MODEL_API_KEY='replace with your API key' MIDSCENE_MODEL_NAME='replace with your model name' # MIDSCENE_MODEL_PROTOCOL="openai-responses" # Uncomment this line to use Responses API; defaults to Chat API. if [ "$MIDSCENE_MODEL_PROTOCOL" = "openai-responses" ]; then model_endpoint="responses" model_input_field="input" else model_endpoint="chat/completions" model_input_field="messages" fi curl -X POST "${MIDSCENE_MODEL_BASE_URL%/}/${model_endpoint}" \ -H "Authorization: Bearer ${MIDSCENE_MODEL_API_KEY}" \ -H "Content-Type: application/json" \ -d '{ "model": "'"${MIDSCENE_MODEL_NAME}"'", "'"${model_input_field}"'": [ { "role": "user", "content": "What is 1+1?" } ] }' ``` If the `curl` request succeeds but the Midscene verification command fails, the model API is reachable. Continue by checking the model capabilities and Midscene configuration. ::: ## Model configuration by intent {#dedicated-models} One Default model is sufficient for most tasks. When a task needs stronger planning, more precise localization, or better page understanding, configure a dedicated model for that intent to use a model better suited to that capability. You can configure separate models for Planning, Locate, and Insight intents. These settings use the same parameter suffixes and meanings as the Default model settings below. Replace the prefix for each role: | Model | Environment variable prefix | | -------- | --------------------------- | | Default | `MIDSCENE_MODEL_` | | Planning | `MIDSCENE_PLANNING_MODEL_` | | Locate | `MIDSCENE_LOCATE_MODEL_` | | Insight | `MIDSCENE_INSIGHT_MODEL_` | Provide a complete configuration for each dedicated model, including its endpoint, API key (if required by the connection method), model name, and family, along with any optional settings you need. A role without a dedicated model uses the Default model. View multi-model configuration example Keep the Default model and add dedicated models as needed. Replace the placeholders and model names with the actual configuration from your providers. ```bash # Default model export MIDSCENE_MODEL_BASE_URL="https://..." export MIDSCENE_MODEL_API_KEY="..." export MIDSCENE_MODEL_NAME="qwen3.8-flash" export MIDSCENE_MODEL_FAMILY="qwen3" # Planning model export MIDSCENE_PLANNING_MODEL_BASE_URL="https://..." export MIDSCENE_PLANNING_MODEL_API_KEY="..." export MIDSCENE_PLANNING_MODEL_NAME="gpt-6-astra" export MIDSCENE_PLANNING_MODEL_FAMILY="gpt-6" # Locate model export MIDSCENE_LOCATE_MODEL_BASE_URL="https://..." export MIDSCENE_LOCATE_MODEL_API_KEY="..." export MIDSCENE_LOCATE_MODEL_NAME="gemini-3.5-flash" export MIDSCENE_LOCATE_MODEL_FAMILY="gemini" # Insight model export MIDSCENE_INSIGHT_MODEL_BASE_URL="https://..." export MIDSCENE_INSIGHT_MODEL_API_KEY="..." export MIDSCENE_INSIGHT_MODEL_NAME="gpt-6.1-sol" export MIDSCENE_INSIGHT_MODEL_FAMILY="gpt-6" ``` ## Advanced settings (optional) ### Configuration reference To configure a separate model for Planning, Locate, or Insight, use the corresponding environment variable prefix. See [Model configuration by intent](#dedicated-models). | Name | Description | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `MIDSCENE_MODEL_ENDPOINT` | Full request URL for the System One API. Supported only by System One models (currently Jev). Takes precedence over the model's `BASE_URL` and is used as-is, without appending a path; `BASE_URL` is optional when this is set. For example, `https://api.typesafe.ai/v1/systemone`. When unset, Midscene continues to append `/systemone` to the Base URL. | | `MIDSCENE_MODEL_TIMEOUT` | Timeout per model request in milliseconds, including reading the response body. Defaults to `180000` (180 seconds). Set to `0` to disable this timeout. | | `MIDSCENE_MODEL_TEMPERATURE` | Model sampling temperature. Set to `unset` to omit the temperature parameter. | | `MIDSCENE_MODEL_RETRY_COUNT` | Number of retries when AI call fails, default 1 (i.e., retry once after failure). Retries occur when the model request encounters an HTTP error or when the model response cannot be structurally parsed | | `MIDSCENE_MODEL_RETRY_INTERVAL` | Interval between retries in milliseconds, default 2000 | | `MIDSCENE_MODEL_REASONING_ENABLED` | Controls whether model-native thinking is enabled. Midscene disables it by default. See [Model-native thinking](#model-native-reasoning) | | `MIDSCENE_MODEL_REASONING_EFFORT` | Controls model-native thinking effort, supported by some models. Common values: `low`, `medium`, `high`. See [Model-native thinking](#model-native-reasoning) | | `MIDSCENE_MODEL_REASONING_BUDGET` | Thinking token budget (number), supported by some models. See [Model-native thinking](#model-native-reasoning) | | `MIDSCENE_MODEL_RESPONSE_FORMAT` | Structured response strategy: `auto` (default) lets Midscene automatically use `response_format` (Chat Completions) or `text.format` (Responses) in appropriate scenarios to specify a structured output format (usually JSON), making the model response as suitable for structured parsing as possible; `none` does not set those format parameters, for models that do not support structured output. | | `MIDSCENE_MODEL_HTTP_PROXY` | HTTP/HTTPS proxy, e.g., `http://127.0.0.1:8080` or `https://proxy.example.com:8080`. Takes precedence over `MIDSCENE_MODEL_SOCKS_PROXY` | | `MIDSCENE_MODEL_SOCKS_PROXY` | SOCKS proxy, e.g., `socks5://127.0.0.1:1080` | | `MIDSCENE_MODEL_INIT_CONFIG_JSON` | JSON that overrides the OpenAI SDK initialization config, suitable for custom headers, query parameters, and other additional options. Overriding `baseURL` or `apiKey` through this setting is not recommended; use `MIDSCENE_MODEL_BASE_URL` and `MIDSCENE_MODEL_API_KEY` instead to keep Midscene’s parameter adaptation consistent with the actual request configuration. Use `defaultHeaders` for custom auth headers; `extra_headers` and `extraHeaders` are accepted as aliases | | `MIDSCENE_MODEL_EXTRA_BODY_JSON` | JSON blob merged into each model request body. It takes precedence when merging request parameters: if a parameter conflicts with one generated by another environment variable, the value in this JSON is used. Unlike `MIDSCENE_MODEL_INIT_CONFIG_JSON` (which configures the SDK client), this is spread into every protocol request sent to the model, e.g. enabling thinking mode in vLLM: `'{"chat_template_kwargs":{"enable_thinking":true}}'` | | `MIDSCENE_MODEL_PROTOCOL` | Model API protocol: `openai-chat` (default) or `openai-responses`. For Responses API support requirements, see [Use the Responses API](#model-api-type). | | `MIDSCENE_MODEL_AUTH_MODE` | Authentication mode: `api-key` (default) uses the configured API Key; `siwc` uses credentials saved after ChatGPT authorization and automatically refreshes access tokens. For setup instructions, see [Use your ChatGPT subscription](/chatgpt-subscription.md). | | `MIDSCENE_MODEL_STREAM_MODE` | Defaults to non-streaming (`non-stream`). When set to `stream`, streamed results are aggregated into a complete result before parsing. | ### Use the Responses API {#model-api-type} Midscene uses Chat Completions (`openai-chat`) by default. Among the built-in model adapters, only `gpt-5` and `gpt-6` currently support the Responses API. Setting `openai-responses` for another model family causes an unsupported-protocol error. For the official OpenAI endpoint, add the following to your GPT model configuration: ```bash MIDSCENE_MODEL_BASE_URL="https://api.openai.com/v1" MIDSCENE_MODEL_PROTOCOL="openai-responses" ``` Set the model name, API key, and family as shown in the [GPT configuration example](/model-api-setup.md#gpt). Do not append `/responses` to the Base URL; the SDK adds it automatically. The Responses API is not restricted to the official OpenAI endpoint. Azure OpenAI and other compatible endpoints can also be used, but both the endpoint and the selected GPT model must support this protocol. Chat Completions compatibility alone does not imply Responses compatibility. See the [Azure OpenAI FAQ](/faq.md) for configuration and the verified coordinate-offset scenario. For a dedicated GPT model, use `MIDSCENE_PLANNING_MODEL_PROTOCOL`, `MIDSCENE_LOCATE_MODEL_PROTOCOL`, or `MIDSCENE_INSIGHT_MODEL_PROTOCOL` for the corresponding role. Each model's protocol is configured independently and does not affect the others. ### Model-native thinking {#model-native-reasoning} Midscene disables model-native thinking by default for better execution speed and stability. If a model cannot disable native thinking, Midscene reduces it as much as possible by controlling the thinking granularity or budget. The following environment variables provide a unified Midscene abstraction over provider-specific parameters. The parameters sent to the model depend on `MIDSCENE_MODEL_FAMILY`. `MIDSCENE_MODEL_REASONING_ENABLED` explicitly controls whether model-native thinking is enabled: - `false`: Force-disable model-native thinking. This is the Midscene default. - `true`: Force-enable model-native thinking and apply explicitly configured effort and budget settings supported by the model. - `default`: Follow the model's default behavior. Midscene does not send a parameter that enables or disables thinking, and it ignores explicit `MIDSCENE_MODEL_REASONING_BUDGET` and `MIDSCENE_MODEL_REASONING_EFFORT` settings. This lets you change just one setting to leave thinking behavior entirely to the model provider. Model-specific thinking parameter mappings Models differ in their support for thinking effort and budget parameters. - `MIDSCENE_MODEL_REASONING_BUDGET` controls the thinking token budget. Qwen Plus and other model series support this setting. - `MIDSCENE_MODEL_REASONING_EFFORT` controls thinking effort. Doubao, DeepSeek, Gemini, GPT, Tencent Hunyuan, Kimi, and other model series support this setting. The code implementation is the source of truth for specific model support and parameter mappings. Parameter support varies by model provider. Refer to the provider's official documentation for accepted values. For official model endpoints, Midscene ignores explicit settings that the current adapter does not support. OpenRouter provides [unified reasoning parameters](https://openrouter.ai/docs/guides/best-practices/reasoning-tokens). When `MIDSCENE_MODEL_BASE_URL` is set to `https://openrouter.ai/api/v1`, Midscene uses the following mappings for adapted models: - Thinking switch `MIDSCENE_MODEL_REASONING_ENABLED` → `reasoning.enabled` (GPT models use `reasoning.effort` instead). - Thinking effort `MIDSCENE_MODEL_REASONING_EFFORT` → `reasoning.effort` (support depends on the specific model). - Thinking budget `MIDSCENE_MODEL_REASONING_BUDGET` → `reasoning.max_tokens` (support depends on the specific model). If your model provider requires additional parameters, use `MIDSCENE_MODEL_EXTRA_BODY_JSON`. For example, to request disabled thinking when calling OpenRouter through a custom proxy: ```bash MIDSCENE_MODEL_EXTRA_BODY_JSON='{"reasoning":{"enabled":false}}' ``` Extra JSON is merged after adapter parameters. Matching top-level fields are replaced in full, not deep-merged. Whether parameters take effect depends on endpoint and model support. ## Troubleshooting ### Common configuration errors {#common-configuration-errors} **`MIDSCENE_MODEL_FAMILY` is not set to a multimodal model** If you see `MIDSCENE_MODEL_FAMILY is not set to a multimodal model with UI localization`, make sure the `MIDSCENE_MODEL_FAMILY` environment variable for the multimodal model is set correctly. Starting with version 1.0, Midscene recommends using `MIDSCENE_MODEL_FAMILY` to specify the multimodal model type. Legacy `MIDSCENE_USE_...` settings remain compatible but are deprecated. See [Use a model API key](/model-api-setup.md) for the correct model family and a complete configuration example. **Base URL or model name is incorrect** Confirm that `MIDSCENE_MODEL_BASE_URL` points to the provider's API endpoint. It commonly ends with a version such as `/v1`. Do not append `/chat/completions` or `/responses`; the underlying SDK adds the request path based on the selected API type. Also confirm that `MIDSCENE_MODEL_NAME` matches a model available from that endpoint. ### When model results are unreliable {#when-model-results-are-unreliable} If the model connects successfully but produces incorrect actions, misses targets, or misinterprets the page: - Check the [replay report](/consume-report-file.md) to identify where the task went wrong. - Try a newer supported model version or compare models on representative tasks. - If failures concentrate in planning, localization, or page understanding, consider a [dedicated model for that intent](#dedicated-models). See the [Model Selection Guide](/model-selection.md) for model choices and role descriptions. ## Debugging capabilities ### Debug logs Set `DEBUG` when you need additional diagnostic output. Common selectors include: - `DEBUG=midscene:ai:profile:stats` prints model latency and Token usage. - `DEBUG=midscene:ai:call` prints AI response details. - `DEBUG=midscene:*` prints all Midscene Debug logs. For the complete selector list, log location, and handling notes, see [Runtime configuration: Debug logs](/reference.md#debug-logs). Usage statistics are also available in generated [report files](/consume-report-file.md). ### Record model calls Set `MIDSCENE_RECORD_MODEL_CALL=true` to write model requests, responses, and streaming chunks to a JSONL file: ```text midscene_run/model-requests/<start-time>-<pid>.jsonl ``` Each process creates one file, with one JSON event per line. Local recording is available only in Node.js and Electron. Browsers and Workers do not write local files. Codex App Server records also include available protocol metadata. Every event has a `type` of `request`, `chunk`, `response`, or `error`. It also includes an `executionId` that groups calls and retries under the same execution ID. For HTTP model requests, this value is also sent in the `x-midscene-execution-id` header. Calls outside a report execution, such as connectivity checks, use a generated ID prefixed with `unscoped-`. :::warning Security considerations Model-call records contain request bodies (including custom `extraBody`), response headers and bodies, streaming responses, and possibly base64-encoded screenshots. Request headers are not recorded. - Enable recording only while troubleshooting. Files may be large; protect or delete them afterward. The record format is not stable across versions. - Do not commit `.env` files, traces, debug logs, or model-call records to source control. - Review logs, traces, and model-call records before sharing them because they can contain model inputs, outputs, or screenshots. ::: ### Request tracing headers Midscene automatically adds the following headers to OpenAI-compatible HTTP model requests: | Header | Value | Purpose | | ------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------- | | `x-midscene-version` | The current `@midscene/core` version | Identify the Midscene version that sent the request | | `x-midscene-execution-id` | The current execution ID | Group all model requests and retries under the same execution ID, such as an `aiAct` call | Calls outside a report execution, such as connectivity checks, use a generated execution ID prefixed with `unscoped-`. These two headers are sent by default; if headers with the same names are customized in `MIDSCENE_*_INIT_CONFIG_JSON`, Midscene overrides them. ## Observability platforms The automatic integrations below wrap the OpenAI SDK client used for OpenAI-compatible HTTP requests. They do not apply to Codex App Server or Jev's System One protocol. Notes: - LangSmith and Langfuse can be enabled simultaneously. - This integration supports Node.js only. Browser environments throw an error. - [`createOpenAIClient`](/reference.md#custom-openai-client) receives the original OpenAI client. If the callback returns a client, that client replaces the automatically wrapped client; apply any tracing wrappers you need inside the callback. If it returns no client, the automatic integrations remain in effect. ### LangSmith LangSmith is a platform for debugging large language models. Midscene provides automatic integration support through a dependency and environment variables. **Install the dependency** ```bash npm install langsmith ``` **Set environment variables** ```bash # Enable Midscene's LangSmith auto-integration export MIDSCENE_LANGSMITH_DEBUG=1 # LangSmith configuration export LANGCHAIN_API_KEY="your-langchain-api-key-here" export LANGCHAIN_TRACING=true export LANGCHAIN_ENDPOINT="https://api.smith.langchain.com" # export LANGCHAIN_ENDPOINT="https://eu.api.smith.langchain.com" # If signed up in the EU region ``` When Midscene creates an OpenAI client for a model request, it logs the enabled wrapper: ```log DEBUGGING MODE: langsmith wrapper enabled ``` For finer-grained control, such as enabling LangSmith only for specific tasks, use [`createOpenAIClient`](/reference.md#custom-openai-client) to wrap the client manually. ### Langfuse [Langfuse](https://langfuse.com) is an LLM observability platform. Midscene integrates Langfuse's `observeOpenAI` wrapper to trace OpenAI API calls automatically. Because Langfuse tracing uses OpenTelemetry, initialize the OpenTelemetry SDK when the application starts. **Install the dependencies** ```bash npm install @langfuse/openai @langfuse/otel @opentelemetry/sdk-node ``` **Initialize OpenTelemetry** Add this code at the very top of the application entry file: ```typescript import { NodeSDK } from "@opentelemetry/sdk-node"; import { LangfuseSpanProcessor } from "@langfuse/otel"; const sdk = new NodeSDK({ spanProcessors: [new LangfuseSpanProcessor()], }); sdk.start(); ``` **Set environment variables** ```bash # Enable Midscene's Langfuse auto-integration export MIDSCENE_LANGFUSE_DEBUG=1 # Langfuse configuration export LANGFUSE_PUBLIC_KEY="your-langfuse-public-key-here" export LANGFUSE_SECRET_KEY="your-langfuse-secret-key-here" export LANGFUSE_BASE_URL="https://cloud.langfuse.com" # 🇪🇺 EU region # export LANGFUSE_BASE_URL="https://us.cloud.langfuse.com" # 🇺🇸 US region ``` When Midscene creates an OpenAI client for a model request, it logs the enabled wrapper: ```log DEBUGGING MODE: langfuse wrapper enabled ``` This log identifies the wrapper being enabled; it does not confirm that traces reached Langfuse. Run a model request and check your Langfuse project to verify trace delivery. See the [Langfuse OpenAI integration documentation](https://langfuse.com/integrations/model-providers/openai-js) for more configuration options and best practices. ## Legacy configuration These settings remain supported; use the replacements below for new configurations. | Legacy setting | Replacement / notes | | ---------------------------------- | ------------------------------------------------------------------------------------------------- | | `MIDSCENE_USE_DOUBAO_VISION` | Use `MIDSCENE_MODEL_FAMILY="doubao-vision"` | | `MIDSCENE_USE_QWEN3_VL` | Use `MIDSCENE_MODEL_FAMILY="qwen3-vl"` | | `MIDSCENE_USE_QWEN_VL` | Use `MIDSCENE_MODEL_FAMILY="qwen2.5-vl"` | | `MIDSCENE_USE_GEMINI` | Use `MIDSCENE_MODEL_FAMILY="gemini"` | | `MIDSCENE_USE_VLM_UI_TARS` | Use `MIDSCENE_MODEL_FAMILY="vlm-ui-tars"` | | `OPENAI_API_KEY` | Prefer `MIDSCENE_MODEL_API_KEY` | | `OPENAI_BASE_URL` | Prefer `MIDSCENE_MODEL_BASE_URL` | | `MIDSCENE_OPENAI_INIT_CONFIG_JSON` | Prefer `MIDSCENE_MODEL_INIT_CONFIG_JSON` | | `MIDSCENE_OPENAI_HTTP_PROXY` | Prefer `MIDSCENE_MODEL_HTTP_PROXY` | | `MIDSCENE_OPENAI_SOCKS_PROXY` | Prefer `MIDSCENE_MODEL_SOCKS_PROXY` | | `MIDSCENE_REPLANNING_CYCLE_LIMIT` | Use the Agent option `replanningCycleLimit`, which takes precedence over the environment variable | --- url: /model-selection.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Model Selection Guide This guide introduces the models supported by Midscene, two ways to connect them, and when to use one Default model or combine multiple models. ## Supported models Midscene supports these multimodal models for operating user interfaces: [Doubao Seed](/model-api-setup.md#doubao-seed-model), [Qwen](/model-api-setup.md#qwen), [DeepSeek](/model-api-setup.md#deepseek), [Google Gemini](/model-api-setup.md#gemini), [OpenAI GPT](/model-api-setup.md#gpt), [Moonshot Kimi](/model-api-setup.md#kimi), [Xiaomi MiMo](/model-api-setup.md#xiaomi-mimo), [Zhipu GLM-V](/model-api-setup.md#glm-v), [Ant Ling](/model-api-setup.md#ant-ling), and [Jev (experimental)](/model-api-setup.md#jev), as well as the other compatible models [AutoGLM](/model-api-setup.md#auto-glm) and [UI-TARS](/model-api-setup.md#ui-tars). ## Choose a connection method Midscene supports two ways to connect a model. Choose either one: - **Model API key**: Use an API key from a model provider to connect to the models listed above. See [Use a model API key](/model-api-setup.md). - **ChatGPT subscription**: Sign in and authorize Midscene to call GPT models using your ChatGPT subscription. Available models depend on your account. See [Use a ChatGPT subscription](/chatgpt-subscription.md). ## Start with one Default model Configure one multimodal Default model for planning, localization, and insight. This works for most scenarios. See [Use a model API key](/model-api-setup.md) for supported models and configuration examples, or choose [Use a ChatGPT subscription](/chatgpt-subscription.md). ## Use multi-model capabilities to handle complex scenarios {#multi-model-strategy} Midscene supports combining multiple models to handle complex scenarios. A single automation task may require multi-step planning, precise element localization, and data extraction or result evaluation. Different models have different strengths across these capabilities. Keep the Default model and add Planning, Locate, or Insight models to divide the work according to those strengths within the same task. For example, use a stronger planning model for long workflows with conditional branches, a localization model for difficult UI targets, or an insight model for complex assertions and structured data extraction. Configure each role independently; you do not need to add every specialized model at once. Any role without a dedicated model continues to use the Default model: | Model | Responsibility | | -------------- | ---------------------------------------------------------------------------------------------------- | | Default model | Required base configuration providing all capabilities; any role without a specialized model uses it | | Planning model | Planning for complex goals, multiple steps, and branching scenarios | | Locate model | Independent element localization, including action targets and `deepLocate` | | Insight model | Data extraction, assertions, and page understanding | Combining models can increase latency and token usage. Use [Model advanced configuration and debugging](/model-config.md#verify-model-connectivity) to identify the problem, then [configure multiple models](/model-config.md#multi-model-combination-example) as needed. --- url: /platforms/android.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Android environment setup Midscene connects to and controls Android devices over `adb`, supporting UI automation across native apps, hybrid apps, and system interfaces. This guide prepares the Android environment: install adb and connect the device. Playground, Midscene Test, and the JavaScript SDK all use this connection. ## Connect the device through adb {#connect-device} Midscene uses `adb` on your computer to communicate with the target Android device over either USB or wireless `adb`. If `adb` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install adb - Install `adb` via [Android Studio](https://developer.android.com/studio) or the standalone [Android command-line tools](https://developer.android.com/studio#command-line-tools-only). - Run the following command to verify the installation: ```bash adb --version ``` Output similar to the following confirms a working installation: ```log Android Debug Bridge version 1.0.41 Version 34.0.4-10411341 Installed as /usr/local/bin/adb Running on Darwin 24.3.0 (arm64) ``` - Configure the `ANDROID_HOME` environment variable as described in [Android environment variables](https://developer.android.com/tools/variables), then check that it takes effect: ```bash echo $ANDROID_HOME ``` The output should point to your local Android SDK directory, for example: ```log /Users/your_username/Library/Android/sdk ``` ### Enable debugging and connect the device The steps below use a USB connection as an example. If your device is already connected over wireless `adb`, you can keep using that connection. 1. In your phone's **Developer options**, enable **USB debugging** (and **USB debugging (Security settings)** if available, so Midscene can inject touch events). 2. Connect the phone to your computer using a USB cable that supports data transfer. 3. Keep the phone unlocked and accept the **Allow USB debugging** prompt on the screen. ![android usb debug](/images/android-usb-debug-en.png) ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash adb devices -l ``` When the device status shows `device`, the connection is ready: ```log List of devices attached s4ey59 device usb:34603008X product:cezanne model:M2006J device:cezan transport_id:3 ``` If multiple devices are connected, note the device ID in the first column (such as `s4ey59` above) so you can select the target device in Playground or your project configuration. If the target device does not appear with the `device` status, check the following: - **Empty list**: For USB, check the data cable (ensure it is not charge-only), USB connection mode, and **USB debugging** toggle; for wireless `adb`, check the network and `adb connect` status. - **`unauthorized`**: Unlock the phone screen and accept the **Allow USB debugging** prompt on the device. - **`offline`**: Reconnect the USB cable or wireless `adb` session, and restart `adb` if needed. Proceed only after the status shows `device`. ## Verify {#verify} When `adb devices -l` shows the target device with the `device` status, verify the environment in Playground. Open [Get started](/get-started.md?platform=android\&scene=playground), where Android and Playground are already selected, choose how to connect a model, and follow the steps to run one `aiAct` action and one `aiAssert` assertion. A passing assertion confirms that the adb connection, screen capture, touch input, and model calls work together. ## FAQ {#faq} ### The device is missing, unauthorized, or offline Run `adb devices -l` and follow the troubleshooting steps in [Verify the device connection](#verify-device-connection) to check the USB cable, debugging authorization, and connection status. Make sure the target device status is `device` before investigating screenshot or input issues. ### Why can't I control the device even though it is connected (`INJECT_EVENTS` error)? If tapping or swiping fails with a permission error like the following: ```text Error: Exception occurred while executing 'tap': java.lang.SecurityException: Injecting input events requires the caller (or the source of the instrumentation, if any) to have the INJECT_EVENTS permission. ``` Some Android OEM ROMs (such as Xiaomi / MIUI / HyperOS, vivo, and OPPO) require an additional toggle in **Developer options** to allow simulated input. Make sure both of the following options are enabled: 1. **USB debugging** 2. **USB debugging (Security settings)** or **Disable permission monitoring** (if present) ![android usb debug](/images/android-usb-debug-en.png) ### Text input is cleared or disappears after typing If text is entered properly but disappears when the soft keyboard closes, the input field may be clearing its value in response to the `ESC` key event sent to dismiss the keyboard. You can customize the keyboard dismissal strategy; see the [Android JavaScript SDK guide](/sdk/android.md#text-input-is-cleared-or-disappears-after-typing) for options and examples. ### English text is altered by the Android input method Compare the input value recorded in the execution report with the text actually entered into the field. If the value in the report is correct but characters in the input field are reordered, missing, or intercepted by Pinyin composition, check the active input method and autocorrect settings on the device. See the [Android JavaScript SDK guide](/sdk/android.md#english-text-is-altered-by-the-android-input-method) for details on input channels. ### Screenshots of secure pages (such as password inputs) are black First switch to a regular page and check whether screenshots work normally. If only password screens or sensitive pages appear black, the app likely enables system screenshot protection (`FLAG_SECURE`) rather than `adb` being disconnected. See the [Android JavaScript SDK guide](/sdk/android.md#screenshots-of-secure-pages-such-as-password-inputs-are-black) for screenshot mechanisms and limitations. ### Why does scrcpy fall back to ADB screenshots? To prevent the AI model from acting on stale frames, Midscene strictly validates scrcpy frame timestamps: any frame that cannot be proven to have been captured after the most recent completed action—or that exceeds the maximum frame age limit—is rejected. If the active scrcpy stream fails to deliver a fresh frame in time, Midscene automatically restarts scrcpy once, and falls back to `adb` screenshots only if the restarted stream also fails. This commonly occurs when an Android hardware encoder pauses frame output on a completely static screen, or during stream startup and transient USB transport hiccups. Note that a frame-freshness warning alone does not indicate insufficient bandwidth or an excessive video bitrate—do not adjust the video bitrate solely in response to this warning. ### How do I configure the scrcpy video bitrate? See the [Android JavaScript SDK guide](/sdk/android.md#how-do-i-configure-the-scrcpy-video-bitrate). ### How do I access Android Playground remotely from another machine on the LAN? By default, both the Playground server and its built-in scrcpy streaming server bind only to `127.0.0.1`. To access Android Playground from another computer on your network, explicitly bind both servers to a reachable interface via environment variables (for example, on macOS or Linux): ```bash MIDSCENE_PLAYGROUND_HOST=0.0.0.0 MIDSCENE_SCRCPY_HOST=0.0.0.0 pnpm dlx @midscene/android-playground ``` Then open Playground in a browser using the host machine's LAN IP address (or hostname) and the Playground port printed at startup (note that `0.0.0.0` is a wildcard bind address, not a URL you can open in a browser), and ensure your firewall allows incoming connections on both the Playground and scrcpy ports. `MIDSCENE_SCRCPY_HOST` applies to the standalone Android Playground CLI and can also be set to a specific local network IP (such as `192.168.1.100`, which the auto-opened local preview page will also use). If you instantiate `ScrcpyServer` directly in code, pass the `host` option to its constructor instead. :::warning Security Notice The scrcpy streaming server does not currently authenticate viewer sessions. Binding it to a network interface exposes device information and live screen streams to any client that can reach the port. Enable remote access only on trusted private networks and restrict access with firewall rules. ::: ### How do I use a custom adb path or remote adb server? See the [Android JavaScript SDK guide](/sdk/android.md#how-do-i-use-a-custom-adb-path-or-remote-adb-server). --- url: /platforms/desktop.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Desktop environment setup Midscene automates desktop applications across Windows, macOS, and Linux using native mouse and keyboard controls or Remote Desktop Protocol (RDP), with built-in multi-display support. It works with Electron, Qt, native desktop apps, and cross-application workflows. This guide prepares the desktop environment: grant screen capture and input permissions, and install the dependencies Linux needs. Playground, Midscene Test, and the JavaScript SDK all rely on them. ## Prepare the desktop environment {#connect-device} Midscene requires screen capture and mouse/keyboard control permissions on the target desktop. Configure local desktop control or a remote Windows desktop (RDP) below. ### Local desktop permissions and dependencies - **macOS**: Grant two separate system permissions to the terminal or IDE that launches Playground or runs your scripts (such as Terminal, iTerm2, VS Code, Cursor, or WebStorm): 1. **Accessibility** (for mouse and keyboard control): Enable your terminal or IDE in **System Settings > Privacy & Security > Accessibility** (see [nut.js macOS setup](https://github.com/nut-tree/nut.js#macos)). 2. **Screen Recording** (for desktop screenshots): Enable your terminal or IDE in **System Settings > Privacy & Security > Screen Recording**. **After granting access, completely quit and relaunch the terminal or IDE** before starting Playground. - **Windows**: No extra setup is required for standard applications. However, Windows User Interface Privilege Isolation (UIPI) blocks non-elevated processes from injecting mouse clicks or keystrokes into windows running **as Administrator** (the cursor still moves to the target coordinates, but clicks and key presses are silently dropped). Prefer running the target app without Administrator privileges; if it must run elevated, launch the terminal or Node.js process running Midscene **as Administrator** as well (see [Windows: clicks have no effect on some apps](/platforms/desktop.md#windows-clicks-have-no-effect-on-some-apps)). - **Linux (desktop GUI)**: Install [ImageMagick](https://imagemagick.org/script/download.php) for screen capture support. - **Linux (headless server / CI)**: To run desktop automation on a headless Linux host (such as GitHub Actions), install Xvfb and ImageMagick, then enable headless mode to start a virtual display automatically: ```bash # Install dependencies sudo apt-get install -y xvfb x11-xserver-utils imagemagick ``` When using Xvfb, make sure the target application is started inside the same virtual display environment (not needed on machines with a physical display). ### Remote Windows desktop over RDP (optional) To automate a remote Windows desktop over RDP, install FreeRDP on the machine running Midscene and enable Remote Desktop on the target Windows host. Playground controls local displays only. To connect to a remote Windows session in code, see [RDP options in the Desktop JavaScript SDK](/sdk/desktop.md#rdp-options). ## Verify {#verify} When you grant the permissions and install the dependencies above, verify the environment in Playground. Open [Get started](/get-started.md?platform=desktop\&scene=playground), where Desktop and Playground are already selected, choose how to connect a model, and follow the steps to run one `aiAct` action and one `aiAssert` assertion. A passing assertion confirms that screen capture, mouse and keyboard input, and model calls work together. ## FAQ {#faq} ### macOS: Script cannot move the mouse or press keys Controlling the mouse and keyboard on macOS requires Accessibility permissions. Open **System Settings > Privacy & Security > Accessibility** and make sure the toggle is enabled for the terminal or IDE running your script (such as Terminal, iTerm2, VS Code, Cursor, or WebStorm). If the toggle is already enabled but input still does not work, remove the app from the Accessibility list (using the `-` button), add it back, and restart the app—macOS occasionally caches stale permission signatures after app updates. ### Windows: Clicks have no effect on some apps If the mouse cursor moves to the right coordinates but clicks or keystrokes have no effect on a specific application window (while working normally in other apps like a browser or Notepad), check whether the target application is running **as Administrator** (elevated). Windows User Interface Privilege Isolation (UIPI) silently drops input events sent from a standard-privilege process to an elevated window without throwing an error. How to fix it: 1. **Recommended**: Run the target application with standard user privileges (uncheck "Run this program as an administrator" in its shortcut or compatibility properties). 2. **Alternative**: If the target application must run as Administrator, launch the terminal (such as PowerShell, Windows Terminal, or your IDE) running Midscene **as Administrator** as well so both processes share the same privilege level. > Note: System-level shortcuts such as `Win+Tab` are handled directly by the Windows shell and still work even when UIPI blocks in-window input, which is why global shortcuts may work while clicks inside the app do not. Whenever the cursor reaches the right spot but clicks do nothing, check for privilege elevation first. ### Linux: Screenshots or interactions fail on a headless server Headless Linux environments (such as CI containers) have no physical display. Install Xvfb and ImageMagick, and enable `headless` mode when creating the Agent: ```bash sudo apt-get install -y xvfb x11-xserver-utils imagemagick ``` Enable in code: ```typescript const agent = await agentForComputer({ headless: true }); ``` Or enable via an environment variable: ```bash MIDSCENE_COMPUTER_HEADLESS_LINUX=true npx tsx example.ts ``` --- url: /platforms/harmonyos.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # HarmonyOS environment setup Midscene connects to and controls HarmonyOS NEXT devices through HarmonyOS Device Connector (HDC), supporting UI automation across native apps, atomic services, and system interfaces. This guide prepares the HarmonyOS environment: install HDC and connect the device. Playground, Midscene Test, and the JavaScript SDK all use this connection. ## Connect the device through HDC {#connect-device} Midscene uses `hdc` on your computer to communicate with the target HarmonyOS NEXT device. If `hdc` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install HDC HDC (HarmonyOS Device Connector) is the official command-line tool for communicating with HarmonyOS devices. Install it using either of the following methods: - Via [DevEco Studio](https://developer.huawei.com/consumer/en/deveco-studio/) (recommended) - Via the standalone [HarmonyOS Command Line Tools](https://developer.huawei.com/consumer/en/download/) Run the following command to verify the installation: ```bash hdc version ``` A version number in the terminal output confirms a working installation. :::info Configuring the HDC path If `hdc` is not in your system `PATH`, set the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` ::: ### Enable debugging and connect the device 1. On your HarmonyOS device, open **Settings > System > Developer options** and enable **USB debugging**. 2. Connect the device to your computer using a USB cable that supports data transfer. 3. Keep the device unlocked and accept the debugging authorization prompt on the screen. ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash hdc list targets ``` A device ID in the output confirms that the device is connected and ready: ```log 0123456789ABCDEF ``` If multiple devices are connected, note the target device ID so you can select it in Playground or your project configuration. If the output is empty or `[Empty]`, check the USB cable, USB connection mode, **USB debugging** toggle, and the authorization prompt on the device. ## Verify {#verify} When `hdc list targets` lists the target device, verify the environment in Playground. Open [Get started](/get-started.md?platform=harmonyos\&scene=playground), where HarmonyOS and Playground are already selected, choose how to connect a model, and follow the steps to run one `aiAct` action and one `aiAssert` assertion. A passing assertion confirms that the HDC connection, screen capture, touch input, and model calls work together. ## FAQ {#faq} ### Keyboard is not dismissed or the page navigates back after typing See the [HarmonyOS JavaScript SDK guide](/sdk/harmonyos.md#keyboard-is-not-dismissed-or-the-page-navigates-back-after-typing). ### How do I specify a custom HDC path? Point the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` For configuring the path via constructor options in code, see the [HarmonyOS JavaScript SDK guide](/sdk/harmonyos.md#how-do-i-specify-a-custom-hdc-path). --- url: /platforms/index.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Platform environment setup Each platform guide prepares one environment: the connection tools, device connection, and system permissions that Midscene needs. Playground, Midscene Test, and the JavaScript SDK all use the same environment. Each guide ends with a Verify section that checks the environment in Playground. Midscene uses multimodal vision models to understand screenshots, operating directly on the rendered UI rather than relying on the underlying DOM or native view hierarchy. This allows the same interaction and assertion approach to work across native apps and cross-platform frameworks alike. ## Choose a platform | Platform | npm package | Connection method | Typical use cases | | ------------------------------------ | -------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------- | | [Web](/platforms/web.md) | `@midscene/web` | Chrome extension (Playground); Playwright / Puppeteer (SDK integration) | Web testing and browser automation | | [Chrome Bridge](/bridge-mode.md) | `@midscene/web` | Chrome extension | Reusing existing login sessions and tabs in desktop Chrome | | [Android](/platforms/android.md) | `@midscene/android` | `adb` | Android apps and system UI automation | | [iOS](/platforms/ios.md) | `@midscene/ios` | WebDriverAgent | iOS apps and system UI automation | | [HarmonyOS](/platforms/harmonyos.md) | `@midscene/harmony` | HDC | HarmonyOS NEXT apps and system UI automation | | [Desktop](/platforms/desktop.md) | `@midscene/computer` | Native mouse/keyboard or RDP | Windows, macOS, and Linux desktop application automation | --- url: /platforms/ios.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # iOS environment setup Midscene connects to and controls iOS devices through WebDriverAgent (WDA), supporting UI automation across native apps, hybrid apps, and system interfaces. This guide prepares the iOS environment: build and start WDA, then make it reachable from the computer that runs Midscene. Playground, Midscene Test, and the JavaScript SDK all use this connection. ## Connect the device through WDA {#connect-device} Midscene communicates with iOS physical devices and simulators through a running WebDriverAgent (WDA) service. If WDA is already running and reachable from your computer, skip directly to [Verify the WDA service status](#verify-wda-status). ### Build and start WebDriverAgent Before you begin, prepare the following iOS development environment: - macOS (required for iOS development and device debugging) - Xcode and Xcode Command Line Tools - An iOS Simulator or physical iOS device :::info Version requirement WebDriverAgent version must be **>= 7.0.0**. ::: Follow the official Appium documentation to build and start WebDriverAgent (WDA): - **Simulator setup**: [Run Prebuilt WDA](https://appium.github.io/appium-xcuitest-driver/latest/guides/run-prebuilt-wda/) - **Physical device setup**: [Real Device Configuration](https://appium.github.io/appium-xcuitest-driver/latest/getting-started/device-setup/) ### Configure a physical device and forward the port iOS Simulators expose WDA directly on `localhost` and do not require port forwarding—if you are using a simulator or a remote WDA service, skip to [Verify the WDA service status](#verify-wda-status). When using a physical iOS device: 1. Connect the device to your Mac via USB and tap **Trust This Computer** when prompted on the device. 2. Enable **Developer Mode** (**Settings > Privacy & Security > Developer Mode**) and **UI Automation** (**Settings > Developer > Enable UI Automation**) on the device. 3. After signing and starting WDA on the device, use `iproxy` (installable via `brew install libimobiledevice`) to forward the WDA port (`8100` by default) from the device to your Mac: ```bash iproxy 8100 8100 YOUR_DEVICE_ID ``` Replace `YOUR_DEVICE_ID` with your device's UDID, and keep both WDA and `iproxy` running. When connecting multiple devices or using custom ports, forward each device to a distinct local port and use that port in Playground or your project configuration. ### Verify the WDA service status {#verify-wda-status} Open the WDA `/status` endpoint in your browser or terminal from the computer running Midscene: - **Default local URL**: `http://localhost:8100/status` (if using a custom port, remote host, or gateway, use the actual service address) - **Expected JSON response**: ```json { "value": { "build": { "version": "10.1.1", "time": "Sep 24 2025 18:56:41", "productBundleIdentifier": "com.facebook.WebDriverAgentRunner" }, "os": { "testmanagerdVersion": 65535, "name": "iOS", "sdkVersion": "26.0", "version": "26.0" }, "device": "iphone", "ios": { "ip": "10.91.115.63" }, "message": "WebDriverAgent is ready to accept commands", "state": "success", "ready": true }, "sessionId": "BCAD9603-F714-447C-A9E6-07D58267966B" } ``` A JSON response containing `"ready": true` confirms that WDA is ready to accept commands. Note the WDA host and port (or gateway base URL) so you can use the same connection settings in Playground and your project. ## Verify {#verify} When the WDA `/status` endpoint returns `"ready": true`, verify the environment in Playground. Open [Get started](/get-started.md?platform=ios\&scene=playground), where iOS and Playground are already selected, choose how to connect a model, and follow the steps to run one `aiAct` action and one `aiAssert` assertion. A passing assertion confirms that WDA, screen capture, touch input, and model calls work together. ## FAQ {#faq} ### Why can't I control my physical device even though WebDriverAgent is connected? Check the following settings on your iOS device: 1. **Developer Mode**: Make sure **Settings > Privacy & Security > Developer Mode** is enabled and the device has been restarted. 2. **UI Automation**: Make sure **Settings > Developer > Enable UI Automation** is turned on. 3. **Computer Trust**: Reconnect the USB cable and make sure you have tapped **Trust This Computer** on the device prompt. ### What are the differences between iOS Simulators and physical devices? | Feature | Physical Device | iOS Simulator | | -------------------- | ------------------------------------------- | -------------------------------------------- | | Port forwarding | Requires `iproxy` | Not required (listens on localhost directly) | | Developer Mode | Must be enabled manually | Enabled by default | | UI Automation toggle | Must be enabled in **Settings > Developer** | Enabled by default | | Performance | Real hardware performance | Depends on host Mac performance | | Hardware sensors | Real sensors | Simulated data | ### How do I customize the WebDriverAgent port and host? See the [iOS JavaScript SDK guide](/sdk/ios.md#how-do-i-customize-the-webdriveragent-port-and-host). ### How do I get a smoother live screen preview in Playground? iOS Playground supports two screen preview modes: - **Polling mode** (default): Captures screenshots sequentially via the WDA screenshot endpoint at roughly 5–10 fps. - **Native MJPEG stream** (recommended): Connects directly to WDA's built-in MJPEG server for higher frame rates and lower latency. To enable the native MJPEG stream on a physical device, forward WDA's MJPEG port (`9100` by default) to your Mac (not required for Simulators): ```bash iproxy 9100 9100 YOUR_DEVICE_ID ``` Playground automatically probes local port `9100` on startup: if available, the terminal logs `MJPEG: streaming via native WDA MJPEG server`; otherwise, it falls back to polling mode automatically. --- url: /platforms/web.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Web environment setup Midscene controls web pages in one of three browsers: the Midscene Chrome extension, a browser launched by Playwright or Puppeteer, or your desktop Chrome through [Chrome Bridge](/bridge-mode.md). This guide prepares each of them. Prepare only the one you plan to use. ## Chrome extension {#chrome-extension} The extension runs Playground in desktop Chrome and needs no project or Node.js. 1. Install Midscene from the Chrome Web Store: [Install the Midscene extension from the Chrome Web Store](https://chromewebstore.google.com/detail/midscene/gbldofcpkknbggpkmbdaefngejllnief) 2. Open **Midscene** from the Chrome extensions list. The Midscene sidebar appears on the right side of the browser. Model settings saved in the extension stay in the browser. Tests and scripts read their own model configuration. ## Playwright {#playwright} Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. In your project directory, run `pnpm init` if there is no `package.json` yet, then install the dependencies and Chromium: ```bash pnpm add -D @midscene/web playwright pnpm exec playwright install chromium ``` A Midscene Test Web project already depends on Playwright. Run only `pnpm exec playwright install chromium` in that project. ## Puppeteer {#puppeteer} ```bash pnpm add -D @midscene/web puppeteer ``` Allow Puppeteer to download its bundled browser during installation. If you use a custom browser binary or a remote browser, make sure the executable path or CDP endpoint is reachable. For connection options, see [Integrate with Puppeteer](/integrate-with-puppeteer.md). ## Chrome Bridge {#chrome-bridge} To reuse the tabs, login sessions, or extensions of your desktop Chrome, install the [Chrome extension](#chrome-extension), then follow [Chrome Bridge environment setup](/bridge-mode.md) to verify that a script can control Chrome through it. ## Verify {#verify} Verify the Chrome extension in Playground. Open [Get started](/get-started.md?platform=web\&scene=playground), where Web and Playground are already selected, choose how to connect a model, and follow the steps to run one `aiAct` action and one `aiAssert` assertion. A passing assertion confirms that the extension and model calls work. Playground runs in the extension and does not use the Playwright or Puppeteer browser. To verify that browser, choose **Create a Midscene Test project** or **Add to a JavaScript test project** on the same page; the first test run uses it. For Chrome Bridge, run the [connection check](/bridge-mode.md#verify-connection). ## FAQ {#faq} ### Can I install the Chrome extension manually? If you cannot access the Chrome Web Store, download the installation package from the [GitHub Releases page](https://github.com/web-infra-dev/midscene/releases) and install it manually. Manual installations do not receive automatic updates. ### It fails with `Cannot access a chrome-extension:// URL of different extension` This error usually indicates a conflict between Midscene and another Chrome extension. For example, another Chrome extension may have injected an `<iframe />` or `<script />` into the page. Follow these steps to find the conflicting Chrome extension: 1. Open the page's developer tools, find an `<iframe />` or `<script />` whose URL starts with `chrome-extension://`, and copy the extension ID from the URL. 2. Open `chrome://extensions/`, find the Chrome extension by its ID, and disable it. 3. Refresh the page and try again. ### I get a 403 error when using an Ollama model in the extension Set the `OLLAMA_ORIGINS="*"` environment variable to allow the Chrome extension to access the Ollama model. ### A test or script cannot open the page Check that the Playwright or Puppeteer browser is installed and that the target URL is reachable from the machine running the test. A browser launched by Playwright or Puppeteer uses a new profile, so login sessions from your desktop Chrome are not available. Use [Chrome Bridge](#chrome-bridge) to reuse them. --- url: /provide-application-knowledge-to-gui-agent.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Provide application knowledge to a GUI Agent When using a GUI Agent, developers often want to describe a goal and let the Agent handle the actions. But a clear goal does not mean the Agent already has the application knowledge needed to complete it. This article uses a practical example to explain how to supply relevant application knowledge and express your intent clearly, helping a GUI Agent execute tasks more reliably. ## Example: where a GUI Agent can go wrong Consider this task in the Dongchedi Android app: > Open the price-reduction ranking, filter for new-energy MPVs launched within the past year, set the price range to CNY 100,000–400,000, and verify that the filters take effect. The prompt is only one sentence, but completing it requires several actions. In practical testing, we observed some potential weak points. :::info The screenshots below show Dongchedi, a Chinese app. Their interface text has been translated into English using AI to help developers follow the workflow. These are illustrative translations, not screenshots of an official English version. All prices remain in CNY; “k” means thousand and “M” means million. ::: | Screenshot | Actions and why the model might go wrong | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | <img src="/images/test-runner-best-practices/ranking-entry-home-en.png" alt="Rankings entry on the Dongchedi home page" width="240" /> | **Intent**<br />Open the price-reduction ranking.<br /><br />**Actions**<br />1. Tap “Rankings” in the shortcut area near the top of the home page.<br />2. Switch to the “Price reductions” ranking at the top of the Rankings page.<br /><br />**Where might the model go wrong?**<br />The name “Price reductions” alone may not tell the model that this feature is inside the Rankings page. Some models may look elsewhere for price-reduction features or try searching for the ranking. The missing knowledge is the app's navigation path: first open Rankings from the home page, then switch rankings. | | <img src="/images/test-runner-best-practices/price-filter-initial-en.png" alt="Vehicle type, launch date, and energy type selected, with the price range not yet adjusted" width="240" /> | **Intent**<br />Set the filters and price range.<br /><br />**Actions**<br />1. Open the vehicle-type filter and select “MPV”.<br />2. Open the launch-date filter and select “Within the past year”.<br />3. Open the energy-type filter and select “New energy”.<br />4. Open the price filter panel.<br />5. Tap the CNY 400,000 tick to set the upper bound.<br />6. Tap the CNY 100,000 tick to set the lower bound.<br /><br />**Where might the model go wrong?**<br />The model may try dragging the slider handles to set the range. Inaccurate drags can require repeated adjustments. This component also supports tapping tick marks: when the target value has a tick, tapping it is more efficient and accurate for the model. | | <img src="/images/test-runner-best-practices/price-filter-pending-en.png" alt="Price range set to CNY 100,000–400,000 in the panel, pending confirmation" width="240" /> | **Intent**<br />Confirm and apply the price filter.<br /><br />**Actions**<br />1. Read the complete price text in the panel to confirm the CNY 100,000–400,000 range.<br />2. Tap the yellow result button at the bottom of the panel to apply the filter.<br /><br />**Where might the model go wrong?**<br />The model may assume that changing the values in the panel has already applied the filter. The selection is still pending, however: the conditions are applied and the list updated only after tapping the yellow result button. This requires knowledge of the component's interaction rules. | | <img src="/images/test-runner-best-practices/price-filter-applied-en.png" alt="Selected filters displayed in the filter bar and the list updated after confirmation" width="240" /> | **Intent**<br />Verify that the filters took effect.<br /><br />**Actions**<br />1. Check that the filter bar displays MPV, within the past year, new energy, and CNY 100,000–400,000.<br />2. Check that the result list updates correctly. | ## Supply the knowledge the GUI Agent needs In this example, finding the price-reduction ranking, setting prices through tick marks, and confirming the selection all depend on application-specific knowledge. Providing that knowledge can help the GUI Agent complete the task more reliably. In Midscene, you can supply this information to `aiAct` through Context, so the Agent can refer to navigation paths, interaction rules, and operating constraints while executing the task. ### Common types of missing knowledge These knowledge gaps usually fall into the following categories: | Knowledge to supply | Examples | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Navigation knowledge**<br />Feature entry points and navigation paths that are not visible on the current screen. | <ul><li>The price-reduction ranking is inside the Rankings page, which you open from the home page.</li><li>Some sections are far down the page and require substantial scrolling to reach.</li></ul> | | **Interaction rules and operating constraints**<br />Unusual interactions or behavior that is hard to infer from the interface, along with accidental actions or side effects to avoid. | <ul><li>Prices can be set by tapping tick marks.</li><li>After adjusting prices, tap the result button to apply them.</li><li>Avoid dragging from the Android screen edges, which can trigger the system back gesture.</li></ul> | | **Business meaning of similar content**<br />Differences in meaning and function between elements with similar appearances or labels. | <ul><li>The range inside the price panel is a pending selection; the range in the filter bar is an applied condition.</li></ul> | ### Add knowledge as needed based on execution Models differ in how well they understand an application, so the knowledge they need also varies. Start with a clear task goal and expected result, then supply additional application knowledge based on actual execution. For example, if the Agent can find the price-reduction ranking on its own, there is no need to explain the entry point. If it forgets to confirm after adjusting the price, add the rule that it must tap the result button to apply the change. As model capabilities improve, some guidance may become unnecessary. Review Context periodically against execution results and remove information the Agent can already work out on its own. ## Common pitfalls Use the following guidance when supplying application knowledge and writing action instructions. ### Do not provide only a vague test goal A prompt such as “test the ranking page” gives no specific goal, expected result, or necessary application knowledge. The Agent has to guess what to do and how to evaluate the result. ### Do not describe actions with fixed coordinates and pixel distances “Tap (424, 815), then drag left by 310 pixels” is tied to the current device and layout. These instructions can fail when the screen size or component position changes, and they limit the Agent's ability to adapt to the current interface. ### Do not inject the entire app knowledge base into every Case Loading the entire app's extensive knowledge base into every Case increases the cost of interpreting irrelevant information. It also makes the details needed for the current task easier to overlook. ### Do not invent operation paths without checking the interface Writing paths based on assumptions rather than the actual user interface can introduce nonexistent entry points or actions into the instructions and mislead the GUI Agent. If you do not know the exact path, keep the task goal clear and leave the path unspecified. Let the GUI Agent decide how to complete the task based on the page it sees during execution. ### Do not write every tap and wait as a separate instruction Chaining multiple `aiTap` calls with fixed-duration `sleep` calls makes execution depend on a predetermined sequence and loading time. This makes it harder to adapt to changes in page state. For example: ```yaml - aiTap: Rankings - sleep: 2000 - aiTap: Price reductions - sleep: 2000 - aiTap: Vehicle-type filter - aiTap: MPV ``` Instead, describe the related business actions in one `aiAct` instruction, letting the Agent decide when to tap and wait based on the current interface: ```yaml - aiAct: Open Rankings from the home-page shortcut, switch to the price-reduction ranking, then open the vehicle-type filter and select MPV. If a dialog appears along the way, close it and continue. ``` The Agent can then close a dialog and continue toward the filtering goal. Compared with a fixed sequence of tap instructions, `aiAct` can adapt its actions to the current interface and handle temporary interruptions like this. The length of an `aiAct` prompt does not necessarily determine how well it works. What matters is whether it expresses your intent clearly. Clearer intent leaves less for the model to infer, reducing the burden of understanding and planning. Vague intent requires the model to fill in more information and places greater demands on its capabilities. ## How to provide context You can pass application knowledge to `aiAct` in two ways: configure global Context for all calls on the current Agent, or provide Context for an individual call. ### Configure global Context for all aiAct calls Set the default context through `aiContexts.aiAct` when creating the Agent. This is useful for application knowledge shared by multiple calls. In this Android example, `deviceId` is the ID of a connected device: ```ts import { agentFromAdbDevice } from '@midscene/android'; const appContext = ` The shortcut area near the top of the home page contains the Rankings entry. Open Rankings, then switch to the price-reduction ranking. Custom prices can be set by tapping tick marks. After adjusting the range, tap the result button at the bottom of the panel to apply it. `; const agent = await agentFromAdbDevice(deviceId, { aiContexts: { aiAct: appContext, }, }); await agent.aiAct('Open the price-reduction ranking'); await agent.aiAct( 'Filter for new-energy MPVs launched within the past year and apply a custom price range of CNY 100,000–400,000', ); ``` Both calls use `appContext`, so you do not need to repeat the same knowledge in each prompt. Here, “global” applies only to `aiAct` calls on the current Agent. ### Provide Context for an individual aiAct call When some knowledge applies only to the current operation, set `context` in the second argument to `aiAct`. For example, after opening the price-reduction ranking, provide interaction rules specifically for the price filter: ```ts await agent.aiAct('Set the price range to CNY 100,000–400,000 and apply the filter', { context: ` Custom prices can be set by tapping tick marks. Set the upper bound first, then the lower bound. After adjusting the range, tap the result button at the bottom of the panel to apply it. The range inside the panel is a pending selection; the range in the filter bar is an applied condition. `, }); ``` This Context applies only to the current call and does not change the default context for subsequent calls. If `aiContexts.aiAct` is also configured, the call's `context` overrides it; the two values are not merged automatically. To use both shared knowledge and knowledge for the current operation, concatenate the two strings before passing them as `context`. For the full parameters and precedence rules, see [API Reference: per-call context](/reference/index.md#per-call-context). --- url: /reference/index.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Shared Agent APIs This page documents the shared APIs inherited by all platform Agents—covering configuration options, interaction methods, data extraction, element location, assertions and waiting, continuous observation, workflow execution, reporting and usage metrics, as well as lifecycle and runtime configuration. [](#) [](#) ## Agent configuration {#agent-options} All platform Agents accept the shared options below (target connection arguments and platform-specific options are defined by each platform SDK). [](#) Device CLIs also accept serializable Agent options per invocation (function-valued options such as `waitForActionReady` are only supported via the JavaScript / TypeScript SDK). Convert `camelCase` option names to `kebab-case` CLI flags without a platform prefix—for example, `waitAfterAction` becomes `--wait-after-action`. See [Skills](/skills.md) for platform-specific CLI entry points. ### Model configuration {#model-options} - `modelConfig?: Record<string, string | number>` — Model configuration for this Agent instance. When provided in code, **all system environment variables for model configuration are ignored by this Agent**, and only the key-value pairs in this object are used. For basic setup and provider examples, see [Configure a model API key](/model-api-setup.md); for advanced parameters, see [Model advanced configuration and debugging](/model-config.md); to understand the Default, Planning, and Insight model roles, see the [Model selection guide](/model-selection.md). - `createOpenAIClient?: (openai, options) => Promise<OpenAI | undefined>` — Custom wrapper function for the OpenAI client, useful for integrating observability tools (such as LangSmith or Langfuse) or attaching custom middleware. [](#) **Custom OpenAI client parameters:** - `openai: OpenAI` — Base OpenAI client instance created by Midscene (pre-configured with the specified API key, base URL, proxy, and other settings). - `options: Record<string, unknown>` — OpenAI initialization options, including: - `baseURL?: string`: API endpoint URL. - `apiKey?: string`: API key. - `dangerouslyAllowBrowser: boolean`: Always `true` in Midscene. - Other OpenAI client initialization options. - **Return value**: Returns the wrapped OpenAI client instance, or `undefined` to keep using the original instance. ### Execution and waiting {#execution-options} - `replanningCycleLimit?: number` — Maximum number of `aiAct` replanning cycles. Default: `20` for standard models, `40` for UI-TARS models, and `100` for AutoGLM models. Prefer setting this Agent option directly (`MIDSCENE_REPLANNING_CYCLE_LIMIT` is retained only for backward compatibility). - `waitForActionReady?: (context: ActionReadyContext) => Promise<void>` — Customizes [readiness checks after each action](#action-ready). - `waitAfterAction?: number` — Fixed delay in milliseconds after each action. Default: `300`. See [Default waiting strategy](#default-waiting-strategy). - `useDeviceTime?: boolean` — Whether task timestamps use the target device's local time. Requires the underlying Device to implement `getDeviceLocalTimeString`; if unimplemented, Midscene logs a warning and falls back to the host system time. Default: `false`. [](#) **Readiness after each action** Configure `waitForActionReady` to control when the next step is allowed to start after an action completes. It runs after every atomic action (such as `Input` or `Tap`, including `aiAct` substeps and cache replay steps), but does not run on initial page load or read-only queries. The callback is invoked only after an action succeeds, and the SDK awaits the returned Promise before proceeding. Its `context` argument includes: - `action: { id, name, param }`: A unique `id` generated for each execution, along with the resolved action parameters and located target. - `signal?: AbortSignal`: An optional cancellation signal used to clean up in-flight work if execution is aborted. In the example below, `app.waitUntilReady` is your custom application readiness check: ```ts import { PlaywrightAgent } from '@midscene/web/playwright'; const agent = new PlaywrightAgent(page, { waitForActionReady: async ({ action, signal }) => { await app.waitUntilReady(action, { signal }); }, }); await agent.aiAct('Log in'); ``` Notes: - If the callback takes longer than 5 seconds, the SDK logs a single warning and continues waiting without imposing a timeout or falling back to default delays. If the outer execution is cancelled, the SDK stops waiting immediately even if the callback has not settled—listen to `signal` inside your callback to stop any custom polling, network requests, or event listeners. - If the action itself fails, the callback is not invoked. If the callback throws an error, execution aborts immediately without replaying the action or falling back to replanning. - Configuring this callback replaces the generic post-action delay (`waitAfterAction`) and platform post-action checks, while keeping required driver timing (such as keyboard preparation and gesture duration) and lifecycle hooks intact. Return immediately from the async callback when no waiting is needed. - Because the callback starts after the action finishes, it cannot catch one-time events that fired while the action was running; check current application state or query underlying `page` / `device` APIs instead. All Agent platforms support this option (`puppeteerAgentForTarget` accepts it in its second argument while preserving its initial network-idle wait). [](#) **Default waiting strategy (advanced)** When `waitForActionReady` is not configured, the following options apply: | Option | Behavior | | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `waitAfterAction` | Fixed delay after each action. Default: `300` ms (explicit delays declared by device actions take precedence). | | `waitForNavigationTimeout` (Web) | Waits for the `<html>` element to be available. Default timeout: `5000` ms (does not guarantee that navigation or rendering has fully completed). | | `waitForNetworkIdleTimeout` (Puppeteer only) | Post-action network-idle check. Default timeout: `2000` ms (requires at most two in-flight requests for `200` ms). | Set either Web timeout to `0` to skip its check. When a timeout is reached, Midscene logs a warning and continues execution without throwing an error. ### Cache {#cache-options} - `cache?: false | { id: string; strategy?: 'read-only' | 'read-write' | 'write-only'; cacheDir?: string }` — Cache configuration: - `false`: Disable caching. - `id`: Cache identifier (required when enabling cache). - `strategy`: Cache read/write strategy. Default: `'read-write'`. - `cacheDir`: Custom directory for cache files. When set, cache files are written to this directory instead of `<MIDSCENE_RUN_DIR>/cache` (relative paths are resolved against the current working directory rather than `MIDSCENE_RUN_DIR`), allowing you to separate cache, log, and report directories. - `cacheId?: string` (deprecated) — Retained for backward compatibility. Use `cache.id` instead. ### Screenshots {#screenshot-options} - `screenshotShrinkFactor?: number` — Factor by which screenshot dimensions are scaled down before being sent to the AI model, reducing image size and token usage. Default: `1` (original size). Setting it to `2` halves both width and height, reducing pixel area to one quarter. - **Mobile devices**: A value of `2` typically reduces token usage significantly while keeping enough detail for recognition; avoid values above `3`, which can make screenshots too blurry for accurate localization. - **Web pages**: Avoid high `screenshotShrinkFactor` values on dense or text-heavy pages. On Web, prefer using Puppeteer or Playwright's `deviceScaleFactor` to control rendering and screenshot resolution at the source. :::info **Difference between `screenshotShrinkFactor` and `deviceScaleFactor`:** - `screenshotShrinkFactor` is a Midscene post-processing option that downscales screenshots after capture to reduce token usage and latency, though excessive downscaling can blur fine details. - `deviceScaleFactor` is a browser viewport option in Puppeteer and Playwright that controls how many physical pixels render each logical CSS pixel, directly determining the native dimensions of captured screenshots. In headed mode, a mismatch between `deviceScaleFactor` and your display's actual scale factor can cause viewport flickering. **Should you use both together?** - **Web**: Usually configuring `deviceScaleFactor` alone is sufficient. The main exception is local headed debugging on a high-DPI display: if you set `deviceScaleFactor: 2` (or higher) to prevent browser flickering, you can pair it with `screenshotShrinkFactor` to downscale the captured image before sending it to the model. - **Mobile and desktop (non-Web)**: `deviceScaleFactor` does not exist on these platforms, so use `screenshotShrinkFactor` to control the image size sent to the model. ::: ### Report configuration {#report-options} - `generateReport?: boolean` — Whether to generate an execution report file. Default: `true`. - `persistExecutionDump?: boolean` — Whether to save additional raw execution JSON for diagnosis or analysis (requires `generateReport: true`). Default: `false`. - `reportFileName?: string` — Custom report output name (auto-generated by default). Its interpretation depends on `outputFormat`: - When `outputFormat` is `'single-html'` (default): Treated as a file name and written to `midscene_run/report/<reportFileName>.html` (if `.html` is already present, it is not duplicated). - When `outputFormat` is `'html-and-external-assets'`: Treated as a subdirectory name and written to `midscene_run/report/<reportFileName>/index.html` alongside its asset files. - `autoPrintReportMsg?: boolean` — Whether to print the generated report path in the terminal. Default: `true`. - `outputFormat?: 'single-html' | 'html-and-external-assets'` — Report output format. Default: `'single-html'`: - `'single-html'` (default): Generates a self-contained HTML file. Open it directly in a browser, view it offline, or share the file alone. - `'html-and-external-assets'`: Generates HTML with external assets and reuses repeated images. Upload the entire report directory when sharing. To preview it, run `pnpm dlx serve` in that directory and open the printed URL. ### Callbacks {#callback-options} - `onTaskStartTip?: (tip: string) => void | Promise<void>` — Optional hook invoked before each subtask starts, receiving a human-readable task summary. Default: `undefined`. - `onLLMUsage?: (usage: AIUsageInfo) => void` — Optional callback invoked after each LLM call with token usage details. See [`onLLMUsage`](#onllmusage-option). ### AI context {#ai-context-options} - `aiContexts?: { default?: string; [apiName]?: string }` — Agent-level AI background context. Default: `undefined`. For precedence rules, see [`context` and `aiContexts` precedence](#per-call-context). - `aiActContext?: string` (deprecated) — Legacy alias for `aiContexts.aiAct` (`aiContexts.aiAct` takes precedence when both are set). Use `aiContexts.aiAct` in new code. For best practices on writing context, see [Provide application knowledge to a GUI Agent](/provide-application-knowledge-to-gui-agent.md). - `aiActionContext?: string` (deprecated) — Older compatibility alias used only when neither `aiContexts.aiAct` nor `aiActContext` is set (resolved via `aiContexts.aiAct ?? aiActContext ?? aiActionContext`; an empty string `''` also overrides lower-priority aliases). Use `aiContexts.aiAct` in new code. ## Prompts and call options {#prompt-options} [](#) [](#) ### Text and image prompts {#prompt-input} When text alone cannot clearly describe the target, you can attach reference images to the prompt. Image-enabled prompts use the following object structure: ```javascript { // Prompt text that references the attached images by name prompt: string, // Attached reference images images?: { // Image name, matching the name referenced in the prompt text name: string, // Local file path, Base64 string, or HTTP(S) URL url: string }[], // When true, converts HTTP(S) image URLs to Base64 before sending them to the model // (useful when the image URLs are not publicly accessible to the model provider) convertHttpImage2Base64?: boolean } ``` - Example 1: Identify a tap target using a reference image ```javascript await agent.aiTap({ prompt: 'The specific logo', images: [ { name: 'The specific logo', url: 'https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png', }, ], }); ``` - Example 2: Assert page content using a reference image ```javascript await agent.aiAssert({ prompt: 'Whether there is a specific logo on the page.', images: [ { name: 'The specific logo', url: 'https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png', }, ], }); ``` - Example 3: Guide `aiAct` planning using a reference image ```javascript await agent.aiAct({ prompt: 'Tap the icon that matches the reference logo', images: [ { name: 'The specific logo', url: 'https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png', }, ], }); ``` **Image size limits** Make sure attached images comply with your model provider's file size and resolution limits (oversized or tiny images may be rejected; check your provider's documentation for exact limits). ### `context` and `aiContexts` precedence {#per-call-context} Context (`context`) provides background knowledge to the AI model—such as domain terms, decision rules, interaction constraints, or output formatting requirements—supplementing rather than replacing the API's main prompt. You can configure context at three levels: - `aiContexts.default`: Shared fallback context for all AI methods on the Agent. - `aiContexts[apiName]`: Context specific to a particular AI method. - `options.context`: Per-call context passed to an individual API invocation. These three levels override one another in the order `options.context ?? aiContexts[apiName] ?? aiContexts.default` and **are not merged automatically**. A lower-priority level is used only when higher-priority levels are `undefined` (or omitted); passing an empty string `''` explicitly clears the context and prevents falling back to lower-priority levels. To combine multiple context strings, concatenate them explicitly as shown below: ```typescript const defaultContext = 'A struck-through price is the original price, a regular price is the current price, and all prices are in USD.'; const agent = new PlaywrightAgent(page, { aiContexts: { default: defaultContext, aiAct: '', // Explicitly ignore the default context aiQuery: 'When extracting an amount, return only the number without the currency symbol.', aiBoolean: `${defaultContext}\n\nA product is on sale only when its current price is lower than its original price.`, }, }); const isOnSale = await agent.aiBoolean('Is this product on sale?'); ``` Supported keys in `aiContexts` are `aiAct`, `aiTap`, `aiRightClick`, `aiMiddleClick`, `aiDoubleClick`, `aiHover`, `aiInput`, `aiKeyboardPress`, `aiScroll`, `aiPinch`, `aiLongPress`, `aiClearInput`, `aiLocate`, `aiQuery`, `aiBoolean`, `aiNumber`, `aiString`, `aiAsk`, `aiAssert`, and `aiWaitFor` (the `ai` and deprecated `aiAction` aliases share the `aiAct` context). [](#) [](#) ### `deepLocate` {#deep-locate} `deepLocate` is available on all APIs that perform element localization (including `aiAct`, `aiTap`, `aiHover`, `aiInput`, `aiKeyboardPress`, `aiScroll`, `aiDoubleClick`, `aiRightClick`, and `aiLocate`). When enabled, Midscene invokes the AI model twice to narrow down and locate the target element more accurately, which is helpful for small targets or elements that blend into their surroundings. Newer models (such as Qwen3.x, Doubao 2.0, and Gemini 3.5) generally achieve high accuracy without it, so enable it only when needed. - **Default**: `false` ```typescript // Enable deepLocate to accurately locate hard-to-identify elements await agent.aiTap('Shopping cart icon in the top right', { deepLocate: true }); ``` :::note In earlier versions, the `deepThink` option name carried two different meanings across APIs: - In `aiAct()`, `deepThink` controlled **planning mode**, guiding deeper task decomposition and planning reasoning (see [`deepThink` planning mode](#aiact-deepthink)). - In single-step action methods such as `aiTap` and `aiHover`, the legacy `deepThink` option controlled **enhanced element localization**, which is now named `deepLocate`. To avoid ambiguity, since v1.5.1 `deepThink` is reserved exclusively for `aiAct()` planning mode, while enhanced localization is named `deepLocate` across all APIs: - In `aiAct()`, you can pass both `deepThink` (to control planning mode) and `deepLocate` (to enable Deep Locate). - In single-step methods such as `aiTap` and `aiHover`, use `deepLocate` (the legacy `deepThink` alias remains supported for backward compatibility). ::: [](#) ## Automatic planning {#planning-interaction} `agent.aiAct()` (and its shorthand alias `agent.ai()`) automatically plans and executes a sequence of steps from a natural-language instruction, whereas the instant interaction methods below (such as `aiTap` and `aiInput`) locate a target element and perform a single specified action directly. [](#) ### `aiAct()` or `ai()` {#agentaiact} Describe your UI goal and optional assertions in natural language. During execution, Midscene continuously plans and performs actions based on the latest UI state until the goal is achieved; if an assertion included in the prompt fails, `aiAct` aborts immediately and throws an error. :::info Backward compatibility This method was named `aiAction()` in earlier versions and remains supported as an alias. We recommend using `aiAct()` in new code for consistency. ::: - Type ```typescript function aiAct( prompt: string | object, options?: { cacheable?: boolean; deepThink?: 'unset' | true | false; deepLocate?: boolean; fileChooserAccept?: string | string[]; fileChooserAllowedDir?: string; abortSignal?: AbortSignal; context?: string; }, ): Promise<string | undefined>; function ai(prompt: string, options?: Object): Promise<string | undefined>; // shorthand form ``` - Parameters: - `prompt: string | object` — Natural-language description of the UI goal and optional assertions, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - `deepThink?: 'unset' | true | false` — Controls the planning strategy used by `aiAct`. See [`deepThink` planning mode](#aiact-deepthink). - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `fileChooserAccept?: string | string[]` — File path(s) to supply when a file chooser dialog is triggered (accepts a single path or an array of paths). Supported on Web pages only (Playwright, Puppeteer, or Chrome Bridge) and not constrained by `fileChooserAllowedDir`. - **Note**: If the target file input does not accept multiple files (lacks the `multiple` attribute) and multiple paths are passed, an error is thrown. - **Note**: If a file chooser is triggered when `fileChooserAccept` is not set, the dialog is ignored so the page can continue operating normally. - **Note**: In Chrome Bridge mode, uploading local files requires enabling **Allow access to file URLs** on `chrome://extensions` > Midscene > **Details**, then reconnecting from the target `http(s)://` tab. - **Note**: Chrome Bridge mode does not support directory upload inputs (`webkitdirectory` / `directory`); use Playwright for directory uploads. - `fileChooserAllowedDir?: string` — Explicitly authorizes the local directory that prompt-driven file uploads in this `aiAct` call may access (without this option, model-planned file uploads are rejected). Relative paths in the prompt are resolved against this directory and validated (including symlinks) to ensure they stay within it; absolute paths are also validated against this directory. Set this to your test suite's `fixtures` directory to prevent accidental uploads of sensitive files due to AI hallucinations or prompt injection. - `abortSignal?: AbortSignal` — An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) used to cancel the `aiAct` call. When triggered, Midscene stops the planning loop immediately and throws an error. - Return value: - Returns the summary text produced upon completing the plan, or `undefined` if no text output was produced. Throws an error if execution fails. - Examples: ```typescript // Perform actions and verify the result await agent.aiAct( 'Search for headphones, add the first item to the cart, and confirm that the cart count changes to 1', ); // Using the shorthand .ai() alias await agent.ai( 'Click the login button at the top of the page, then enter "test@example.com" in the username field', ); // Using abortSignal to enforce a 30-second timeout const controller = new AbortController(); setTimeout(() => controller.abort('timeout'), 30000); await agent.aiAct('Fill in the form and submit', { abortSignal: controller.signal, }); // Enable deepThink planning mode for complex multi-step tasks await agent.aiAct( 'Complete the GitHub account registration form with the region set to "Canada". Ensure no fields are missed and all fields pass validation. Fill in the fields without submitting the form, and finally return the values filled in', { deepThink: true }, ); ``` [](#) **`deepThink` planning mode** `deepThink` controls the internal planning strategy of `aiAct`: - By default (`false` or `'unset'`), `aiAct` plans the next step and locates the target element in a single model request. - When set to `true`, `aiAct` focuses on task decomposition and separates high-level task planning from element localization into distinct model calls. This improves stability on complex tasks at the cost of additional model calls and latency. Note that `deepThink` only controls Midscene's planning pipeline, not the underlying model's native reasoning mode; see [Model-native reasoning](/model-config.md#model-native-reasoning) for the corresponding environment variables. [](#) **Upload files from an `aiAct` prompt** To let `aiAct` upload files referenced directly in a natural-language prompt, pass `fileChooserAllowedDir` (recommended: your test suite's `fixtures` directory). Midscene resolves both relative and absolute paths and verifies that they stay within the authorized directory before configuring the file chooser: ```typescript const agent = new PlaywrightAgent(page); await agent.aiAct( 'First click the "Upload avatar" button and upload avatar.png. Then click the "Upload cover" button and upload cover.png. After uploading, confirm that the avatar displays a cat and the cover displays a beach.', { fileChooserAllowedDir: './fixtures' }, ); ``` When uploading multiple files in a single `aiAct` call, state each relative file path alongside the specific upload action in the prompt (each planned upload replaces the previous file chooser path). Do not combine prompt-specified file paths with `options.fileChooserAccept`, as file chooser configurations planned by the model will overwrite `options.fileChooserAccept`. This feature is supported on Web pages (Playwright, Puppeteer, and Chrome Bridge). When using Chrome Bridge for local file uploads, make sure **Allow access to file URLs** is enabled in `chrome://extensions` > Midscene > **Details**. ## Instant interactions {#instant-interactions} ### `aiTap()` {#agentaitap} Tap a specified element. - Type ```typescript function aiTap(locate: string | object, options?: object): Promise<void>; ``` - Parameters: - `locate: string | object` — Natural-language description of the element to tap, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - `fileChooserAccept?: string | string[]` — File path(s) to supply when tapping triggers a file chooser dialog (accepts a single path or an array of paths). Supported on Web pages only (Playwright, Puppeteer, or Chrome Bridge). - **Note**: If the target file input does not accept multiple files (lacks the `multiple` attribute) and multiple paths are passed, an error is thrown. - **Note**: If a file chooser is triggered when `fileChooserAccept` is not set, the dialog is ignored so the page can continue operating normally. - **Note**: Chrome Bridge mode does not support directory upload inputs (`webkitdirectory` / `directory`); use Playwright for directory uploads. - Return value: - `Promise<void>` - Examples: ```typescript await agent.aiTap('The login button at the top of the page'); // Enable deepLocate to accurately locate the element await agent.aiTap('The login button at the top of the page', { deepLocate: true, }); // File upload: tap the upload button and select files await agent.aiTap('Choose file button', { fileChooserAccept: ['./document.pdf'] }); await agent.aiTap('Upload images', { fileChooserAccept: ['./image1.jpg', './image2.png'] }); ``` ### `aiDoubleClick()` {#agentaidoubleclick} Double-click a specified element. - Type ```typescript function aiDoubleClick(locate: string | object, options?: object): Promise<void>; ``` - Parameters: - `locate: string | object` — Natural-language description of the element to double-click, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - Return value: - `Promise<void>` - Examples: ```typescript await agent.aiDoubleClick('The file name at the top of the page'); // Enable deepLocate to accurately locate the element await agent.aiDoubleClick('The file name at the top of the page', { deepLocate: true, }); ``` ### `aiMiddleClick()` {#agentaimiddleclick} > Supported on Web pages and desktop (`@midscene/computer`) only; not supported on mobile devices (Android, iOS, or HarmonyOS). Middle-click a specified element. The resulting behavior depends on the application. - Type ```typescript function aiMiddleClick(locate: string | object, options?: object): Promise<void>; ``` - Parameters: - `locate: string | object` — Natural-language description of the element to middle-click, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - Return value: - `Promise<void>` - Examples: ```typescript await agent.aiMiddleClick('The link in the search results'); // Enable deepLocate to accurately locate the element await agent.aiMiddleClick('The link in the search results', { deepLocate: true, }); ``` ### `aiRightClick()` {#agentairightclick} > Supported on Web pages and desktop (`@midscene/computer`) only; not supported on mobile devices (Android, iOS, or HarmonyOS). Right-click a specified element. Note that Midscene cannot interact with the browser's native OS-level context menu after right-clicking; use this method for elements that listen for `contextmenu` events and render custom context menus. - Type ```typescript function aiRightClick(locate: string | object, options?: object): Promise<void>; ``` - Parameters: - `locate: string | object` — Natural-language description of the element to right-click, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - Return value: - `Promise<void>` - Examples: ```typescript await agent.aiRightClick('The file name at the top of the page'); // Enable deepLocate to accurately locate the element await agent.aiRightClick('The file name at the top of the page', { deepLocate: true, }); ``` ### `aiHover()` {#agentaihover} > Supported on Web pages and desktop (`@midscene/computer`) only; not supported on mobile devices (Android, iOS, or HarmonyOS). Move the mouse pointer over a specified element. - Type ```typescript function aiHover(locate: string | object, options?: object): Promise<void>; ``` - Parameters: - `locate: string | object` — Natural-language description of the element to hover over, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - Return value: - `Promise<void>` - Examples: ```typescript await agent.aiHover('The version number of the current page'); ``` ### `aiLongPress()` {#agentailongpress} Long-press (press and hold) a specified element, commonly used to open context menus, enter multi-select mode, or trigger other long-press gestures. - Type ```typescript function aiLongPress( locate: string | object, opt?: { duration?: number; deepLocate?: boolean; xpath?: string; cacheable?: boolean; }, ): Promise<void>; ``` - Parameters: - `locate: string | object` — Natural-language description of the element to long-press, or an [image-enabled prompt](#prompting-with-images). - `opt?: object` — Optional configuration: - `duration?: number` — Hold duration in milliseconds. Defaults: Android `2000`, iOS `1000`, Web `500` (on HarmonyOS, the system long-press duration is always used and this option is ignored). - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - Return value: - `Promise<void>` - Examples: ```typescript // Long-press an article to open its context menu await agent.aiLongPress('the first article on the homepage'); // Long-press with a custom hold duration await agent.aiLongPress('the message bubble', { duration: 2000 }); ``` :::info Platform support - Supported on **Android**, **iOS**, **HarmonyOS**, and **Web** (Chromium-based browsers via touch events). On HarmonyOS, `duration` is ignored because the underlying `uitest` API does not support custom hold durations. ::: ### `aiInput()` {#agentaiinput} Enter text into a specified input field. - Type ```typescript // Recommended: locate first, followed by options (including value) function aiInput( locate: string | object, opt: { value: string | number; deepLocate?: boolean; xpath?: string; cacheable?: boolean; autoDismissKeyboard?: boolean; keyboardTypeDelay?: number; inputStrategy?: 'legacy' | 'sequential' | 'bulk'; mode?: 'replace' | 'clear' | 'typeOnly'; }, ): Promise<void>; // Legacy signature (backward compatible) function aiInput( value: string | number, locate: string | object, options?: object, ): Promise<void>; ``` - Parameters: **Recommended usage:** - `locate: string | object` — Natural-language description of the target input field, or an [image-enabled prompt](#prompting-with-images). - `opt: object` — Configuration: - `value: string | number` — **Required.** Text to enter: - When `mode` is `'replace'` (default): Clears existing content in the input field before entering `value`. - When `mode` is `'typeOnly'`: Types `value` directly without clearing existing content first. - When `mode` is `'clear'`: Ignores `value` and only clears the input field. - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - `autoDismissKeyboard?: boolean` — Whether to automatically dismiss the on-screen keyboard after text input (supported on Android, iOS, and HarmonyOS only). Default: `true`. - `keyboardTypeDelay?: number` — Delay in milliseconds between keystrokes (must be a finite non-negative number). Whether this option takes effect in `'legacy'` mode depends on the platform's existing input path (see the table below); `'legacy'` paths that support delay send characters one Unicode code point at a time when set to a positive value. Useful when an input field drops characters during fast typing. - `inputStrategy?: 'legacy' | 'sequential' | 'bulk'` — Text dispatch strategy. Default: `'legacy'`: - `'legacy'` (default): Preserves each platform's historical default input behavior so existing tests behave identically after upgrading. - `'sequential'`: Always sends characters one Unicode code point at a time (even when `keyboardTypeDelay` is omitted or `0`). - `'bulk'`: Sends the entire string in a single platform input call when supported. On Web, `'replace'` mode selects the existing text and calls `insertText`, firing a single insertion `input` event (instead of a clear event followed by per-character `input` events); on other platforms, Midscene makes a single call to the underlying input backend (though the OS or driver may still dispatch multiple events to the application). - `'bulk'` requires `keyboardTypeDelay` to be omitted or set to `0` (passing a positive value throws an error; negative or non-finite values throw an error under all strategies). Action-level options override Device or Agent defaults, so you can pass `keyboardTypeDelay: 0` on a single `aiInput` call to use `'bulk'` when a positive delay is configured globally. - `mode?: 'replace' | 'clear' | 'typeOnly'` — Input mode. Default: `'replace'`: - `'replace'`: Clear the input field first, then enter the new text. - `'typeOnly'`: Enter the text directly without clearing the field first. - `'clear'`: Clear the input field without entering new text. On iOS, when WDA cannot identify a located input, `clear` and `replace` can use a Select All item exposed by WDA. If the menu is closed, WDA can reopen it using a unique input element identified before the tap. If Select All is unavailable, WDA sends a single batch of Backspaces. Clearing is best effort and skips model verification. A successful deletion request allows replacement to proceed even if some text remains. WDA errors propagate. `typeOnly` types at the cursor without clearing. Platform-specific behavior under the default `inputStrategy: 'legacy'`: | Platform | `'legacy'` behavior | | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Web / Playwright / Puppeteer | In `'replace'` mode, clears the existing value and waits for the DOM to settle, then passes the full string to `keyboard.type(value)`; a positive `keyboardTypeDelay` is handled by the browser driver. | | Chrome Bridge | Follows the Web clear-then-type flow and sends text through the remote keyboard primitive; `'legacy'` CDP typing is always zero-delay, and Bridge resolves the strategy on the CLI side before forwarding. | | Android | Non-ASCII or shell-sensitive text uses a single yadb call (ignoring `keyboardTypeDelay` for backward compatibility); pure ASCII via native `adb input text` sends the full segment by default and switches to one call per Unicode code point when `keyboardTypeDelay > 0`. | | iOS | Uses a single WDA `typeText` call by default; switches to one `typeRawKeys` call per Unicode code point when `keyboardTypeDelay > 0`. | | HarmonyOS | Uses a single HDC `inputText` call by default; switches to one call per Unicode code point when `keyboardTypeDelay > 0`. | | Local Computer | Uses clipboard paste when `keyboardTypeDelay` is omitted or `0`; switches to real keyboard events once per Unicode code point when `keyboardTypeDelay > 0`. | | RDP Computer | Uses a single backend `typeText` call when `keyboardTypeDelay` is omitted or `0`; switches to one backend call per Unicode code point when `keyboardTypeDelay > 0`. | **Legacy usage (deprecated, retained for backward compatibility):** - `value: string | number` — Text to enter. - `locate: string | object` — Natural-language description of the target element, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration (same type as `opt` in the recommended signature). - Return value: - `Promise<void>` - Examples: ```typescript // Recommended await agent.aiInput('The search input box', { value: 'Hello World' }); // Legacy signature (not recommended) await agent.aiInput('Hello World', 'The search input box'); ``` :::note Signature update Prefer the new signature `aiInput(locate, opt)` with the locate prompt first. The legacy signature `aiInput(value, locate, options)` remains supported for backward compatibility, but new code should use `aiInput(locate, opt)`. ::: ### `aiClearInput()` {#agentaiclearinput} Clear the contents of a specified input field. Useful when you need clearing as a standalone step (for example, to test empty-field validation messages or to separate clearing and typing into distinct steps). - Type ```typescript function aiClearInput( locate: string | object, opt?: { deepLocate?: boolean; xpath?: string; cacheable?: boolean; }, ): Promise<void>; ``` - Parameters: - `locate: string | object` — Natural-language description of the input field to clear, or an [image-enabled prompt](#prompting-with-images). - `opt?: object` — Optional configuration: - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - Return value: - `Promise<void>` - Examples: ```typescript // Clear the search box await agent.aiClearInput('the search input field'); // Clear and then type a new value as separate steps await agent.aiClearInput('the email input'); await agent.aiInput('the email input', { value: 'user@example.com' }); ``` :::info Choosing between `aiClearInput` and `aiInput` `aiInput(locate, { value: '...' })` already clears the field before typing by default (`mode: 'replace'`). Only call `aiClearInput` when you specifically need clearing as an isolated step. ::: ### `aiKeyboardPress()` {#agentaikeyboardpress} Press a specified keyboard key or key combination. - Type ```typescript // Recommended: locate first, followed by options (including keyName) function aiKeyboardPress( locate: string | object | undefined, opt: { keyName: string; deepLocate?: boolean; xpath?: string; cacheable?: boolean; }, ): Promise<void>; // Legacy signature (backward compatible) function aiKeyboardPress( key: string, locate?: string | object, options?: object, ): Promise<void>; ``` - Parameters: **Recommended usage:** - `locate: string | object | undefined` — Optional natural-language description of the target element, or an [image-enabled prompt](#prompting-with-images). Pass `undefined` to send the key press directly to the currently focused element without AI localization or a preliminary click. - `opt: object` — Configuration: - `keyName: string` — **Required.** Key name to press (such as `'Enter'`, `'Tab'`, or `'Escape'`; use `aiInput()` to enter regular text). Web and desktop (`Computer`) devices support modifier shortcuts joined with `'+'` (such as `'Control+A'` or `'Shift+Enter'`); see the [shared key-name definitions](https://github.com/web-infra-dev/midscene/blob/main/packages/shared/src/us-keyboard-layout.ts) for candidate key names on non-mobile platforms (actual support varies by platform). Built-in Android, iOS, and HarmonyOS devices support single keys only (HarmonyOS supports common control keys plus `A`–`Z` and `0`–`9`, and does not treat shifted characters without dedicated key codes such as `'?'` as key names); passing unsupported keys or key combinations on mobile throws an error. - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. **Legacy usage (deprecated, retained for backward compatibility):** - `key: string` — Key name to press (such as `'Enter'`, `'Tab'`, or `'Escape'`). - `locate?: string | object` — Optional natural-language description of the target element, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration (same type as `opt` in the recommended signature). - Return value: - `Promise<void>` - Examples: ```typescript // Recommended await agent.aiKeyboardPress('The search input box', { keyName: 'Enter' }); await agent.aiKeyboardPress('The search input box', { keyName: 'Control+A' }); // Send a key press directly to the currently focused element (no location or click) await agent.aiKeyboardPress(undefined, { keyName: 'Control+X' }); // Legacy signature (not recommended) await agent.aiKeyboardPress('Enter', 'The search input box'); ``` :::note Signature update Prefer the new signature `aiKeyboardPress(locate, opt)` with the optional locate prompt first. Pass `undefined` as the first argument when the key press should act on the current focus without locating or clicking an element (a valid model configuration is still validated before execution, even though no localization request is sent). The legacy signature `aiKeyboardPress(key, locate, options)` remains supported for backward compatibility. ::: ### `aiScroll()` {#agentaiscroll} Scroll the page or a specified scrollable container. - Type ```typescript // Recommended: locate first, followed by scroll options function aiScroll( locate: string | object | undefined, opt: { scrollType?: 'singleAction' | 'scrollToBottom' | 'scrollToTop' | 'scrollToRight' | 'scrollToLeft'; direction?: 'down' | 'up' | 'left' | 'right'; distance?: number | null; deepLocate?: boolean; xpath?: string; cacheable?: boolean; }, ): Promise<void>; // Legacy signature (backward compatible) function aiScroll( scrollParam: PlanningActionParamScroll, locate?: string | object, options?: object, ): Promise<void>; ``` - Parameters: **Recommended usage:** - `locate: string | object | undefined` — Optional natural-language description of the scroll target, or an [image-enabled prompt](#prompting-with-images). When `undefined`, mobile platforms perform the default center-screen swipe gesture described below, while Web and desktop platforms scroll at the current pointer position. - `opt: object` — Configuration: - `scrollType?: 'singleAction' | 'scrollToBottom' | 'scrollToTop' | 'scrollToRight' | 'scrollToLeft'` — Scroll behavior type. Default: `'singleAction'`. - `direction?: 'down' | 'up' | 'right' | 'left'` — Takes effect only when `scrollType` is `'singleAction'`, specifying **which direction of off-screen content to bring into view** (rather than the direction the visible content moves). For example, `'down'` scrolls down the page to reveal content below the current viewport. Default: `'down'`. - `distance?: number | null` — Scroll distance in device logical pixels, meaning the coordinate units used by the width and height returned by `size()` in a custom device integration. At runtime, this distance is converted into a swipe gesture travel distance on touch devices or a wheel scroll delta on Web and desktop platforms. The actual content displacement is not guaranteed to match this value. Pass `null` to let Midscene choose the distance automatically. - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. **Legacy usage (deprecated, retained for backward compatibility):** - `scrollParam: PlanningActionParamScroll` — Object containing `scrollType`, `direction`, and `distance`. - `locate?: string | object` — Optional natural-language description of the target element, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration (same type as `opt` in the recommended signature). - Return value: - `Promise<void>` - Examples: ```typescript // Recommended await agent.aiScroll('The form panel', { scrollType: 'singleAction', direction: 'up', distance: 100, }); // Legacy signature (not recommended) await agent.aiScroll( { scrollType: 'singleAction', direction: 'up', distance: 100 }, 'The form panel', ); ``` [](#) **Mobile scrolling behavior** Android, iOS, and HarmonyOS share the same default swipe gesture: swiping across the central 70% of the screen along its centerline over roughly one second. This default distance is designed to keep part of the previous screen in view for continuous reading. Note that finger travel distance does not strictly equal content displacement (lists may continue scrolling due to inertia after release, and paged views may snap to the next page). | Parameter combination | Behavior | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Neither `locate` nor `distance` | Performs the default full-screen center swipe gesture above. | | `distance` only | Swipes from the center of the screen by the specified `distance`. | | `locate` only | Swipes starting from the located element using a default distance derived from the screen size. | | Both `locate` and `distance` | Swipes starting from the located element by the specified `distance`. | | Scroll to an edge | Set `scrollType` to `'scrollToTop'`, `'scrollToBottom'`, etc. (very long lists may require multiple calls to reach the end). | Keep `distance` within the available screen dimensions; an excessive distance can cause the gesture to fail. When scrolling inside a dialog or a smaller scrollable container, pass both `locate` and an appropriate `distance`: ```typescript await agent.aiScroll('The list inside the dialog', { direction: 'down', distance: 100 }); ``` If you need a fast fling gesture or exact start/end coordinates, use the platform `Swipe` action (which accepts a `duration`); `aiScroll` is designed for browsing content. :::note Signature update Prefer the new signature `aiScroll(locate, opt)` with the optional locate prompt first. The legacy signature `aiScroll(scrollParam, locate, options)` remains supported for backward compatibility. ::: ### `aiPinch()` {#agentaipinch} Perform a two-finger pinch or spread gesture to zoom out or in. Supported on Android, iOS, and Chromium-based Web browsers. - Type ```typescript function aiPinch( locate: string | object | undefined, opt: { direction: 'in' | 'out'; distance?: number; duration?: number; deepLocate?: boolean; xpath?: string; cacheable?: boolean; }, ): Promise<void>; ``` - Parameters: - `locate: string | object | undefined` — Optional natural-language description of the target element to zoom, or an [image-enabled prompt](#prompting-with-images). When `undefined`, the pinch gesture is performed at the center of the screen. - `opt: object` — Configuration: - `direction: 'in' | 'out'` — **Required.** `'in'` pinches two fingers together (zoom out); `'out'` spreads two fingers apart (zoom in). - `distance?: number` — The amount by which the distance between the two fingers changes, in device logical pixels, meaning the coordinate units used by the width and height returned by `size()` in a custom device integration. Defaults to one quarter of the shorter screen dimension. - `duration?: number` — Gesture duration in milliseconds. Default: `500`. - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - Return value: - `Promise<void>` - Examples: ```typescript // Zoom in on the map (spread fingers apart) await agent.aiPinch('the map area', { direction: 'out', distance: 200 }); // Zoom out at the center of the screen (pinch fingers together) await agent.aiPinch(undefined, { direction: 'in' }); // Zoom in with a custom gesture duration await agent.aiPinch('the image', { direction: 'out', distance: 300, duration: 1000 }); ``` :::info Platform support - **Android**: Implemented via the [yadb](https://github.com/ysbing/yadb) `-pinch` command. - **iOS**: Implemented via the W3C Actions API with dual touch pointers. - **Web**: Implemented via CDP touch events (Puppeteer and Playwright require `enableTouchEventsInActionSpace: true`, and Playwright support is limited to Chromium-based browsers). - **HarmonyOS**: Not supported (the underlying `uitest` framework does not provide multi-touch APIs). ::: [](#) ## Data extraction {#extraction-location-assertion} ### `aiAsk()` {#agentaiask} Ask the AI model a question about the current UI and return its answer as a string. `aiAsk()` shares the same underlying query and return behavior as `aiString()`, though they can still be configured with separate Agent-level contexts via `aiContexts.aiAsk` and `aiContexts.aiString`. - Type ```typescript function aiAsk(prompt: string | object, options?: object): Promise<string>; ``` - Parameters: - `prompt: string | object` — Natural-language question, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `domIncluded?: boolean | 'visible-only'` — Whether to send a simplified DOM tree to the model (commonly used to extract attributes invisible in screenshots, such as image or link URLs; set to `'visible-only'` to include only visible elements). Default: `false`. - `screenshotIncluded?: boolean` — Whether to send a screenshot of the current UI to the model. Default: `true`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - Return value: - `Promise<string>` — Resolves to the text answer from the AI model. - Examples: ```typescript const result = await agent.aiAsk('What should I focus on testing on this page?'); console.log(result); ``` To extract structured data (such as objects or arrays) instead of a free-form string, use `aiQuery()` below. ### `aiQuery()` {#agentaiquery} Extract structured data from the current UI. Describe the desired data and its return format in `dataDemand` (supporting strings, numbers, booleans, objects, or arrays), and Midscene returns a matching value. - Type ```typescript function aiQuery<T>(dataDemand: string | object, options?: object): Promise<T>; ``` - Parameters: - `dataDemand: string | object` — Description of the data to extract and its expected structure (can be a key-value object or a string with type annotations). - `options?: object` — Optional configuration: - `domIncluded?: boolean | 'visible-only'` — Whether to send a simplified DOM tree to the model (commonly used to extract attributes invisible in screenshots, such as image or link URLs; set to `'visible-only'` to include only visible elements). Default: `false`. - `screenshotIncluded?: boolean` — Whether to send a screenshot of the current UI to the model. Default: `true`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - Return value: - `Promise<T>` — Resolves to a value matching the structure declared in `dataDemand` (such as a string, number, JSON object, or array). - Examples: ```typescript const dataA = await agent.aiQuery({ time: 'The date and time displayed in the top-left corner, string', userInfo: 'User information in the format {name: string}', tableFields: 'An array of table field names, string[]', tableDataRecord: 'Table records in the format {id: string, [fieldName]: string}[]', }); // You can also describe the expected return format using a plain string: // dataB is an array of strings const dataB = await agent.aiQuery('string[], list of task names'); // dataC is an array of objects const dataC = await agent.aiQuery( '{name: string, age: string}[], table data records', ); // Enable domIncluded to extract DOM attributes not visible in screenshots (such as avatarUrl) const dataD = await agent.aiQuery( '{name: string, age: string, avatarUrl: string}[], table data records', { domIncluded: true }, ); ``` In addition to `aiQuery()`, Midscene provides three shorthand methods—`aiBoolean()`, `aiNumber()`, and `aiString()`—for extracting primitive values directly. ### `aiBoolean()` {#agentaiboolean} Extract a boolean value from the current UI. - Type ```typescript function aiBoolean(prompt: string | object, options?: object): Promise<boolean>; ``` - Parameters: - `prompt: string | object` — Natural-language description of the condition or boolean value to extract, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `domIncluded?: boolean | 'visible-only'` — Whether to send a simplified DOM tree to the model (set to `'visible-only'` to include only visible elements). Default: `false`. - `screenshotIncluded?: boolean` — Whether to send a screenshot of the current UI to the model. Default: `true`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - Return value: - `Promise<boolean>` — Resolves to the boolean returned by the AI model. - Examples: ```typescript const boolA = await agent.aiBoolean('Whether there is a login dialog'); // Enable domIncluded to inspect DOM attributes const boolB = await agent.aiBoolean('Whether the login button has a link', { domIncluded: true, }); ``` ### `aiNumber()` {#agentainumber} Extract a numeric value from the current UI. - Type ```typescript function aiNumber(prompt: string | object, options?: object): Promise<number>; ``` - Parameters: - `prompt: string | object` — Natural-language description of the target number, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `domIncluded?: boolean | 'visible-only'` — Whether to send a simplified DOM tree to the model (set to `'visible-only'` to include only visible elements). Default: `false`. - `screenshotIncluded?: boolean` — Whether to send a screenshot of the current UI to the model. Default: `true`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - Return value: - `Promise<number>` — Resolves to the number returned by the AI model. - Examples: ```typescript const numberA = await agent.aiNumber('The remaining points of the account'); // Enable domIncluded to extract a numeric DOM attribute const numberB = await agent.aiNumber( 'The value attribute of the remaining points element', { domIncluded: true }, ); ``` ### `aiString()` {#agentaistring} Extract a string value from the current UI. `aiString()` shares the same underlying query and return behavior as `aiAsk()`, though they can still be configured with separate Agent-level contexts via `aiContexts.aiString` and `aiContexts.aiAsk`. - Type ```typescript function aiString(prompt: string | object, options?: object): Promise<string>; ``` - Parameters: - `prompt: string | object` — Natural-language description of the target text, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `domIncluded?: boolean | 'visible-only'` — Whether to send a simplified DOM tree to the model (set to `'visible-only'` to include only visible elements). Default: `false`. - `screenshotIncluded?: boolean` — Whether to send a screenshot of the current UI to the model. Default: `true`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - Return value: - `Promise<string>` — Resolves to the string returned by the AI model. - Examples: ```typescript const stringA = await agent.aiString('The name of the first item in the list'); // Enable domIncluded to extract a link URL from DOM attributes const stringB = await agent.aiString('The link of the first item in the list', { domIncluded: true, }); ``` ## Element location {#element-location} [](#) ### `aiLocate()` {#agentailocate} Locate an element on the current UI using natural language and return its coordinates. - Type ```typescript function aiLocate( locate: string | object, options?: object, ): Promise<{ rect: { left: number; top: number; width: number; height: number; }; center: [number, number]; dpr?: number; // Web only: device pixel ratio }>; ``` - Parameters: - `locate: string | object` — Natural-language description of the element to locate, or an [image-enabled prompt](#prompting-with-images). - `options?: object` — Optional configuration: - `deepLocate?: boolean` — Whether to enable [Deep Locate](#deep-locate-deeplocate) (the legacy `deepThink` alias remains supported). Default: `false`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - `xpath?: string` — XPath of the target element. When provided, Midscene tries the XPath first before falling back to the cache and AI model. Default: `undefined`. - `cacheable?: boolean` — Whether this call can use the [cache](/caching.md). Default: `true`. - Return value: - Resolves to a location object: - `center: [number, number]`: Center coordinates of the located element in physical screenshot pixels. Prefer `center` when you need a reliable click coordinate. - `rect`: Bounding box of the matched element under models that support bounding-box grounding. Under models that only support point grounding (such as AutoGLM), `rect` falls back to a small `8x8` box around the center point—avoid relying on `rect` for exact element dimensions. - `dpr?: number`: Web-only compatibility field indicating the ratio of physical screenshot pixels to logical CSS pixels (not guaranteed on other platforms). - Examples: ```typescript const locateInfo = await agent.aiLocate( 'The login button at the top of the page', ); console.log(locateInfo); ``` ## Assertions and waiting {#assertions-waiting} ### `aiAssert()` {#agentaiassert} Verify an assertion described in natural language against the current UI. If the assertion fails, the SDK throws an error containing both the optional `errorMsg` and the detailed reason provided by the AI model. - Type ```typescript function aiAssert( assertion: string | object, errorMsg?: string, options?: object, ): Promise<void>; ``` - Parameters: - `assertion: string | object` — Natural-language description of the expected condition, or an [image-enabled prompt](#prompting-with-images). - `errorMsg?: string` — Custom error message prepended if the assertion fails. - `options?: object` — Optional configuration: - `domIncluded?: boolean | 'visible-only'` — Whether to send a simplified DOM tree to the model (set to `'visible-only'` to include only visible elements). Default: `false`. - `screenshotIncluded?: boolean` — Whether to send a screenshot of the current UI to the model. Default: `true`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - Return value: - `Promise<void>` — Resolves when the assertion passes; throws an error containing `errorMsg` and the AI model's explanation when it fails. - Example: ```typescript await agent.aiAssert('The price of "Sauce Labs Onesie" is 7.99'); ``` :::info For assertions that require strict, deterministic value checks, you can also extract structured data with `aiQuery()` first and validate it using your test runner's native `expect`: ```typescript const items = await agent.aiQuery( '{name: string, price: number}[], return product names and prices', ); const onesieItem = items.find((item) => item.name === 'Sauce Labs Onesie'); expect(onesieItem).toBeTruthy(); expect(onesieItem.price).toBe(7.99); ``` ::: ### `aiWaitFor()` {#agentaiwaitfor} Poll until a condition described in natural language becomes true on the UI. To avoid excessive model calls, consecutive checks are started at least `checkIntervalMs` apart. - Type ```typescript function aiWaitFor( assertion: string, options?: { timeoutMs?: number; checkIntervalMs?: number; context?: string; }, ): Promise<void>; ``` - Parameters: - `assertion: string` — Natural-language description of the condition to wait for. - `options?: object` — Optional configuration: - `timeoutMs?: number` — Maximum time window in milliseconds for starting a new check. As long as a check starts within this window, Midscene waits for it to finish; if the condition is still not met and the window has elapsed, a timeout error is thrown. Default: `15000`. - `checkIntervalMs?: number` — Minimum interval in milliseconds between the start of consecutive checks. Default: `3000`. - `context?: string` — Additional context for this call. See [`context` and `aiContexts` precedence](#per-call-context). - Return value: - `Promise<void>` — Resolves once the condition is met; throws an error if it times out. - Examples: ```typescript // Basic usage await agent.aiWaitFor( 'At least one headphone product is displayed on the page', ); // Custom timeout and check interval await agent.aiWaitFor('The shopping cart icon shows a quantity of 2', { timeoutMs: 30000, // Wait up to 30 seconds checkIntervalMs: 5000, // Check every 5 seconds }); ``` :::info Each `aiWaitFor()` check invokes the AI model and consumes tokens. When your application or framework exposes a deterministic readiness signal, prefer awaiting that signal directly. ::: **Comparison of waiting mechanisms** | Mechanism | Use case | | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | [`agent.aiWaitFor(condition)`](#agentaiwaitfor) | Wait for a visible UI condition at a specific step using AI. | | [`browserAgent.waitForNewPage(action)`](/sdk/playwright.md#wait-for-new-page) | Attach a listener before running `action`, then wait for and return the newly opened page (Playwright / Puppeteer). | | [`waitForActionReady`](#action-ready) | Globally customize when to proceed after every atomic action completes. | For other in-app events, `await` your application's Promise or underlying browser / device APIs directly (for one-time events, subscribe before triggering the action). ## Continuous observation {#observation-waiting} ### `startObserving()` {#agentstartobserving} `startObserving()` continuously captures screen frames, making it ideal for verifying transient UI states such as toast notifications, banners, or page transitions. Typical workflow: call `startObserving()` to begin recording, perform your UI actions, and then call `observer.stop()` to obtain a `UIObservation` instance, which you can query or assert against. ```typescript function startObserving(options?: { intervalMs?: number; // Sampling interval (default: 1,000 ms, minimum: 200 ms) maxFrames?: number; // Maximum retained frames (default: 30) watchdogMs?: number; // Maximum recording duration (default: 300,000 ms; 0 disables the limit) }): Promise<UIObserver>; ``` `UIObserver` provides: - `observer.bufferedFrameCount: number` — Number of frames currently buffered during recording. - `observer.stop(): Promise<UIObservation>` — Stops recording and returns a `UIObservation` instance. `UIObservation` holds the captured frames (frozen once `stop()` is called). You can invoke `aiQuery()`, `aiBoolean()`, `aiNumber()`, `aiString()`, `aiAsk()`, and `aiAssert()` on `UIObservation`. Because these methods inspect recorded image frames rather than the live page DOM, `domIncluded` is not supported (rejected by TypeScript at compile time and throws at runtime). `UIObservation` also exposes `frameCount`, `startedAt`, and `endedAt`. When finished, call `observation.dispose()` to delete temporary frame files on disk (`agent.destroy()` also cleans up any remaining frame files). ```typescript const observer = await agent.startObserving(); await agent.aiAct('submit the form'); const observation = await observer.stop(); await observation.aiAssert('a success toast appeared during submission'); const toastCount = await observation.aiNumber( 'how many success toasts appeared?', ); await observation.dispose(); ``` Sampling and resource management: - **Frame sources**: Midscene uses a continuous stream when available—scrcpy on Android (`scrcpyConfig.enabled`), WDA MJPEG on iOS (`wdaMjpegFrameSource.enabled`), and CDP Screencast on Web. When no stream is available, it falls back to periodic screenshots (which samples more slowly on mobile). - **Memory and disk usage**: To avoid holding all images in memory, Data URL frames are written to temporary files as they are sampled, while other frame handles are decoded and written to disk in small batches when `stop()` is called. Frame files are read only when a query or assertion runs. - **Frame limits**: Up to `maxFrames` observed frames plus the final screenshot are sent to the model. Increase `intervalMs` to sample less frequently, or reduce `maxFrames` to cap the frame count. Observed frames appear in the report timeline with an `Observed` badge. - **iOS frame quality**: On iOS, observed frames come from the lower-resolution MJPEG stream, while the final screenshot retains full resolution. [](#) ## Workflow execution {#workflow-context} ### `runYaml()` {#agentrunyaml} Parse and execute a YAML automation script (running only its `tasks` section), returning the results of all `aiQuery` steps in the script. - Type ```typescript function runYaml(yamlScriptContent: string): Promise<{ result: any }>; ``` - Parameters: - `yamlScriptContent: string` — YAML script content string. - Return value: - Returns `{ result: any }`, where `result` contains the outputs of all `aiQuery` steps in the script. - Example: ```typescript const { result } = await agent.runYaml(` tasks: - name: search weather flow: - ai: input 'weather today' in input box, click search button - sleep: 3000 - name: query weather flow: - aiQuery: "the result shows the weather info, {description: string}" `); console.log(result); ``` :::info For full YAML script syntax and configuration, see [Automate with scripts in YAML](/automate-with-scripts-in-yaml.md). ::: ### `runGherkinScenario()` {#agentrungherkinscenario} Execute a single Gherkin scenario by mapping its steps to Midscene Agent calls. :::caution Beta Available since Midscene v1.10 and currently in Beta; the API may change in future releases. ::: - Type ```typescript function runGherkinScenario( scenarioText: string, options?: { context?: string; abortSignal?: AbortSignal; deepThink?: 'unset' | true | false; deepLocate?: boolean; }, ): Promise<void>; ``` - Parameters: - `scenarioText: string` — A single Gherkin scenario string, or a sequence of Gherkin steps without the `Scenario:` header line. - `options?: object` — Optional runtime configuration: - `context?: string` — Additional AI context applied to every step in this scenario run (takes precedence over `aiContexts[apiName]` and `aiContexts.default` on the Agent). - `abortSignal?: AbortSignal` — Optional signal to abort the scenario run. - `deepThink?: 'unset' | true | false` — Forwarded to the underlying `aiAct` calls for `Given` and `When` steps. - `deepLocate?: boolean` — Forwarded to the underlying `aiAct` calls for `Given` and `When` steps. - Return value: - `Promise<void>` — Resolves when all steps complete; if a step fails, the thrown error includes the Gherkin line number, original step text, and the Midscene action being executed. - Example: ```typescript await agent.runGherkinScenario(` Scenario: Add a todo item Given the todo page is open When I add a todo item named "Buy milk" Then the todo list should contain "Buy milk" `); ``` For supported syntax rules, limitations, caching behavior, and YAML integration, see [BDD-style scripts with Gherkin](/advanced/bdd-style-scripts-with-gherkin.md). ## Context management {#context-management} `setAIContext()` dynamically updates the background context provided to the AI model; `freezePageContext()` and `unfreezePageContext()` control whether subsequent calls reuse a single captured page snapshot (including its screenshot). ### `setAIContext()` {#agentsetaicontext} Dynamically set the Agent-level shared fallback context or the context for a specific API. - Type ```typescript function setAIContext( target: 'default' | AiApiName, context: string | undefined, ): void; ``` - Parameters: - `target` — Pass `'default'` to set the shared fallback context across all AI methods, or pass a specific API name (such as `'aiAct'`, `'aiTap'`, `'aiQuery'`, or `'aiAssert'`). - `context` — Background context provided to the AI model (such as domain facts, rules, constraints, or output format requirements). For a specific API `target`, pass `''` to explicitly block the shared `aiContexts.default`, or pass `undefined` to clear the API-specific override and inherit `aiContexts.default` again; for the `'default'` target, pass `undefined` to remove the shared fallback. - Example: ```typescript agent.setAIContext('default', 'Prices are displayed in USD.'); agent.setAIContext('aiQuery', 'Return monetary values without currency symbols.'); agent.setAIContext('aiQuery', ''); // Explicitly ignore aiContexts.default for aiQuery agent.setAIContext('aiQuery', undefined); // Inherit aiContexts.default again for aiQuery ``` [](#) **`setAIActContext()` (deprecated)** Sets the background context for subsequent `agent.aiAct()` or `agent.ai()` calls (does not affect instant interaction methods such as `aiTap()`). Equivalent to `agent.setAIContext('aiAct', context)` and overwrites any existing `aiContexts.aiAct` value; use `agent.setAIContext('aiAct', context)` in new code. - Type ```typescript function setAIActContext(aiActContext: string): void; ``` - Parameters: - `aiActContext: string` — Background knowledge sent to the AI model. For guidance on writing effective context, see [Provide application knowledge to a GUI Agent](/provide-application-knowledge-to-gui-agent.md). - Example: ```typescript agent.setAIActContext('Close the cookie consent dialog first if it exists'); ``` :::info Both `agent.setAIActContext()` and the older `agent.setAIActionContext()` are retained only for backward compatibility; use `agent.setAIContext('aiAct', context)` in new code. ::: ### `freezePageContext()` {#agentfreezepagecontext} Freeze the current page context so subsequent operations reuse a single captured snapshot instead of capturing screenshots and page state repeatedly. Useful when running a batch of concurrent read-only queries against a static screen. Usage constraints: - Use this only when page context capture is a confirmed performance bottleneck. - Call `agent.unfreezePageContext()` as soon as you need live page state again. - **Do not run interaction methods** (such as clicks or typing) while the context is frozen—the model will not see UI updates and will act on stale snapshot data. - Type ```typescript function freezePageContext(): Promise<void>; ``` - Return value: - `Promise<void>` - Examples: ```typescript // Freeze the page context so concurrent queries share one snapshot await agent.freezePageContext(); const results = await Promise.all([ agent.aiQuery('Username input box value'), agent.aiQuery('Password input box value'), agent.aiLocate('Login button'), ]); console.log(results); // Unfreeze the page context so subsequent operations read live state await agent.unfreezePageContext(); ``` :::info In the execution report's Insight tab, steps that reuse a frozen snapshot are marked with a 🧊 icon. ::: ### `unfreezePageContext()` {#agentunfreezepagecontext} Unfreeze the page context and resume capturing live page state before each operation. - Type ```typescript function unfreezePageContext(): Promise<void>; ``` - Return value: - `Promise<void>` ## JavaScript execution {#javascript-execution} ### `evaluateJavaScript()` {#agentevaluatejavascript} > Available on Web Agents only. Evaluate a JavaScript expression in the controlled web page's context and return the result. - Type ```typescript function evaluateJavaScript(script: string): Promise<any>; ``` - Parameters: - `script: string` — JavaScript expression string to evaluate. - Return value: - Returns the evaluated result of the JavaScript expression. - Example: ```typescript const result = await agent.evaluateJavaScript('document.title'); console.log(result); ``` ## Reports and usage {#reporting-metrics-lifecycle} [](#) [](#) ### `reportFile` {#agentreportfile} Path to the current report file (`string | null | undefined`). This property has no value before the first report update, or when report generation is disabled (`generateReport: false`), when the Agent runs in a browser environment without file-system access, or when the Agent has not executed any tasks. Even after a path is assigned, subsequent operations may continue updating the report. Always call [`await agent.destroy()`](#agentdestroy) before reading or consuming the final report file so that all pending writes are flushed and `.reportFile` is updated with the finalized path. [](#) [](#) ### `recordToReport()` {#agentrecordtoreport} Record a custom entry in the execution report (capturing a fresh screenshot by default, or attaching caller-supplied screenshots). - Type ```typescript interface RecordToReportOptions { content?: string; /** @deprecated Use screenshots instead. */ screenshotBase64?: string; screenshots?: { /** * PNG/JPEG Data URI, or raw PNG Base64 string. */ base64: string; description?: string; }[]; } function recordToReport( title?: string, options?: RecordToReportOptions, ): Promise<void>; ``` - Parameters: - `title?: string` — Title for the report entry. Default: `'untitled'`. - `options?: RecordToReportOptions` — Optional configuration: - `content?: string` — Text description for the entry. - `screenshots?: Array<{ base64: string; description?: string }>` — One or more external screenshots to attach to this report entry (when set, Midscene does not capture a new screenshot automatically). `base64` accepts a PNG / JPEG Data URI (such as `data:image/png;base64,...`) or a raw Base64 body (treated as PNG). - Compatibility: The legacy single-screenshot option `screenshotBase64?: string` remains supported for backward compatibility, but new code should use `screenshots: [{ base64 }]` (do not pass both `screenshots` and `screenshotBase64`). - Return value: - `Promise<void>` - Examples: ```typescript await agent.recordToReport('Login page', { content: 'User A', }); const before = await page.screenshot({ encoding: 'base64' }); const after = await page.screenshot({ encoding: 'base64' }); await agent.recordToReport('Checkout comparison', { content: 'Compare the state before and after submit.', screenshots: [ { base64: `data:image/png;base64,${before}`, description: 'Before submit', }, { base64: `data:image/png;base64,${after}`, description: 'After submit', }, ], }); ``` [](#) ### `metrics` {#agentmetrics} Midscene automatically tracks token usage for every LLM call. You can read the accumulated usage snapshot at runtime via the `agent.metrics` getter, which is useful for cost observability with platforms like Langfuse. - Type ```typescript interface UsageBucket { promptTokens: number; completionTokens: number; totalTokens: number; calls: number; } interface MidsceneUsageMetrics { totalPromptTokens: number; totalCompletionTokens: number; totalTokens: number; totalCachedInput: number; totalTimeCostMs: number; calls: number; // Breakdown by call intent: `planning`, `insight`, `default` byIntent: Record<string, UsageBucket>; // Breakdown by model name byModel: Record<string, UsageBucket>; } ``` - Example ```typescript await agent.aiAct('search for headphones'); const usage = agent.metrics; console.log(usage.totalTokens, usage.byIntent, usage.byModel); ``` ### `onLLMUsage` {#onllmusage-option} For real-time usage tracking after each model call, pass an `onLLMUsage` callback when constructing the Agent. It is invoked once per LLM call as soon as usage data is returned, receiving raw usage details (token counts, model name, `intent`, request ID, etc.): ```typescript const agent = new PuppeteerAgent(page, { onLLMUsage: (usage) => { langfuse.event({ name: usage.intent, value: usage.total_tokens }); }, }); ``` `usage` may include debugging fields that vary by model or SDK version. ### `_unstableLogContent()` {#agent_unstablelogcontent} Retrieve the internal log object associated with the current report. Note that the structure of this object is internal and may change in future releases. - Type ```typescript function _unstableLogContent(): object; ``` - Return value: - Returns an object containing the current execution log data. - Examples: ```typescript const logContent = agent._unstableLogContent(); console.log(logContent); ``` ## Lifecycle {#lifecycle} ### `destroy()` {#agentdestroy} Finalize the Agent's execution report and release resources held by the Agent. - Type ```typescript function destroy(): Promise<void>; ``` - Behavior: - Stops any active `UIObserver`. - Calls the optional `destroy()` method on the underlying Device / Interface and waits for cleanup to complete. - Flushes and finalizes the report, then updates `agent.reportFile` with the final path (or `undefined` if no report was generated). - Idempotent: calling `destroy()` again after the first call completes is a no-op. - If underlying Device cleanup throws an error, Midscene still attempts to finalize the report before rethrowing the cleanup error. Treat the Agent instance as disposed after calling `destroy()` and do not invoke further methods on it. :::warning Cleanup scope `agent.destroy()` stops the Agent, finalizes its report, and releases control resources held internally by Midscene. It generally does not close external browser tabs or disconnect physical devices, though some platforms terminate automated sessions or virtual displays they started. See the "Lifecycle" section of each platform's SDK guide for platform-specific cleanup behavior. ::: ## Report merging utilities {#reporting-utilities} [](#) When multiple automation workflows or test cases each generate their own report, use `ReportMergingTool` to combine them into a single summary report (output as either a standalone HTML file or a directory containing `index.html` and external screenshot assets). ### `new ReportMergingTool()` Create a `ReportMergingTool` instance. - Example: ```typescript import { ReportMergingTool } from '@midscene/core/report'; const reportMergingTool = new ReportMergingTool(); ``` ### `.append()` Append a workflow's report entry to the merge queue after the workflow finishes. - Type ```typescript type SkippedReportFileAttributes = Omit< ReportFileAttributes, 'testStatus' > & { testStatus: 'skipped'; }; type ReportFileWithAttributes = | { reportFilePath: string; reportAttributes: ReportFileAttributes; } | { reportFilePath?: undefined; reportAttributes: SkippedReportFileAttributes; }; function append(reportInfo: ReportFileWithAttributes): void; ``` - Parameters: - `reportInfo: ReportFileWithAttributes` — Report entry to append: - `reportFilePath: string | undefined` — Path to the source report file (typically `agent.reportFile`). May be omitted only when `reportAttributes.testStatus` is `'skipped'`; for any other status, a missing path causes `append()` to throw an error. - `reportAttributes: object` — Workflow or test case metadata: - `testId: string`: Unique identifier. - `testTitle: string`: Title. - `testDescription: string`: Description. - `testDuration: number`: Execution duration in milliseconds. - `testStatus: 'passed' | 'failed' | 'timedOut' | 'skipped' | 'interrupted'`: Execution status. - Return value: - `void` - Example: ```typescript import type { TestStatus } from '@midscene/core'; // Collect reports in your test runner's afterEach hook (assuming each test owns its Agent) afterEach(async (ctx) => { let workflowStatus: TestStatus = 'passed'; if (ctx.task.result?.state === 'skip') { workflowStatus = 'skipped'; } else if (ctx.task.result?.errors?.[0]?.message.includes('timed out')) { workflowStatus = 'timedOut'; } else if (ctx.task.result?.state === 'fail') { workflowStatus = 'failed'; } // Finalize the report with destroy() before reading agent.reportFile await agent.destroy(); const reportFilePath = agent.reportFile; const reportAttributes = { testId: ctx.task.name, testTitle: ctx.task.name, testDescription: 'Automation workflow description', testDuration: Date.now() - startTime, }; if (!reportFilePath) { if (workflowStatus !== 'skipped') { throw new Error('Midscene report was not generated'); } reportMergingTool.append({ reportAttributes: { ...reportAttributes, testStatus: 'skipped', }, }); return; } reportMergingTool.append({ reportFilePath, reportAttributes: { ...reportAttributes, testStatus: workflowStatus, }, }); }); ``` Note: Make sure every report-producing Agent has completed `await agent.destroy()` before calling `.mergeReports()`. ### `.mergeReports()` Merge all appended reports into a single combined report. - Type ```typescript function mergeReports( reportFileName?: 'AUTO' | string, opts?: { rmOriginalReports?: boolean; overwrite?: boolean; outputDir?: string; outputFormat?: 'single-html' | 'html-and-external-assets'; }, ): string | null; ``` - Parameters: - `reportFileName?: 'AUTO' | string` — Output name for the merged report. Default: `'AUTO'` (auto-generated by Midscene); custom names do not need a `.html` suffix. - `opts?: object` — Optional configuration: - `rmOriginalReports?: boolean` — Whether to delete the original source report files after merging. Default: `false`. - `overwrite?: boolean` — Whether to overwrite an existing file at the target path. Default: `false`. - `outputDir?: string` — Output directory for the merged report (relative paths are resolved against the current working directory). Default: `midscene_run/report/`. - `outputFormat` — `'single-html'` (default) or `'html-and-external-assets'`, independent of the source formats. - Return value: - Returns the entry HTML path of the merged report, or `null` if no reports were appended. - With `'single-html'` (default), the output path is `<outputDir>/<reportFileName>.html`. - With `'html-and-external-assets'`, the output path is `<outputDir>/<reportFileName>/index.html`. Keep the entire report directory together when sharing and view it over HTTP. - Examples: ```typescript // Basic usage: auto-generated file name afterAll(() => { reportMergingTool.mergeReports(); }); // Custom file name afterAll(() => { reportMergingTool.mergeReports('my-automation-report'); }); // Merge and delete original source reports afterAll(() => { reportMergingTool.mergeReports('my-automation-report', { rmOriginalReports: true, }); }); // Overwrite an existing report file afterAll(() => { reportMergingTool.mergeReports('my-automation-report', { overwrite: true, }); }); // Output to a custom directory afterAll(() => { reportMergingTool.mergeReports('my-automation-report', { outputDir: './test-results', }); }); ``` ### `.clear()` Clear the list of appended reports (useful when reusing the same `ReportMergingTool` instance across multiple merge batches). - Type ```typescript function clear(): void; ``` - Return value: - `void` - Example: ```typescript reportMergingTool.mergeReports('first-batch'); reportMergingTool.clear(); // Clear the queue before the next batch ``` ## `exportReportArtifact()` Export one Agent or Test report to the specified format. The input report remains unchanged. ```ts import { exportReportArtifact } from '@midscene/core/report'; const reportPath = await exportReportArtifact({ reportPath: './reports/run/index.html', outputDir: './delivery', reportFileName: 'run', // without .html outputFormat: 'single-html', // default; or 'html-and-external-assets' overwrite: false, // default }); ``` The same operation is available through the CLI: ```bash pnpm exec midscene report-tool --action export --htmlPath ./reports/run/index.html --outputDir ./delivery --outputName run --outputFormat single-html ``` ## Runtime configuration {#runtime-configuration} ### Environment variables {#environment-variables} The following environment variables control global runtime behavior (rather than model request parameters) and cannot be passed inside an Agent's `modelConfig` object: | Variable | Type | Default | Description | | ----------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `MIDSCENE_RUN_DIR` | `string` | `midscene_run` | Root directory for reports, logs, model-call records, and other run artifacts (accepts an absolute path or a path relative to the current working directory). | | `MIDSCENE_PREFERRED_LANGUAGE` | `string` | Auto-detected from system time zone: `Chinese` when time zone is `Asia/Shanghai`, otherwise `English` | Preferred language for model reasoning and status messages (guided via system prompts; actual output depends on model capabilities and context). | | `MIDSCENE_PLAYGROUND_HOST` | `string` | `127.0.0.1` | Network interface address bound by the local Playground server. Set this to a reachable interface IP when connecting from a remote device, VM, container, or another machine on your LAN (setting `0.0.0.0` listens on all interfaces—use only on trusted networks). | | `DEBUG` | `string` | Unset | Enables debug log output for matching namespaces; see [Debug logs](#debug-logs) below. | ### Debug logs {#debug-logs} Set the `DEBUG` environment variable to print debug logs in the terminal: | Value | Description | | ---------------------------- | ---------------------------------------------------------------------- | | `midscene:ai:profile:stats` | Prints model call latency and token usage in a comma-separated format. | | `midscene:ai:profile:detail` | Prints detailed token usage breakdown logs. | | `midscene:ai:call` | Prints raw AI request and response details. | | `midscene:android:adb` | Prints Android `adb` command execution details. | | `midscene:*` | Prints all Midscene debug logs. | Even when `DEBUG` is unset, Midscene writes log files under `<MIDSCENE_RUN_DIR>/log`. Note that log files may contain prompts, model outputs, or screenshots—review and redact sensitive data before sharing, and do not commit them to public repositories. For model connectivity verification, call recording, and tracing integrations, see [Model advanced configuration and debugging](/model-config.md). **See also** - [Model advanced configuration and debugging](/model-config.md) - [Caching](/caching.md) --- url: /sdk/android.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Android JavaScript SDK `@midscene/android` controls Android devices over `adb`. `AndroidAgent` inherits all [AI methods](/reference.md#interaction-methods) from the base `Agent`. ## Imports and API overview ```typescript import { AndroidAgent, AndroidDevice, agentFromAdbDevice, getConnectedDevices } from '@midscene/android'; ``` In most cases, use the `agentFromAdbDevice()` factory to create and connect a Device in one step. If you need to configure and manage the `AndroidDevice` and `AndroidAgent` instances separately, construct them explicitly. [](#) [](#) [](#) [](#) ## `agentFromAdbDevice()` ```typescript agentFromAdbDevice( deviceId?: string, options?: AndroidAgentOpt & AndroidDeviceOpt, ): Promise<AndroidAgent> ``` Connects to an Android device and returns an `AndroidAgent` bound to the connected Device. `deviceId` is optional; when omitted, Midscene selects the first connected device and throws an error if none is found. `options` accepts both Agent and Device settings (including `adb` connection settings used during device discovery). ```typescript const agent = await agentFromAdbDevice('device-id'); ``` [](#) [](#) ## `AndroidDevice` / `AndroidAgent` ```typescript new AndroidDevice(deviceId: string, options?: AndroidDeviceOpt) new AndroidAgent(device: AndroidDevice, options?: AndroidAgentOpt) ``` When constructing `AndroidDevice` explicitly, call `await device.connect()` before passing the Device to `AndroidAgent`. Each Device instance belongs to a single Agent. ```typescript const device = new AndroidDevice('device-id'); await device.connect(); const agent = new AndroidAgent(device); ``` [](#) ## Configuration options ### Agent options Accepts all [shared Agent options](/reference.md#agent-options), plus the following platform option: - `appNameMapping?: Record<string, string>` — Maps friendly app names to Android package names so you can reference apps by name in `launch()`, `terminate()`, or natural-language prompts. User-provided mappings take precedence over built-in defaults. ### Device options - `autoDismissKeyboard?: boolean` — Whether to automatically dismiss the on-screen keyboard after text input. Default: `true`. - `keyboardDismissStrategy?: 'esc-first' | 'back-first'` — Key priority used when dismissing the on-screen keyboard. Default: `'esc-first'`. - `keyboardTypeDelay?: number` — Delay in milliseconds between keystrokes (must be a finite non-negative number). In `'legacy'` mode, a positive value causes the native `adb input text` path to send characters one Unicode code point at a time, while the yadb path ignores this option for backward compatibility. To apply per-character delay to yadb input as well, set `inputStrategy` to `'sequential'`. - `inputStrategy?: 'legacy' | 'sequential' | 'bulk'` — Default text input strategy for `Input` actions. Default: `'legacy'`: - `'sequential'`: Makes one `adb` or yadb call per Unicode code point. Use this strategy when setting a positive `keyboardTypeDelay`. - `'bulk'`: Sends the entire string in a single backend call when supported by the active input method. Requires `keyboardTypeDelay` to be omitted or set to `0`. - `androidAdbPath?: string` — Custom path to the `adb` executable. - `remoteAdbHost?: string` / `remoteAdbPort?: number` — Host and port of a remote `adb` server. - `imeStrategy?: 'always-yadb' | 'yadb-for-non-ascii'` — Controls when [yadb](https://github.com/ysbing/yadb) is used for text input. Default: `'yadb-for-non-ascii'`: - `'yadb-for-non-ascii'` (default): Uses yadb for non-ASCII characters (including accented Latin characters such as `ö`, `é`, and `ñ`, as well as Chinese and Japanese text) and format specifiers (such as `%s` and `%d`). Pure ASCII text uses the faster native `adb input text`. - `'always-yadb'`: Uses yadb for all text input. Provides maximum compatibility, though slightly slower for pure ASCII text. - `screenshotStrategy?: 'auto' | 'always-yadb'` — Controls how screenshots are captured. Default: `'auto'`: - `'auto'` (default): Tries `adb.takeScreenshot` first, falls back to shell `screencap`, and finally uses yadb if `screencap` fails (when `scrcpyConfig.enabled` is `true`, scrcpy is tried first). Note that `'auto'` does not inspect image contents—if a capture command succeeds but returns a black frame, it will not automatically fall back to the next method. - `'always-yadb'`: Bypasses the default `'auto'` flow and captures screenshots directly via [yadb](https://github.com/ysbing/yadb). Useful when `screencap` returns black frames on secure screens (`FLAG_SECURE`) while yadb can capture them (actual support depends on the Android version, ROM, root/hook environment, and device setup; always verify on your target device). Yadb only supports the default display (`displayId=0`); combining `'always-yadb'` with a non-zero `displayId` throws an error. Can also be configured via the `MIDSCENE_ANDROID_SCREENSHOT_STRATEGY=always-yadb` environment variable. - `displayId?: number` — Target virtual display ID when the device has multiple displays. - `exposeRunAdbShellAction?: boolean` — Whether to expose the built-in `RunAdbShell` action in the action space. Default: `true`. Set to `false` to prevent the AI planner, YAML scripts, and `agent.runAdbShell()` from executing `adb shell` commands. - `customActions?: DeviceAction[]` — Custom actions registered for the Agent planner to invoke. Pass this option to `new AndroidDevice()` or `agentFromAdbDevice()`; see [Integrate with any interface](/integrate-with-any-interface.md) for details. - `screenshotResizeScale?: number` — **Deprecated** (removed and no longer has any effect). Use `screenshotShrinkFactor` in `AgentOpt` instead to control the screenshot size sent to the AI model. - `minScreenshotBufferSize?: number` — Minimum valid screenshot buffer size in bytes. Smaller buffers are rejected as failed or corrupted captures. Default: `1024` (1 KB). Set to `0` to skip this size check (empty buffers and invalid image formats are still rejected). - `alwaysRefreshScreenInfo?: boolean` — Whether to re-query screen rotation and resolution before every step. Default: `false`. [](#) **scrcpy configuration and status methods** - `scrcpyConfig?: object` — High-performance scrcpy screenshot configuration (disabled by default): - `enabled?: boolean` — Whether to enable scrcpy screenshots. Default: `false`. - `maxSize?: number` — Maximum width or height of captured screenshots in pixels (must be a non-negative integer; default: `0`, which disables scaling). When scrcpy is temporarily unavailable and falls back to `adb` / yadb, this limit still applies so planning and report images do not suddenly revert to full device resolution. - `videoBitRate?: number` — scrcpy H.264 encoding bitrate in bits per second. Default: `100000000`. Adjusting this trades encoding bandwidth against screenshot detail; tune it only when independent transport measurements indicate a need, and verify recognition accuracy afterward (do not change it solely in response to a frame-freshness timeout warning). - `frameRate?: number` — Optional MediaCodec frame-rate hint (positive 32-bit integer). Omit to use the scrcpy encoder default. To tune low-bitrate screenshots, try `10` and compare image quality on your device. - `idleTimeoutMs?: number` — Idle duration in milliseconds before automatically disconnecting the scrcpy stream (`0` disables auto-disconnect). Default: `30000`. - `videoResetFrameTimeoutMs?: number` — Time in milliseconds to wait for a new keyframe after scrcpy triggers an in-band video reset (must be a positive integer). Default: `800`. Increase this only on devices whose display capture pipeline is slow to restart. - `device.getScrcpyStatus()` — Returns the current scrcpy state (`enabled`, `connected`, `lastError`, and `retryAfter`). - `device.retryScrcpy(): Promise<void>` — Bypasses the cooldown timer and immediately retries the scrcpy connection. ## Platform methods [](#) ### `launch()` Open a web URL, or launch an Android package or activity. ```ts function launch(target: string): Promise<void>; ``` - `target: string` — Web URL, `package/.Activity` identifier (such as `com.android.settings/.Settings`), package name, or app name. If `target` matches a key in `appNameMapping`, Midscene resolves it to the mapped package name; otherwise, it launches `target` as provided. [](#) ### `runAdbShell()` Execute a raw `adb shell` command on the connected device. Pass only the shell command itself, without the `adb shell` prefix. ```ts function runAdbShell(command: string, opt?: { timeout?: number }): Promise<string>; ``` - `command: string` — Command string passed verbatim to `adb shell` (for example, `'input tap 100 200'`, not `'adb shell input tap 100 200'`). - `opt.timeout?: number` — Command execution timeout in milliseconds. This method invokes the `RunAdbShell` action under the hood. If `exposeRunAdbShellAction` is set to `false` on the `AndroidDevice`, this method is unavailable. ```ts const result = await agent.runAdbShell('dumpsys battery', { timeout: 60 * 1000 }); console.log(result); await agent.runAdbShell('input tap 100 200'); ``` [](#) ### `terminate()` Force-stop a running Android app. ```ts function terminate(uri: string): Promise<void>; ``` - `uri: string` — Package name, app name registered in `appNameMapping`, or `package/.Activity` string (only the package name portion is used). ```ts await agent.terminate('com.android.settings'); ``` [](#) ### System navigation - `agent.back(): Promise<void>` — Trigger the system Back action. - `agent.home(): Promise<void>` — Return to the home screen. - `agent.recentApps(): Promise<void>` — Open the recent apps (multitasking) screen. [](#) ## Device discovery ```typescript getConnectedDevices(options?: AndroidDeviceOpt): Promise< Array<{ udid: string; state: string; port?: number }> > ``` Returns the IDs (`udid`) and states of connected devices. Another exported helper, `getConnectedDevicesWithDetails(options?)`, also queries optional `model`, `brand`, `resolution`, and numeric `density` fields (returning `undefined` for any field that cannot be retrieved). Both functions are exported from `@midscene/android`. [](#) ### `getConnectedDevicesWithDetails()` ```typescript getConnectedDevicesWithDetails(options?: AndroidDeviceOpt): Promise<Array<{ udid: string; state: string; port?: number; model?: string; brand?: string; resolution?: string; density?: number; }>> ``` [](#) ## Lifecycle ```typescript agent.destroy(): Promise<void> ``` Calling `agent.destroy()` waits for pending operations to complete, calls the underlying Device's `destroy()`, and finalizes the execution report. Do not share a single Device instance across multiple Agents or reuse a Device after cleanup. On Android, `device.destroy()` clears screen caches and `adb` client state, and closes any active scrcpy connection. It does not disconnect the physical device from the host `adb` server or close apps on the device. ## Troubleshooting [](#) ### Text input is cleared or disappears after typing By default, Midscene automatically dismisses the on-screen keyboard after entering text by sending an **ESC key event**. However, some input fields (especially inside WebViews) listen for the ESC key and trigger side effects such as: - Clearing the text that was just entered - Closing the modal or popup containing the input field - Navigating away from the current page Try the following workarounds in order: **Option 1: Dismiss the keyboard with the Android BACK key** Set `keyboardDismissStrategy` to `'back-first'` so Midscene sends the Android BACK key instead of ESC: ```typescript const device = new AndroidDevice('device-id', { keyboardDismissStrategy: 'back-first', }); ``` **Option 2: Disable automatic keyboard dismissal** If the input field also reacts to the BACK key, disable automatic keyboard dismissal and let subsequent AI actions manage the keyboard state: ```typescript const device = new AndroidDevice('device-id', { autoDismissKeyboard: false, }); ``` When automatic dismissal is disabled, the keyboard remains on screen and may cover the lower half of the interface. You can handle this by: - Calling `aiAct` to collapse the keyboard explicitly, e.g., `await agent.aiAct('tap the collapse button on the keyboard')`. - Installing and switching to [ADBKeyBoard](https://github.com/senzhk/ADBKeyBoard), a minimal virtual keyboard that takes up almost no screen space even when active. [](#) ### English text is altered by the Android input method If the report shows the expected input string, but the app receives garbled characters, missing letters, or Chinese/pinyin candidates, the active Android input method is likely intercepting and rewriting the input. This commonly occurs when pure ASCII text is sent via the native `adb input text` path while a Chinese IME or predictive keyboard is active. Set `imeStrategy` to `'always-yadb'` to route all text input through yadb: ```typescript const device = new AndroidDevice('device-id', { imeStrategy: 'always-yadb', }); ``` In a YAML script: ```yaml android: imeStrategy: always-yadb ``` Or via an environment variable: ```bash export MIDSCENE_ANDROID_IME_STRATEGY=always-yadb ``` Note that this differs from text being cleared after typing: if the text appears properly in the field and then disappears when the keyboard closes, check `keyboardDismissStrategy` or `autoDismissKeyboard` above instead. [](#) ### Screenshots of secure pages (such as password inputs) are black Apps such as banking or payment clients often set `FLAG_SECURE` on password entry screens to prevent screen capture, causing `screencap` to return a black image for the protected region. The yadb utility creates a virtual display with the `secure` flag via `SurfaceControl.createDisplay`, which allows capturing `FLAG_SECURE` screens in certain environments (actual support depends on the Android version, ROM, root/Magisk hook setup, and device configuration; always test on your target device). Set `screenshotStrategy` to `'always-yadb'` to force yadb for all screenshots: ```typescript const device = new AndroidDevice('device-id', { screenshotStrategy: 'always-yadb', }); ``` In a YAML script: ```yaml android: screenshotStrategy: always-yadb ``` Or via an environment variable: ```bash export MIDSCENE_ANDROID_SCREENSHOT_STRATEGY=always-yadb ``` By default, `'auto'` tries `adb.takeScreenshot` and shell `screencap` (or scrcpy first when `scrcpyConfig.enabled` is `true`), falling back to yadb only if those commands fail to execute. Because `'auto'` does not inspect image contents, it will not automatically switch to yadb when `screencap` succeeds with a black image—you must explicitly set `'always-yadb'` to bypass the default capture chain. Note that yadb only supports the default display (`displayId=0`); combining `'always-yadb'` with a non-zero `displayId` throws an error. ### How do I configure the scrcpy video bitrate? When using the Android CLI, pass `--scrcpy-video-bit-rate <bits-per-second>` (or `--scrcpyVideoBitRate`). Specifying this flag automatically enables scrcpy, so `--use-scrcpy` can be omitted: ```bash midscene-android tap \ --device-id <device-id> \ --locate '{"prompt":"the target"}' \ --scrcpy-video-bit-rate <bits-per-second> ``` Because each CLI invocation runs in a separate process, pass this flag to every command that needs a custom bitrate. In the JavaScript SDK or YAML scripts, set `scrcpyConfig.videoBitRate` once in the device configuration. Adjusting the bitrate trades encoding bandwidth against image detail—tune it only when independent transport measurements show a need, and verify recognition accuracy afterward. For defaults and related options, see [scrcpy configuration](#scrcpy) above. ### How do I use a custom adb path or remote adb server? You can configure these via environment variables: ```bash export MIDSCENE_ADB_PATH=/path/to/adb export MIDSCENE_ADB_REMOTE_HOST=192.168.1.100 export MIDSCENE_ADB_REMOTE_PORT=5037 ``` Or pass them in the `AndroidDevice` constructor (or `agentFromAdbDevice`): ```typescript const device = new AndroidDevice('s4ey59', { androidAdbPath: '/path/to/adb', remoteAdbHost: '192.168.1.100', remoteAdbPort: 5037, }); ``` --- url: /sdk/chrome-bridge.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Chrome Bridge SDK `AgentOverChromeBridge` controls desktop Chrome through the Midscene Chrome extension and inherits all [AI methods](/reference.md#interaction-methods) from the base `Agent`. Complete the [Chrome Bridge environment setup](/bridge-mode.md) before connecting. ## Import and construction {#constructor} ```typescript import { AgentOverChromeBridge } from '@midscene/web/bridge-mode'; const agent = new AgentOverChromeBridge({ closeNewTabsAfterDisconnect: false, }); ``` Instantiating `AgentOverChromeBridge` starts a local Bridge Server in the Node.js process and waits for the Chrome extension to connect. Each Agent instance binds to a single tab; call one of the connection methods below to attach to a target tab before invoking AI methods. ## Configuration options In addition to [shared Agent options](/reference.md#agent-options), the constructor accepts: | Option | Type | Default | Description | | ----------------------------- | ------------------------------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `allowRemoteAccess` | `boolean` | `false` | When `true`, listens on `0.0.0.0`; defaults to local connections only (`127.0.0.1`) | | `host` | `string` | `'127.0.0.1'` | Explicit listening address; takes precedence over `allowRemoteAccess` | | `port` | `number` | `3766` | Bridge Server listening port | | `serverListeningTimeout` | `number \| false` | `30000` | Timeout in milliseconds while waiting for the extension to connect; `false` disables the timeout | | `closeConflictServer` | `boolean` | `false` | Whether to close an existing Bridge Server bound to the same address and port before starting | | `closeNewTabsAfterDisconnect` | `boolean` | `false` | Whether to automatically close tabs created by this Agent instance upon destruction | | `enableWaterFlowAnimation` | `boolean` | `true` | Whether to display the blue animated border and pointer indicator during operations | | `keyboardTypeDelay` | `number` | `—` | Delay in milliseconds between keystrokes (must be a finite non-negative number). Ignored in `'legacy'` mode; set `inputStrategy` to `'sequential'` for delayed input | | `inputStrategy` | `'legacy' \| 'sequential' \| 'bulk'` | `'legacy'` | Default text input strategy: `'sequential'` sends one Unicode code point at a time; `'bulk'` sends the full string at once (requires `keyboardTypeDelay` to be omitted or `0`) | For cross-machine setups, see [Remote access configuration](/bridge-mode.md#remote-access-configuration) to configure both the server and the extension. Note that model settings are loaded from the Node.js process running the script, not from the extension's Playground. ## Connection methods ### `connectCurrentTab()` ```typescript agent.connectCurrentTab(options?: { timeout?: number; forceSameTabNavigation?: boolean; }): Promise<void> ``` Connects to the currently active tab in Chrome's frontmost window. Once bound, the Agent continues operating on that tab even if the user later switches to another tab. ```typescript await agent.connectCurrentTab({ timeout: 60000 }); await agent.aiAssert('The account page is visible'); ``` ### `connectNewTabWithUrl()` ```typescript agent.connectNewTabWithUrl(url: string, options?: { activateTab?: boolean; timeout?: number; forceSameTabNavigation?: boolean; }): Promise<void> ``` Opens `url` in a new tab and binds the Agent to it. `activateTab` defaults to `true` (brings the new tab to the foreground); set it to `false` to open the tab in the background. ```typescript await agent.connectNewTabWithUrl('https://example.com', { activateTab: false, timeout: 60000, }); ``` ### Connection behavior and limitations - `timeout` sets the timeout for the connection call itself (default: `30000` ms) and is independent of the constructor's `serverListeningTimeout`. Exceeding this timeout throws an error. - `forceSameTabNavigation` defaults to `true` to intercept new-tab navigations and open them in the current tab. Note that in the current implementation, passing `false` does not remove previously injected interception—do not rely on it to restore native new-tab behavior. - Once an Agent is bound to a tab, calling a connection method or `setActiveTabId()` again throws an error. To operate on another tab, destroy the current Agent with `agent.destroy()` and create a new instance. ## Tab APIs ### `getBrowserTabList()` ```typescript agent.getBrowserTabList(): Promise<Array<{ id: string; title: string; url: string; currentActiveTab: boolean; }>> ``` Returns the list of tabs in Chrome's current window (excluding entries missing an ID, title, or URL). `currentActiveTab` indicates whether the tab is currently active in the Chrome window, not whether it is the tab bound to the Agent. ### `setActiveTabId()` ```typescript agent.setActiveTabId(tabId: string): Promise<void> ``` Before the Agent is bound to any tab, activates and binds a specific tab using its string `id` from `getBrowserTabList()`. This method is for initial binding only and cannot be used to switch tabs at runtime; calling it after a tab is already bound throws an error. ## Lifecycle ```typescript agent.destroy(closeNewTabsAfterDisconnect?: boolean): Promise<void> ``` Performs shared Agent cleanup and report finalization, instructs the Chrome extension to detach from the page, and shuts down the local Bridge Server. - By default, Chrome and all tabs remain open after disconnecting. - Pass `true` to override the constructor setting and close tabs created by this bridge instance, or `false` to keep them open. - Existing tabs attached via `connectCurrentTab()` were not created by the bridge instance and are never closed by this option. ```typescript try { await agent.connectNewTabWithUrl('https://example.com'); await agent.aiAssert('The page is visible'); } finally { await agent.destroy(true); } ``` ## Platform limitations Chrome Bridge reuses your desktop Chrome session directly, so it does not expose Playwright or Puppeteer `Browser` / `Page` objects or support multi-tab switching like `PlaywrightBrowserAgent`. For local file upload permissions, connection authorization, and remote network setup, see [Chrome Bridge environment setup](/bridge-mode.md); for YAML-specific options, see [Chrome Bridge in YAML](/automate-with-scripts-in-yaml.md#chrome-bridge). --- url: /sdk/desktop.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Computer JavaScript SDK `@midscene/computer` provides Device implementations for local desktops (`ComputerDevice`) and remote RDP desktops (`RDPDevice`), along with `ComputerAgent`, which inherits all [AI methods](/reference.md#interaction-methods) from the base `Agent`. ## Imports and API overview ```typescript import { ComputerAgent, ComputerDevice, RDPDevice, agentForComputer, agentForRDPComputer, checkComputerEnvironment, } from '@midscene/computer'; ``` In most cases, use a factory function to create and connect a Device in one step: `agentForComputer()` for the local desktop (backed by `ComputerDevice`), or `agentForRDPComputer()` for a remote Windows desktop over RDP (backed by `RDPDevice`). If you need to configure and manage the Device and Agent instances separately, construct them explicitly. [](#) [](#) ## `agentForComputer()` ```typescript agentForComputer(options?: LocalComputerAgentOpt): Promise<ComputerAgent<ComputerDevice>> ``` Connects to the local desktop (controlling the primary display by default) and returns a `ComputerAgent` bound to `ComputerDevice`. `options` accepts both shared Agent settings and local Device settings (`agentFromComputer` is a deprecated compatibility alias). ```typescript const agent = await agentForComputer({ displayId: '0' }); ``` [](#) ## `agentForRDPComputer()` ```typescript agentForRDPComputer(options: RDPComputerAgentOpt): Promise<ComputerAgent<RDPDevice>> ``` Connects to a remote Windows desktop over RDP and returns a `ComputerAgent` bound to `RDPDevice`. `host` is required; see [RDP options](#rdp-options) below for additional connection settings. The default backend requires [FreeRDP](https://www.freerdp.com/) to be installed on the machine running the script, and a reachable remote Windows host with RDP enabled. Each RDP session is treated as a single remote display. ```typescript const agent = await agentForRDPComputer({ host: 'windows.example.com', username: process.env.RDP_USERNAME, password: process.env.RDP_PASSWORD, }); ``` ## `ComputerDevice` / `RDPDevice` / `ComputerAgent` ```typescript new ComputerDevice(options?: ComputerDeviceOpt) new RDPDevice(options: RDPDeviceOpt) new ComputerAgent(device, options?) ``` When constructing `ComputerDevice` or `RDPDevice` explicitly, call `await device.connect()` before passing the Device to `ComputerAgent`. Pass device-specific settings to the Device constructor; the second argument of `ComputerAgent` accepts [shared Agent options](/reference.md#agent-options). ```typescript const device = new ComputerDevice({ displayId: '0' }); await device.connect(); const agent = new ComputerAgent(device); ``` [](#) ## Configuration options Both `agentForComputer()` and `agentForRDPComputer()` accept [shared Agent options](/reference.md#agent-options). To register custom actions, pass `customActions` to the factory function or Device constructor; see [Integrate with any interface](/integrate-with-any-interface.md) for details. ### Local desktop options - `displayId?: string` — ID of the display to control. Use `ComputerDevice.listDisplays()` to query available displays. Default: the primary display. - `customActions?: DeviceAction<any>[]` — Custom actions registered for the Agent planner to invoke. - `keyboardDriver?: 'applescript' | 'libnut'` — Keyboard event backend on macOS. Default: `'applescript'` (wider compatibility); set to `'libnut'` for faster keystroke injection when supported by the target application. - `keyboardModifierDelay?: number` — Delay in milliseconds after each modifier key state change and primary key press when using the local `libnut` keyboard driver (must be a finite non-negative number). Default: `0`. Modifiers include `Control`, `Shift`, `Alt`, and `Command`, so this delay applies to keyboard shortcuts as well as the implicit `Shift` used for uppercase letters during sequential typing (and shifted `en-US` punctuation when `keyboardLayout: 'en-US'` is set). Has no effect on direct RDP input or the macOS `'applescript'` driver. See [Forward keyboard input through desktop clients](/faq.md#keyboard-input-through-desktop-clients). - `keyboardLayout?: 'en-US'` — Enables base-key mapping for shifted `en-US` punctuation during sequential typing with the local `libnut` driver (uppercase Latin letters do not require this setting). Other layouts retain the backend's default behavior. Has no effect on direct RDP input or the macOS `'applescript'` driver. - `headless?: boolean` — On Linux, set to `true` to start a virtual display via [Xvfb](https://www.x.org/releases/X11R7.6/doc/man/man1/Xvfb.1.xhtml), enabling desktop automation on headless servers and CI environments (can also be enabled via `MIDSCENE_COMPUTER_HEADLESS_LINUX=true`). Default: `false`. - `xvfbResolution?: string` — Resolution of the Xvfb virtual display. Default: `'1920x1080x24'`. ### Keyboard input options - `keyboardTypeDelay?: number` — Minimum delay in milliseconds between keystrokes (must be a finite non-negative number). Default: `undefined`. In `'legacy'` mode, a positive value causes local and RDP Computer Agents to emit text one Unicode code point at a time (sending real key events on local desktops); when omitted or set to `0`, local `'legacy'` input uses clipboard paste to avoid interference from the active system IME. An action-level `keyboardTypeDelay` passed to `aiInput()` overrides the Agent-level default (pass `0` to restore clipboard paste for that single action). - `inputStrategy?: 'legacy' | 'sequential' | 'bulk'` — Default text input strategy for `Input` actions. Default: `'legacy'`: - `'sequential'`: Uses real key events locally and makes one backend call per Unicode code point over RDP. Use this strategy when setting a positive `keyboardTypeDelay`. - `'bulk'`: Performs a single clipboard paste locally and makes a single backend call over RDP. Requires `keyboardTypeDelay` to be omitted or set to `0`. Agent-level input options also apply to `Input` actions planned by `agent.ai()` / `agent.aiAct()`, so you do not need to call `aiInput()` explicitly: ```typescript const agent = await agentForComputer({ keyboardTypeDelay: 80 }); await agent.aiAct('Type the account details into the form'); // Override the default for a single deterministic input action to use bulk paste await agent.aiInput('the notes field', { value: 'Pasted as one value', keyboardTypeDelay: 0, inputStrategy: 'bulk', }); ``` ### RDP options - `host: string` — Remote Windows hostname or IP address (required). - `port?: number` — RDP port. Default: `3389`. - `username?: string` / `password?: string` — Login credentials for the remote session. - `domain?: string` — Windows domain. Default: `undefined`. - `localAddress?: string` — Local source IP address to bind for the RDP TCP connection (useful when the host machine has multiple outbound network routes). Default: `undefined`. - `adminSession?: boolean` — Whether to request a remote admin session when permitted by the server. Default: `false`. - `ignoreCertificate?: boolean` — Whether to skip TLS certificate validation (useful for self-signed certificates). Default: `false`. - `securityProtocol?: 'auto' | 'tls' | 'nla' | 'rdp'` — RDP security negotiation protocol. Default: `'auto'`. - `desktopWidth?: number` / `desktopHeight?: number` — Requested remote desktop resolution. When omitted, the session size is negotiated between the RDP client and server. ## Displays and environment checks [](#) ### `ComputerDevice.listDisplays()` ```typescript ComputerDevice.listDisplays(): Promise<Array<{ id: string; name: string; primary?: boolean; }>> ``` Lists all displays connected to the local machine. Pass a returned `id` to `agentForComputer({ displayId })` to target a specific display. ```typescript const displays = await ComputerDevice.listDisplays(); const display = displays.find((item) => item.primary) ?? displays[0]; if (!display) throw new Error('No displays found'); const agent = await agentForComputer({ displayId: display.id }); ``` [](#) ### `checkComputerEnvironment()` ```typescript checkComputerEnvironment(): Promise<{ available: boolean; error?: string; platform: string; displays: number; }> ``` Checks whether the local desktop environment is ready, returning the OS platform, display count, and availability (`available`). If `available` is `false`, inspect `error` for details. [](#) [](#) ## Lifecycle ```typescript agent.destroy(): Promise<void> ``` The Agent manages Device cleanup and report finalization. Each Device instance belongs to a single Agent. | Device type | `destroy()` cleanup behavior | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `ComputerDevice` | Releases the local input driver and stops any Xvfb virtual display started by the instance; does not close your local desktop session or running apps | | `RDPDevice` | Disconnects the RDP session and clears connection state | As a result, your local desktop and applications remain untouched after destroying a `ComputerDevice`, whereas managed Xvfb virtual displays and remote RDP connections are closed automatically. ```typescript try { await agent.aiAct('Open Settings'); } finally { await agent.destroy(); } ``` ## Platform support and limitations - Local desktop automation requires the appropriate screen recording, accessibility, or display service permissions; see [Desktop environment setup](/platforms/desktop.md). - `headless` (Xvfb) is supported on Linux only. - `keyboardDriver` applies to macOS only; `keyboardModifierDelay` and `keyboardLayout` apply only to the local `libnut` driver and have no effect on direct RDP connections. --- url: /sdk/harmonyos.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # HarmonyOS JavaScript SDK `@midscene/harmony` controls HarmonyOS devices over HDC. `HarmonyAgent` inherits all [AI methods](/reference.md#interaction-methods) from the base `Agent`. ## Imports and API overview ```typescript import { HarmonyAgent, HarmonyDevice, agentFromHdcDevice, getConnectedDevices } from '@midscene/harmony'; ``` In most cases, use the `agentFromHdcDevice()` factory to create and connect a Device in one step. If you need to configure and manage the `HarmonyDevice` and `HarmonyAgent` instances separately, construct them explicitly. [](#) [](#) [](#) [](#) ## `agentFromHdcDevice()` ```typescript agentFromHdcDevice( deviceId?: string, options?: HarmonyAgentOpt & HarmonyDeviceOpt, ): Promise<HarmonyAgent> ``` Connects to a HarmonyOS device and returns a `HarmonyAgent` bound to the connected Device. `deviceId` is optional; when omitted, Midscene selects the first connected device and throws an error if none is found. `options` accepts both Agent and Device settings (including HDC connection settings used during device discovery). ```typescript const agent = await agentFromHdcDevice('device-id'); ``` [](#) [](#) ## `HarmonyDevice` / `HarmonyAgent` ```typescript new HarmonyDevice(deviceId: string, options?: HarmonyDeviceOpt) new HarmonyAgent(device: HarmonyDevice, options?: HarmonyAgentOpt) ``` When constructing `HarmonyDevice` explicitly, call `await device.connect()` before passing the Device to `HarmonyAgent`. Each Device instance belongs to a single Agent. ```typescript const device = new HarmonyDevice('device-id'); await device.connect(); const agent = new HarmonyAgent(device); ``` [](#) ## Configuration options ### Agent options Accepts all [shared Agent options](/reference.md#agent-options), plus the following platform option: - `appNameMapping?: Record<string, string>` — Maps friendly app names to HarmonyOS bundle names or explicit `bundle/Ability` targets so you can reference apps by name in `launch()`, `terminate()`, or natural-language prompts. User-provided mappings take precedence over built-in defaults. ### Device options - `hdcPath?: string` — Custom path to the `hdc` executable. If omitted, Midscene searches the `HDC_HOME` environment variable and common installation paths. - `autoDismissKeyboard?: boolean` — Whether to automatically dismiss the on-screen keyboard after text input. Default: `true`. - `keyboardDismissStrategy?: 'esc-first' | 'back-first'` — Key strategy used when dismissing the on-screen keyboard. Default: `'esc-first'` (on HarmonyOS, `'esc-first'` sends the Escape key, while `'back-first'` sends the Back key). - `keyboardTypeDelay?: number` — Delay in milliseconds between keystrokes (must be a finite non-negative number). When set to a positive value, `'legacy'` input sends characters one Unicode code point at a time via `uitest uiInput inputText`. Useful when an input field drops characters during fast typing. - `inputStrategy?: 'legacy' | 'sequential' | 'bulk'` — Default text input strategy for `Input` actions. Default: `'legacy'`: - `'sequential'`: Makes one HDC input call per Unicode code point. Use this strategy when setting a positive `keyboardTypeDelay`. - `'bulk'`: Sends the entire string in a single HDC text input call. Requires `keyboardTypeDelay` to be omitted or set to `0`. - `screenshotResizeScale?: number` — **Deprecated** (removed and no longer has any effect). Use `screenshotShrinkFactor` in `AgentOpt` instead to control the screenshot size sent to the AI model. - `customActions?: DeviceAction[]` — Custom actions registered for the Agent planner to invoke. Pass this option to `new HarmonyDevice()` or `agentFromHdcDevice()`; see [Integrate with any interface](/integrate-with-any-interface.md) for details. ## Platform methods [](#) ### `launch()` Open a web URL or launch a HarmonyOS app. ```ts function launch(uri: string): Promise<void>; ``` - `uri: string` — App bundle name (such as `com.huawei.hmos.settings`), explicit `bundle/Ability` target, app name registered in `appNameMapping`, or `http://` / `https://` URL (web URLs are opened in the system browser). ```ts await agent.launch('com.huawei.hmos.settings'); // Open Settings await agent.launch('com.huawei.hmos.camera'); // Open Camera await agent.launch('Video'); // Open the mapped ability ``` [](#) ### `runHdcShell()` Execute a raw `hdc shell` command on the connected device. ```ts function runHdcShell(command: string): Promise<string>; ``` - `command: string` — Command string passed directly to `hdc shell`. ```ts const result = await agent.runHdcShell('hidumper -s RenderService -a screen'); console.log(result); ``` [](#) ### `terminate()` Force-stop a running HarmonyOS app. ```ts function terminate(uri: string): Promise<void>; ``` - `uri: string` — Bundle name, app name registered in `appNameMapping`, or `bundle/Ability` string (only the bundle name portion is used). ```ts await agent.terminate('com.huawei.hmos.settings'); ``` [](#) ### System navigation - `agent.back(): Promise<void>` — Trigger the system Back action. - `agent.home(): Promise<void>` — Return to the home screen. - `agent.recentApps(): Promise<void>` — Open the recent apps (multitasking) screen. [](#) ## Device discovery ```typescript getConnectedDevices( hdcPath?: string, options?: { timeout?: number }, ): Promise<Array<{ deviceId: string }>> ``` Returns the list of devices discovered by HDC. Pass `hdcPath` to specify a custom `hdc` executable path. [](#) ## Lifecycle ```typescript agent.destroy(): Promise<void> ``` Calling `agent.destroy()` waits for pending operations to complete, calls the underlying Device's `destroy()`, and finalizes the execution report. Do not share a single Device instance across multiple Agents or reuse a Device after cleanup. On HarmonyOS, `device.destroy()` clears screen caches and HDC client state. It does not disconnect the physical device from HDC or close apps on the device. ## Troubleshooting [](#) ### Keyboard is not dismissed or the page navigates back after typing By default, Midscene automatically dismisses the on-screen keyboard after entering text. On HarmonyOS, it sends the ESC key (`'esc-first'`) by default to avoid accidentally navigating back. If ESC does not close the keyboard in your app, switch `keyboardDismissStrategy` to `'back-first'`: ```typescript const device = new HarmonyDevice('device-id', { keyboardDismissStrategy: 'back-first', }); ``` If your input field also reacts to the Back key by clearing its text or closing a modal, set `autoDismissKeyboard` to `false` to disable automatic dismissal: ```typescript const device = new HarmonyDevice('device-id', { autoDismissKeyboard: false, }); ``` With automatic dismissal disabled, the keyboard stays on screen. You can use `aiAct` to collapse it when needed, e.g., `await agent.aiAct('dismiss the keyboard')`. [](#) ### How do I specify a custom HDC path? Point the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` Or pass the full executable path via `hdcPath` in the `HarmonyDevice` constructor (or `agentFromHdcDevice`): ```typescript const device = new HarmonyDevice('0123456789ABCDEF', { hdcPath: '/path/to/hdc', }); ``` --- url: /sdk/ios.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # iOS JavaScript SDK `@midscene/ios` controls iOS devices through WebDriverAgent (WDA). `IOSAgent` inherits all [AI methods](/reference.md#interaction-methods) from the base `Agent`. ## Imports and API overview ```typescript import { IOSAgent, IOSDevice, agentFromWebDriverAgent } from '@midscene/ios'; ``` In most cases, use the `agentFromWebDriverAgent()` factory to create and connect a Device in one step. If you need to configure and manage the `IOSDevice` and `IOSAgent` instances separately, construct them explicitly. [](#) [](#) [](#) ## `agentFromWebDriverAgent()` ```typescript agentFromWebDriverAgent(options?: IOSAgentOpt & IOSDeviceOpt): Promise<IOSAgent> ``` Connects to WebDriverAgent and returns an `IOSAgent` bound to the connected Device. `options` accepts both Agent and Device settings. Note that `wdaBaseUrl` cannot be combined with `wdaHost` or `wdaPort`. ```typescript const agent = await agentFromWebDriverAgent({ wdaHost: 'localhost', wdaPort: 8100 }); ``` [](#) Set `MIDSCENE_IOS_DEVICE_CLASS_OVERRIDE` to configure a device class override module. An explicit `iOSDeviceClassOverride` passed to the factory takes precedence over the environment variable. [](#) [](#) ## `IOSDevice` / `IOSAgent` ```typescript new IOSDevice(options?: IOSDeviceOpt) new IOSAgent(device: IOSDevice, options?: IOSAgentOpt) ``` When constructing `IOSDevice` explicitly, call `await device.connect()` before passing the Device to `IOSAgent`. Each Device instance belongs to a single Agent. ```typescript const device = new IOSDevice({ wdaHost: 'localhost', wdaPort: 8100 }); await device.connect(); const agent = new IOSAgent(device); ``` [](#) [](#) ## Configuration options ### Agent options Accepts all [shared Agent options](/reference.md#agent-options), plus the following platform option: - `appNameMapping?: Record<string, string>` — Maps friendly app names to iOS bundle IDs so you can reference apps by name in `launch()`, `terminate()`, or natural-language prompts. User-provided mappings take precedence over built-in defaults. ### Device options - `wdaPort?: number` — WebDriverAgent server port. Default: `8100`. - `wdaHost?: string` — WebDriverAgent server host. Default: `'localhost'`. - `wdaBaseUrl?: string` — Full HTTP(S) base URL for the WDA API (including any gateway path prefix). Cannot be combined with `wdaHost` or `wdaPort`. - `iOSDeviceClassOverride?: string` — Custom npm module path used to replace the default `IOSDevice` implementation when calling `agentFromWebDriverAgent()` or running the iOS Playground. The module must export an `IOSDevice` class or a default class. - `sessionId?: string` — Existing WebDriverAgent session ID to reuse. When provided, Midscene skips creating a new WDA session, and detaches from the external session during cleanup instead of deleting it. - `wdaMjpegPort?: number` — WDA MJPEG server port for real-time screen streaming. Default: `9100`. - `wdaMjpegUrl?: string` — Full HTTP(S) MJPEG stream URL (including any gateway path or query string). Cannot be combined with `wdaMjpegPort`. - `wdaMjpegFrameSource?: { enabled?: boolean }` — Whether to use WDA's MJPEG stream as the continuous frame source for `agent.startObserving()`. Disabled by default; when disabled, observers fall back to sequential `screenshotBase64()` calls. - `autoDismissKeyboard?: boolean` — Whether to automatically dismiss the on-screen keyboard after text input. Default: `true`. - `keyboardTypeDelay?: number` — Delay in milliseconds between keystrokes (must be a finite non-negative number). When set to a positive value, `'legacy'` input sends characters one Unicode code point at a time through WDA's `/wda/keys` endpoint. Useful when an input field drops characters during fast typing. - `inputStrategy?: 'legacy' | 'sequential' | 'bulk'` — Default text input strategy for `Input` actions. Default: `'legacy'`: - `'sequential'`: Makes one WDA call per Unicode code point. Use this strategy when setting a positive `keyboardTypeDelay`. - `'bulk'`: Sends the entire string in a single WDA text call. Requires `keyboardTypeDelay` to be omitted or set to `0`. - `customActions?: DeviceAction<any>[]` — Custom actions registered for the Agent planner to invoke. Pass this option to `new IOSDevice()` or `agentFromWebDriverAgent()`; see [Integrate with any interface](/integrate-with-any-interface.md) for details. ## Platform methods [](#) ### `launch()` Open a web URL, launch a native app, or trigger a custom URL scheme. ```ts function launch(target: string): Promise<void>; ``` - `target: string` — Web URL, app bundle ID, custom URL scheme (such as `tel:` or `mailto:`), or app name. If `target` matches a key in `appNameMapping`, Midscene resolves it to the mapped bundle ID; otherwise, it launches `target` as provided. ```ts await agent.launch('https://www.apple.com'); await agent.launch('com.apple.Preferences'); await agent.launch('myapp://profile/user/123'); await agent.launch('tel:+1234567890'); ``` [](#) ### `terminate()` Terminate (close) a running iOS app by its bundle ID. ```ts function terminate(bundleId: string): Promise<void>; ``` - `bundleId: string` — Bundle ID of the app to terminate (such as `com.apple.Preferences`) or an app name registered in `appNameMapping`. ```ts await agent.terminate('com.apple.Preferences'); await agent.terminate('com.apple.mobilesafari'); ``` [](#) ### `runWdaRequest()` Send raw requests to WebDriverAgent REST endpoints when you need low-level control. ```ts function runWdaRequest(params: { method: 'GET' | 'POST' | 'DELETE' | 'PUT'; endpoint: string; data?: Record<string, any>; }): Promise<any>; ``` - `params.method` — HTTP method: `'GET'`, `'POST'`, `'DELETE'`, or `'PUT'`. - `params.endpoint` — WebDriverAgent endpoint path. - `params.data` — Optional JSON request body. ```ts const screen = await agent.runWdaRequest({ method: 'GET', endpoint: '/wda/screen', }); ``` When calling `device.runWdaRequest()` directly on an `IOSDevice` instance, use the positional signature: `runWdaRequest(method, endpoint, data?)`. [](#) ### System navigation - `agent.home(): Promise<void>` — Return to the Home screen. - `agent.appSwitcher(): Promise<void>` — Open the app switcher. [](#) ### `device.hideKeyboard()` ```typescript device.hideKeyboard(keyNames?: string[]): Promise<boolean> ``` Dismisses the on-screen keyboard and returns whether it was hidden. When called explicitly, a failed WDA request throws an error. By default (`autoDismissKeyboard: true`), after entering text, Midscene attempts to locate the standard iOS keyboard accessory toolbar, tap its dismiss button, and wait until WebDriverAgent confirms that the keyboard is hidden. Some keyboards (such as the iPhone number pad) do not include a dismiss button. If the toolbar cannot be safely identified, the keyboard remains visible, or the dismissal request fails, Midscene logs a warning instead of failing the text input step. When an `Enter`, `Return`, or `Tab` key action immediately follows an auto-dismissed input, Midscene restores focus to that input field once before sending the key. Any intervening pointer, touch, system, custom, or text-input action clears the pending focus target. :::warning Custom input accessory toolbars defined by an app may contain business buttons such as Save or Submit. To avoid accidental taps, Midscene skips toolbars that do not match the standard iOS layout (navigation controls on the left, dismiss button on the right). If your app uses a custom toolbar, set `autoDismissKeyboard: false` and call `hideKeyboard()` explicitly with the dismiss control's accessibility name. ::: ```typescript const device = new IOSDevice({ autoDismissKeyboard: false, }); await device.connect(); // After entering text, explicitly tap the custom keyboard dismiss control await device.hideKeyboard(['Close Keyboard']); ``` [](#) ## Lifecycle ```typescript agent.destroy(): Promise<void> ``` Calling `agent.destroy()` waits for pending operations to complete, calls the underlying Device's `destroy()`, and finalizes the execution report. Do not share a single Device instance across multiple Agents or reuse a Device after cleanup. On iOS, `device.destroy()` stops the MJPEG frame source, deletes the WDA session created by Midscene, and stops the WDA manager (an external session passed via `sessionId` is detached rather than deleted). Any Device cleanup errors are logged. ## Troubleshooting [](#) ### How do I customize the WebDriverAgent port and host? Pass `wdaPort` and `wdaHost` to `agentFromWebDriverAgent()` or the `IOSDevice` constructor: ```typescript // Option 1: Via factory function (recommended) const agent = await agentFromWebDriverAgent({ wdaPort: 8100, // Custom port wdaHost: '192.168.1.100', // Custom host }); // Option 2: Via IOSDevice constructor const device = new IOSDevice({ wdaPort: 8100, wdaHost: '192.168.1.100', }); ``` For physical or remote devices, make sure port forwarding is set up accordingly: ```bash iproxy 8100 8100 YOUR_DEVICE_ID ``` If WebDriverAgent is exposed behind a gateway with a path prefix, specify the full API base URL using `wdaBaseUrl` instead: ```typescript const agent = await agentFromWebDriverAgent({ wdaBaseUrl: 'https://gateway.example/device/wda', }); ``` Midscene appends `/status`, `/session`, and session command paths to this base URL. Use either `wdaBaseUrl` or `wdaHost` / `wdaPort`—combining them throws an error. Note that `wdaBaseUrl` only configures WDA API requests; by default, the MJPEG screen stream still connects to `http://localhost:9100`. If your gateway also proxies the MJPEG stream, configure `wdaMjpegUrl` separately: ```typescript const agent = await agentFromWebDriverAgent({ wdaBaseUrl: 'https://gateway.example/device/wda', wdaMjpegUrl: 'https://gateway.example/device/mjpeg', }); ``` `wdaMjpegUrl` must be a full HTTP(S) URL (with its own host, port, path, and query string; embedded credentials and URL fragments are rejected) and cannot be combined with `wdaMjpegPort`. For local port forwarding, leave `wdaMjpegUrl` unset and configure `wdaMjpegPort` (default `9100`). If the MJPEG stream is unavailable, Playground automatically falls back to screenshot polling. --- url: /sdk/playwright.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Web / Playwright SDK `@midscene/web/playwright` provides Agents bound to a Playwright page or BrowserContext. Both inherit the base Agent’s [AI methods](/reference.md#interaction-methods) and accept Web configuration options. ## Imports and API overview ```typescript import { PlaywrightPageAgent, PlaywrightAgent, PlaywrightBrowserAgent, } from '@midscene/web/playwright'; ``` | API | Scope | Purpose | | ------------------------ | -------------------- | ---------------------------------------------------------------------- | | `PlaywrightPageAgent` | One `Page` | Operate on the same page throughout its lifetime | | `PlaywrightAgent` | One `Page` | Compatibility alias for `PlaywrightPageAgent`, with identical behavior | | `PlaywrightBrowserAgent` | One `BrowserContext` | Switch between pages; subsequent AI operations use the active page | In the signatures below, `Page` and `BrowserContext` come from `playwright`. Option types come from `@midscene/web/playwright`. [](#) ## `PlaywrightPageAgent` {#playwright-agent} ```typescript new PlaywrightPageAgent(page: Page, options?: PlaywrightPageAgentOpt) ``` - `page`: required, an existing Playwright page. Throws when omitted. - `options`: optional, accepts [shared Agent options](/reference.md#agent-options) and [Web options](#web-options). ```typescript const agent = new PlaywrightPageAgent(page, { forceSameTabNavigation: false, }); await agent.aiAct('Click the login button'); ``` The Agent stays bound to the supplied page. By default, `forceSameTabNavigation: true` intercepts `window.open` and links with `target="_blank"` to open them in the current page. Set it to `false` to preserve new tabs; the Agent will not automatically switch to them. ## `PlaywrightBrowserAgent` {#playwright-browser-agent} ```typescript new PlaywrightBrowserAgent( context: BrowserContext, initialPage: Page, options?: PlaywrightBrowserAgentOpt, ) ``` - `context`: required, the BrowserContext used to listen for, list, and create pages. - `initialPage`: required, the initial active page. Use a page from this context. - `options`: optional, accepts shared Agent options, Web options, and the dedicated options below. Throws when `context` or `initialPage` is omitted. Browser Agent does not accept `forceSameTabNavigation`; even passing `false` through JavaScript throws an error. ### `PlaywrightBrowserAgent.create()` ```typescript PlaywrightBrowserAgent.create( context: BrowserContext, options?: PlaywrightBrowserAgentCreateOpt, ): Promise<PlaywrightBrowserAgent> ``` Creates an Agent asynchronously. The initial page is selected in this order: `options.initialPage` → `context.pages()[0]` → `await context.newPage()`. ```typescript const agent = await PlaywrightBrowserAgent.create(context, { autoFollowNewPage: true, }); ``` ### Dedicated options | Option | Type | Default | Description | | ------------------- | --------- | ---------------------- | ------------------------------------------------------- | | `autoFollowNewPage` | `boolean` | `false` | Automatically make newly created context pages active | | `newPageTimeout` | `number` | `5000` | Default timeout for `waitForNewPage()`, in milliseconds | | `initialPage` | `Page` | Automatically selected | Initial active page; available only in `create()` | ## Page management APIs {#page-management} These properties and methods belong only to `PlaywrightBrowserAgent`. ### `activePage` ```typescript agent.activePage: Page ``` Read-only property returning the Playwright page used by current AI operations. Use `setActivePage()` to switch pages. ### `pages()` ```typescript agent.pages(): Page[] ``` Returns the pages in the bound context without changing the active page. ### `newPage()` ```typescript agent.newPage(): Promise<Page> ``` Creates a page in the bound context, makes it active, and returns it. ### `setActivePage()` ```typescript agent.setActivePage(page: Page): Promise<void> ``` Makes the supplied page active and attempts to bring it to the foreground. Throws for an invalid or closed page. Supply a page from the bound context. [](#) ### `waitForNewPage()` {#wait-for-new-page} ```typescript agent.waitForNewPage( action?: () => Promise<unknown> | unknown, options?: { timeout?: number }, ): Promise<Page> ``` Registers a context page listener before running the optional `action`, then returns the new page it observes. `options.timeout` overrides `newPageTimeout` for this call, in milliseconds. Throws on timeout or if `action` fails. This method does not itself switch the active page. With `autoFollowNewPage: true`, the independent page listener still switches automatically. Keep that option `false` to control switching explicitly: ```typescript const agent = await PlaywrightBrowserAgent.create(context, { autoFollowNewPage: false, }); const newPage = await agent.waitForNewPage( () => agent.aiTap('Open details'), { timeout: 10000 }, ); await agent.setActivePage(newPage); await agent.aiAssert('The details page is open'); ``` ## Configuration options {#web-options} Both Agents also accept [shared Agent options](/reference.md#agent-options), including model, report, and cache settings. | Option | Type | Default | Description | | -------------------------------- | --------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `forceSameTabNavigation` | `boolean` | `true` | Page Agent only; opens new-tab links in the current page | | `waitForNavigationTimeout` | `number` | `5000` | Timeout for waiting for the page’s `html` element, in milliseconds; `0` skips the check. Execution continues after timeout; this does not guarantee application readiness | | `waitForNetworkIdleTimeout` | `number` | — | Has no effect in Playwright | | `enableTouchEventsInActionSpace` | `boolean` | `false` | Adds touch gestures to the action space | | `keyboardTypeDelay` | `number` | Unset | Per-character input delay in milliseconds; must be finite and non-negative. In legacy mode, Playwright’s `page.keyboard.type` handles positive delays. When unset, uses the underlying driver’s default | | `inputStrategy` | `'legacy' \| 'sequential' \| 'bulk'` | `'legacy'` | Text input strategy; `sequential` sends individual Unicode code points, while `bulk` inserts the full text at once | | `forceChromeSelectRendering` | `boolean` | `true` | Injects `base-select` styling so native `select` options appear in screenshots; requires Playwright ≥ `1.52.0` and browser support for this styling | | `customActions` | `DeviceAction[]` | Unset | Adds [custom actions](/integrate-with-any-interface.md) to the planner | | `beforeInvokeAction` | `(actionName: string, param: any) => Promise<void>` | Unset | Callback before an action | | `afterInvokeAction` | `(actionName: string, param: any) => Promise<void>` | Unset | Callback after an action | | `testRunner` | `PlaywrightTestRunnerOptions` | Unset | Supplies base URL, cookie, and storage-state settings to Midscene Test’s Playwright Nodes; this is not Playwright Test fixture configuration | `inputStrategy: 'bulk'` requires `keyboardTypeDelay` to be omitted or set to `0`. Use `'sequential'` for delayed input. To wait for application readiness, use `aiWaitFor()` or Playwright’s own waiting APIs. ## Lifecycle {#lifecycle} ```typescript agent.destroy(): Promise<void> ``` Both Agents follow the [shared `destroy()` contract](/reference.md#agentdestroy): it waits for associated operations, cleans up Agent-owned resources, calls the internal Device’s `destroy()`, and finishes report processing. Browser Agent also removes its automatic page-following listener. The Playwright Device’s `destroy()` does not close the supplied Page, BrowserContext, or Browser, or explicitly disconnect a remote browser. The caller manages these Playwright resources. Pages and browsers remain usable after the Agent is destroyed. ```typescript try { await agent.aiAct('Submit the form'); } finally { await agent.destroy(); // The caller closes page, context, or browser according to resource ownership. } ``` ## Browser support and limitations Chromium is recommended. Some capabilities depend on CDP, including browser-level events, touch gestures, and fallback paths for some interactions. Firefox and WebKit may support basic Playwright operations, but CDP-dependent capabilities may fail. ### Remote browsers Agents accept existing Playwright pages, with the same construction API as local browsers. For example, after connecting over CDP: ```typescript import { chromium } from 'playwright'; import { PlaywrightPageAgent } from '@midscene/web/playwright'; const browser = await chromium.connectOverCDP(cdpWsUrl); const context = browser.contexts()[0]; const page = context.pages()[0] ?? await context.newPage(); const agent = new PlaywrightPageAgent(page); ``` The caller manages the connection, authentication, and browser closure. [](#) #### Getting a CDP WebSocket URL {#get-cdp-url} You can get a CDP WebSocket URL from various sources, for example: - **Browser Use**: Get an API key at [https://cloud.browser-use.com](https://cloud.browser-use.com) and connect to `wss://connect.browser-use.com?apiKey=YOUR_API_KEY` - **BrowserBase**: Sign up at [https://browserbase.com](https://browserbase.com) and get your CDP URL - **Browserless**: Use [https://browserless.io](https://browserless.io) or run your own instance - **Local Chrome**: Run Chrome with `--remote-debugging-port=9222` and use `ws://localhost:9222/devtools/browser/...` - **Docker**: Run Chrome in a Docker container with debugging port exposed ## FAQ ### Playwright browser download takes too long Playwright does not download browser binaries during `pnpm install` by default. You need to run `pnpm exec playwright install` separately, and that step can be slow on limited networks. You can speed it up in two ways: 1. Use a mirror, for example `npmmirror.com` ```bash PLAYWRIGHT_DOWNLOAD_HOST="https://npmmirror.com/mirrors/playwright" pnpm exec playwright install ``` 2. Download only the commonly used `chromium` ```bash pnpm exec playwright install --with-deps chromium ``` ### Cannot click the dropdown This usually happens when the page uses a native `select` element for the dropdown. In that case, the browser asks the operating system to render the expanded option list with a native control, so the dropdown is not actually rendered inside the webpage and cannot be captured by Playwright screenshots. First, check the screenshot in the report. If the dropdown options do not appear in the report screenshot after the click, this is very likely the cause. Midscene enables `forceChromeSelectRendering` by default, which forces Chrome to render the `select` dropdown so it appears in screenshots and can be recognized by Playwright. The dropdown style will look noticeably different from the operating system's default style. If you need the native rendering back, set `forceChromeSelectRendering: false`. ### The webpage continues to flash when running in headed mode In the local visualization interface, continuous flashing is usually caused by a mismatch between the viewport's `deviceScaleFactor` and the system/browser's pixel ratio (common on high-resolution or Retina screens). This flashing does not affect Midscene's screenshots or automation execution, but it does affect the local preview experience. To resolve this, set `deviceScaleFactor` to match your browser's `window.devicePixelRatio`, or use Puppeteer's auto-adaptation feature. ```typescript // Playwright: Playwright does not support using 0 for auto-adaptation like Puppeteer const page = await browser.newPage({ deviceScaleFactor: 2, // Replace the number 2 with your window.devicePixelRatio }) ``` If you are unsure of your browser's pixel ratio, you can press F12 on any page to open the console and type `window.devicePixelRatio` to check; or paste the following into the Chrome address bar and press Enter to see the value in a popup: ```plain data:text/html,<script>alert(`deviceScaleFactor of your browser: ${devicePixelRatio}`)</script> ``` ### Customize the network timeout `waitForNetworkIdleTimeout` has no effect in Playwright. `waitForNavigationTimeout` only controls waiting for the page’s `html` element; it does not guarantee application readiness. See [Configuration options](#web-options). For Puppeteer, `waitForNetworkIdleTimeout` defaults to `2000` milliseconds; `0` disables the check. See the [default waiting strategy](/reference.md#default-waiting-strategy). ### `waiting for fonts to load` or `page.screenshot: Timeout ... exceeded` when taking screenshots If you see an error like this in a Playwright-based environment: ```plain page.screenshot: Timeout 10000ms exceeded. Call log: - taking page screenshot - waiting for fonts to load... ``` This is usually not caused by Midscene itself. Playwright waits for fonts to finish loading before taking a screenshot. In some CI, container, or restricted network environments, font resources may load very slowly or never finish, which can eventually cause the screenshot to time out. You can work around it by setting this environment variable: ```bash export PW_TEST_SCREENSHOT_NO_FONTS_READY=1 ``` If you want to set it only for a single command, you can also write: ```bash PW_TEST_SCREENSHOT_NO_FONTS_READY=1 <your-command> ``` For more background, see the Playwright issue: [\[BUG\] Page.screenshot method hangs indefinitely](https://github.com/microsoft/playwright/issues/28995). --- url: /sdk/rstest.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Integrate with Rstest We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for writing JavaScript and TypeScript tests on Android, iOS, HarmonyOS, and desktop. This guide covers Rstest. Rstest organizes test cases, runs lifecycle hooks, and aggregates test results, while Midscene Agents connect to devices, interact with the UI, and perform assertions. ## Before you begin - **Runtime**: Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. Use an existing project or run `pnpm init` to create one (skip if `package.json` already exists). - **Model configuration and verification**: Complete [model configuration](/model-api-setup) and [model verification](/model-config#verify-model-connectivity), then save the configuration in the project's `.env` file or shell environment. - **Platform environment**: Complete the environment setup for [Android](/platforms/android), [iOS](/platforms/ios), [HarmonyOS](/platforms/harmonyos), or [desktop](/platforms/desktop), including device connections and required permissions. - **(Optional) Try Playground first**: Run an action and an assertion against your target interface in the [Playground for your platform](/get-started?scene=playground) to verify screenshots, interactions, and model behavior. ## 1. Install dependencies **Android** ```bash pnpm add -D @rstest/core dotenv @midscene/android ``` **iOS** ```bash pnpm add -D @rstest/core dotenv @midscene/ios ``` **HarmonyOS** ```bash pnpm add -D @rstest/core dotenv @midscene/harmony ``` **Desktop** ```bash pnpm add -D @rstest/core dotenv @midscene/computer ``` ## 2. Configure Rstest Create `rstest.config.ts`. If your project already uses Rstest for unit tests, you can save this configuration separately as `rstest.device.config.ts` and pass `--config rstest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="rstest.config.ts" import { defineConfig } from '@rstest/core'; export default defineConfig({ include: ['e2e/**/*.test.ts'], testEnvironment: 'node', testTimeout: 90_000, hookTimeout: 90_000, pool: { maxWorkers: 1 }, maxConcurrency: 1, output: { externals: { '@silvia-odwyer/photon': 'commonjs @silvia-odwyer/photon', }, }, }); ``` Model calls and device connections can take longer than unit tests, so adjust `testTimeout` and `hookTimeout` for your cases. For a shared device, use one worker (`pool.maxWorkers: 1`) and `maxConcurrency: 1`, and avoid `test.concurrent` and `describe.concurrent`. The external declaration keeps the Photon native addon out of the test bundle. See the [Rstest configuration reference](https://rstest.rs/config/). ## 3. Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: **Android** ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from '@rstest/core'; import { agentFromAdbDevice } from '@midscene/android'; let agent: Awaited<ReturnType<typeof agentFromAdbDevice>> | undefined; beforeEach(async () => { agent = await agentFromAdbDevice(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.android.settings'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` If multiple devices are connected, pass a device ID to `agentFromAdbDevice(deviceId)`. See the [Android SDK guide](/sdk/android.md) for connection options. **iOS** ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from '@rstest/core'; import { agentFromWebDriverAgent } from '@midscene/ios'; let agent: Awaited<ReturnType<typeof agentFromWebDriverAgent>> | undefined; beforeEach(async () => { agent = await agentFromWebDriverAgent({ wdaHost: 'localhost', wdaPort: 8100, }); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.apple.Preferences'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` Replace `wdaHost` and `wdaPort` with your verified WebDriverAgent service endpoint. See the [iOS SDK guide](/sdk/ios.md) for connection options. **HarmonyOS** ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from '@rstest/core'; import { agentFromHdcDevice } from '@midscene/harmony'; let agent: Awaited<ReturnType<typeof agentFromHdcDevice>> | undefined; beforeEach(async () => { agent = await agentFromHdcDevice(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.huawei.hmos.settings'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` If multiple devices are connected, pass a device ID to `agentFromHdcDevice(deviceId)`. See the [HarmonyOS SDK guide](/sdk/harmonyos.md) for connection options. **Desktop** ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from '@rstest/core'; import { agentForComputer } from '@midscene/computer'; let agent: Awaited<ReturnType<typeof agentForComputer>> | undefined; beforeEach(async () => { agent = await agentForComputer(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` Before running the test, open your system Settings app and bring a scrollable settings page to the foreground. Keep it visible during the test. See the [desktop SDK guide](/sdk/desktop.md) for permissions and connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## 4. Run the test and view the report ```bash pnpm exec rstest run e2e/settings.test.ts ``` Rstest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Rstest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Rstest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). ## Common methods | Category | Representative methods | Description | | ------------------ | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | Auto-planning | `aiAct` | Describe a goal in natural language and let the Agent plan and execute multiple steps. | | Direct interaction | `aiTap`, `aiInput` | Locate a UI element by description and perform a single specified action without multi-step planning. | | Data extraction | `aiQuery`, `aiString`, `aiNumber`, `aiBoolean` | Extract structured or primitive data from the current UI for further processing in code. | | Assertions | `aiAssert` | Verify that the current UI meets an expectation; throws an error if it does not. | | Waiting | `aiWaitFor` | Wait until the UI meets a specified condition; throws an error on timeout. | In practice, you typically perform actions with `aiAct` or direct interaction methods and then verify the outcome with `aiAssert`—completing an action does not guarantee that the expected UI state was reached. For full parameter and return value details, see the [Agent API reference](/reference/index.md#interaction-methods). ## Lifecycle and exclusive device access - **Isolate Agents per test**: Create a new Agent for each test case. Each Device instance belongs to a single Agent, and `agent.destroy()` cleans up the associated Device as well—do not reuse a destroyed instance in subsequent tests. - **Manage application state explicitly**: Destroying an Agent does not reset app data or close the app. Each test should explicitly prepare the required initial screen and data, and clean up state as needed so tests can be retried or run individually. - **Avoid device contention across processes**: The runner's sequential settings only apply to the current test runner process; other local processes, CI jobs, or manual input can still contend for the same device. To run tests in parallel, assign a dedicated device or desktop session to each worker and explicitly specify its connection target in code. --- url: /sdk/standalone.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Write standalone automation scripts You can call the Midscene SDK directly from a Node.js script to operate apps, extract data, or automate everyday workflows without a test runner. Your script controls the execution order, branching logic, error handling, and resource cleanup. ## Before you begin - **Runtime**: Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. Use an existing project or run `pnpm init` to create one (skip if `package.json` already exists). - **Model configuration and verification**: Complete [model configuration](/model-api-setup) and [model verification](/model-config#verify-model-connectivity), then save the configuration in the project's `.env` file or shell environment. - **Platform environment**: Prepare the target browser or device, including connections and required permissions. For mobile and desktop, complete the setup for [Android](/platforms/android), [iOS](/platforms/ios), [HarmonyOS](/platforms/harmonyos), or [desktop](/platforms/desktop); for Chrome Bridge, install the [Chrome extension](/platforms/web#chrome-extension). The browser installation command for Web / Playwright is included in the example below. - **(Optional) Try Playground first**: Run an action and an assertion against your target interface in the [Playground for your platform](/get-started?scene=playground) to verify screenshots, interactions, and model behavior. ## Run your first example Select your target platform from the tabs below, install the dependencies, save the script as `demo.ts`, and run the command. Each example is self-contained. The script opens the public React TodoMVC page, adds a todo item named `Try Midscene`, marks it as completed, and asserts the result. Make sure the browser or device can access that URL; on mobile, complete any first-run prompts in the default browser beforehand, and on desktop, ensure a browser is installed. **Web / Playwright** **1. Install dependencies** ```bash pnpm add -D @midscene/web playwright dotenv tsx pnpm exec playwright install chromium ``` **2. Write the code** Save the following code as `demo.ts`, and make sure your verified model configuration is saved in a `.env` file in the same directory (loaded automatically via `dotenv/config`). ```typescript title="demo.ts" import 'dotenv/config'; import { chromium } from 'playwright'; import { PlaywrightAgent } from '@midscene/web/playwright'; async function main() { const browser = await chromium.launch(); try { const page = await browser.newPage(); await page.goto('https://todomvc.com/examples/react/dist/#/'); const agent = new PlaywrightAgent(page); try { await agent.aiWaitFor('The TodoMVC input is visible'); await agent.aiAct('Add a todo named Try Midscene, then mark it completed'); await agent.aiAssert('A todo named Try Midscene is marked completed'); } finally { await agent.destroy(); } } finally { await browser.close(); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` **3. Run** (Optional) Verify your model configuration before running the script: ```bash pnpm dlx @midscene/test@latest model verify ``` Run the script from the same directory: ```bash pnpm exec tsx demo.ts ``` **4. Further reading** For browser connection options, platform capabilities, and limitations, see [Web / Playwright SDK](/sdk/playwright.md). To use Midscene in a test suite, see [Integrate with Playwright Test](/integrate-with-playwright.md). **Web / Puppeteer** **1. Install dependencies** ```bash pnpm add -D @midscene/web puppeteer dotenv tsx ``` **2. Write the code** Save the following code as `demo.ts`, and make sure your verified model configuration is saved in a `.env` file in the same directory (loaded automatically via `dotenv/config`). ```typescript title="demo.ts" import 'dotenv/config'; import puppeteer from 'puppeteer'; import { PuppeteerAgent } from '@midscene/web/puppeteer'; async function main() { const browser = await puppeteer.launch(); try { const page = await browser.newPage(); await page.goto('https://todomvc.com/examples/react/dist/#/'); const agent = new PuppeteerAgent(page); try { await agent.aiWaitFor('The TodoMVC input is visible'); await agent.aiAct('Add a todo named Try Midscene, then mark it completed'); await agent.aiAssert('A todo named Try Midscene is marked completed'); } finally { await agent.destroy(); } } finally { await browser.close(); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` **3. Run** (Optional) Verify your model configuration before running the script: ```bash pnpm dlx @midscene/test@latest model verify ``` Run the script from the same directory: ```bash pnpm exec tsx demo.ts ``` **4. Further reading** For connection settings, platform capabilities, and limitations, see the [Puppeteer integration guide](/integrate-with-puppeteer.md). **Chrome Bridge** **1. Install dependencies** ```bash pnpm add -D @midscene/web dotenv tsx ``` **2. Write the code** Save the following code as `demo.ts`, and make sure your verified model configuration is saved in a `.env` file in the same directory (loaded automatically via `dotenv/config`). Keep Chrome open and approve the connection when prompted by the extension. When the script finishes, it automatically closes the tab it created. ```typescript title="demo.ts" import 'dotenv/config'; import { AgentOverChromeBridge } from '@midscene/web/bridge-mode'; async function main() { const agent = new AgentOverChromeBridge({ closeNewTabsAfterDisconnect: true }); try { await agent.connectNewTabWithUrl('https://todomvc.com/examples/react/dist/#/'); await agent.aiWaitFor('The TodoMVC input is visible'); await agent.aiAct('Add a todo named Try Midscene, then mark it completed'); await agent.aiAssert('A todo named Try Midscene is marked completed'); } finally { await agent.destroy(); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` **3. Run** (Optional) Verify your model configuration before running the script: ```bash pnpm dlx @midscene/test@latest model verify ``` Run the script from the same directory: ```bash pnpm exec tsx demo.ts ``` **4. Further reading** For connection settings, platform capabilities, and limitations, see the [Chrome Bridge SDK](/sdk/chrome-bridge.md). **Android** **1. Install dependencies** ```bash pnpm add -D @midscene/android dotenv tsx ``` **2. Write the code** Save the following code as `demo.ts`, and make sure your verified model configuration is saved in a `.env` file in the same directory (loaded automatically via `dotenv/config`). By default, this connects to the first available device. If multiple devices are connected, pass a device ID from `adb devices` to `agentFromAdbDevice(deviceId)`. ```typescript title="demo.ts" import 'dotenv/config'; import { agentFromAdbDevice } from '@midscene/android'; async function main() { const agent = await agentFromAdbDevice(); try { await agent.launch('https://todomvc.com/examples/react/dist/#/'); await agent.aiWaitFor('The TodoMVC input is visible'); await agent.aiAct('Add a todo named Try Midscene, then mark it completed'); await agent.aiAssert('A todo named Try Midscene is marked completed'); } finally { await agent.destroy(); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` **3. Run** (Optional) Verify your model configuration before running the script: ```bash pnpm dlx @midscene/test@latest model verify ``` Run the script from the same directory: ```bash pnpm exec tsx demo.ts ``` **4. Further reading** For connection settings, platform capabilities, and limitations, see the [Android integration guide](/sdk/android.md). **iOS** **1. Install dependencies** ```bash pnpm add -D @midscene/ios dotenv tsx ``` **2. Write the code** Save the following code as `demo.ts`, and make sure your verified model configuration is saved in a `.env` file in the same directory (loaded automatically via `dotenv/config`). Replace `wdaHost` and `wdaPort` with your verified WebDriverAgent service endpoint. ```typescript title="demo.ts" import 'dotenv/config'; import { agentFromWebDriverAgent } from '@midscene/ios'; async function main() { const agent = await agentFromWebDriverAgent({ wdaHost: 'localhost', wdaPort: 8100, }); try { await agent.launch('https://todomvc.com/examples/react/dist/#/'); await agent.aiWaitFor('The TodoMVC input is visible'); await agent.aiAct('Add a todo named Try Midscene, then mark it completed'); await agent.aiAssert('A todo named Try Midscene is marked completed'); } finally { await agent.destroy(); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` **3. Run** (Optional) Verify your model configuration before running the script: ```bash pnpm dlx @midscene/test@latest model verify ``` Run the script from the same directory: ```bash pnpm exec tsx demo.ts ``` **4. Further reading** For connection settings, platform capabilities, and limitations, see the [iOS integration guide](/sdk/ios.md). **HarmonyOS** **1. Install dependencies** ```bash pnpm add -D @midscene/harmony dotenv tsx ``` **2. Write the code** Save the following code as `demo.ts`, and make sure your verified model configuration is saved in a `.env` file in the same directory (loaded automatically via `dotenv/config`). By default, this connects to the first available device. If multiple devices are connected, pass a device ID from `hdc list targets` to `agentFromHdcDevice(deviceId)`. ```typescript title="demo.ts" import 'dotenv/config'; import { agentFromHdcDevice } from '@midscene/harmony'; async function main() { const agent = await agentFromHdcDevice(); try { await agent.launch('https://todomvc.com/examples/react/dist/#/'); await agent.aiWaitFor('The TodoMVC input is visible'); await agent.aiAct('Add a todo named Try Midscene, then mark it completed'); await agent.aiAssert('A todo named Try Midscene is marked completed'); } finally { await agent.destroy(); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` **3. Run** (Optional) Verify your model configuration before running the script: ```bash pnpm dlx @midscene/test@latest model verify ``` Run the script from the same directory: ```bash pnpm exec tsx demo.ts ``` **4. Further reading** For connection settings, platform capabilities, and limitations, see the [HarmonyOS integration guide](/sdk/harmonyos.md). **Desktop** **1. Install dependencies** ```bash pnpm add -D @midscene/computer dotenv tsx ``` **2. Write the code** Save the following code as `demo.ts`, and make sure your verified model configuration is saved in a `.env` file in the same directory (loaded automatically via `dotenv/config`). This script directly controls the browser on your active desktop. Avoid using the mouse or keyboard while it is running. ```typescript title="demo.ts" import 'dotenv/config'; import { agentForComputer } from '@midscene/computer'; async function main() { const agent = await agentForComputer(); try { await agent.aiAct('Open a browser and navigate to https://todomvc.com/examples/react/dist/#/'); await agent.aiWaitFor('The TodoMVC input is visible'); await agent.aiAct('Add a todo named Try Midscene, then mark it completed'); await agent.aiAssert('A todo named Try Midscene is marked completed'); } finally { await agent.destroy(); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` **3. Run** (Optional) Verify your model configuration before running the script: ```bash pnpm dlx @midscene/test@latest model verify ``` Run the script from the same directory: ```bash pnpm exec tsx demo.ts ``` **4. Further reading** For connection settings, platform capabilities, and limitations, see the [Desktop integration guide](/sdk/desktop.md). ## View the report By default, the SDK generates an HTML report under `midscene_run/report/` in your project and prints the file path in the terminal. Open the file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. If a script fails, locate the failed step in the report and compare its screenshots against the error message. These reports are designed for inspecting GUI Agent execution details; when integrated with a test runner, the runner still manages overall test results and pass/fail summaries. To merge or further process report files, see [Process report files](/consume-report-file.md). ## Understand the Agent design ### Device and Agent Working with the SDK involves two core concepts: - **Device**: Communicates with the underlying browser or device, providing low-level capabilities such as taking screenshots, clicking, and typing. For example, `AndroidDevice` connects to and controls an Android device over `adb`. - **Agent**: Combines a Device's low-level capabilities with an AI model to understand the UI and execute tasks. Your code primarily calls Agent methods such as `aiAct`, `aiAssert`, and `aiQuery`. You can instantiate a Device manually and pass it to the corresponding Agent, or use the SDK's convenience factory functions such as `agentFromAdbDevice()`, `agentFromWebDriverAgent()`, `agentFromHdcDevice()`, and `agentForComputer()`. These factories create and connect the Device internally and return a ready-to-use Agent. For Playwright and Puppeteer, pass an existing `Page` instance directly to `PlaywrightAgent` or `PuppeteerAgent`—no separate Device instantiation is required. ### Lifecycle and resource ownership Each Device instance belongs to a single Agent. Calling `agent.destroy()` also cleans up the bound Device instance and its resources (exact cleanup behavior varies by platform; for example, Android cleanup does not disconnect the host's `adb` session from the device). Do not reuse a Device after its Agent is destroyed, and do not share a single Device instance across multiple Agents. Wrap your execution logic in `try / finally` to ensure resources are released even when an action or assertion fails. Manage the lifecycle of externally created resources separately. For example, the Web examples on this page launch their own browser instance, so they explicitly call `browser.close()` after destroying the Agent; the Chrome Bridge example sets `closeNewTabsAfterDisconnect` to close the tab it opened upon disconnecting. Do not assume that `agent.destroy()` will automatically close external browsers or target applications. ### Common methods | Category | Representative methods | Description | | ------------------ | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | Auto-planning | `aiAct` | Describe a goal in natural language and let the Agent plan and execute multiple steps. | | Direct interaction | `aiTap`, `aiInput` | Locate a UI element by description and perform a single specified action without multi-step planning. | | Data extraction | `aiQuery`, `aiString`, `aiNumber`, `aiBoolean` | Extract structured or primitive data from the current UI for further processing in code. | | Assertions | `aiAssert` | Verify that the current UI meets an expectation; throws an error if it does not. | | Waiting | `aiWaitFor` | Wait until the UI meets a specified condition; throws an error on timeout. | In practice, you typically perform actions with `aiAct` or direct interaction methods and then verify the outcome with `aiAssert`—completing an action does not guarantee that the expected UI state was reached. For full parameter and return value details, see the [Agent API reference](/reference/index.md#interaction-methods). ### Cross-platform support Each platform-specific Agent inherits from the base `Agent` class and extends it with platform-specific capabilities. For example, Web Agents integrate with browser `Page` objects, Android Agents provide system navigation methods such as `back()` and `home()`, and iOS Agents communicate with devices through WebDriverAgent. As a result, core AI methods like `aiAct` and `aiAssert` work consistently across platforms, while device connections, system-level actions, and resource cleanup remain platform-specific. Refer to the respective platform guides for detailed configuration options and limitations. --- url: /sdk/vitest.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Integrate with Vitest We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for writing JavaScript and TypeScript tests on Android, iOS, HarmonyOS, and desktop. This guide covers Vitest. Vitest organizes test cases, runs lifecycle hooks, and aggregates test results, while Midscene Agents connect to devices, interact with the UI, and perform assertions. ## Before you begin - **Runtime**: Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. Use an existing project or run `pnpm init` to create one (skip if `package.json` already exists). - **Model configuration and verification**: Complete [model configuration](/model-api-setup) and [model verification](/model-config#verify-model-connectivity), then save the configuration in the project's `.env` file or shell environment. - **Platform environment**: Complete the environment setup for [Android](/platforms/android), [iOS](/platforms/ios), [HarmonyOS](/platforms/harmonyos), or [desktop](/platforms/desktop), including device connections and required permissions. - **(Optional) Try Playground first**: Run an action and an assertion against your target interface in the [Playground for your platform](/get-started?scene=playground) to verify screenshots, interactions, and model behavior. ## 1. Install dependencies **Android** ```bash pnpm add -D vitest dotenv @midscene/android ``` **iOS** ```bash pnpm add -D vitest dotenv @midscene/ios ``` **HarmonyOS** ```bash pnpm add -D vitest dotenv @midscene/harmony ``` **Desktop** ```bash pnpm add -D vitest dotenv @midscene/computer ``` ## 2. Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## 3. Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: **Android** ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromAdbDevice } from '@midscene/android'; let agent: Awaited<ReturnType<typeof agentFromAdbDevice>> | undefined; beforeEach(async () => { agent = await agentFromAdbDevice(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.android.settings'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` If multiple devices are connected, pass a device ID to `agentFromAdbDevice(deviceId)`. See the [Android SDK guide](/sdk/android.md) for connection options. **iOS** ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromWebDriverAgent } from '@midscene/ios'; let agent: Awaited<ReturnType<typeof agentFromWebDriverAgent>> | undefined; beforeEach(async () => { agent = await agentFromWebDriverAgent({ wdaHost: 'localhost', wdaPort: 8100, }); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.apple.Preferences'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` Replace `wdaHost` and `wdaPort` with your verified WebDriverAgent service endpoint. See the [iOS SDK guide](/sdk/ios.md) for connection options. **HarmonyOS** ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromHdcDevice } from '@midscene/harmony'; let agent: Awaited<ReturnType<typeof agentFromHdcDevice>> | undefined; beforeEach(async () => { agent = await agentFromHdcDevice(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.huawei.hmos.settings'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` If multiple devices are connected, pass a device ID to `agentFromHdcDevice(deviceId)`. See the [HarmonyOS SDK guide](/sdk/harmonyos.md) for connection options. **Desktop** ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentForComputer } from '@midscene/computer'; let agent: Awaited<ReturnType<typeof agentForComputer>> | undefined; beforeEach(async () => { agent = await agentForComputer(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` Before running the test, open your system Settings app and bring a scrollable settings page to the foreground. Keep it visible during the test. See the [desktop SDK guide](/sdk/desktop.md) for permissions and connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## 4. Run the test and view the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). ## Common methods | Category | Representative methods | Description | | ------------------ | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | Auto-planning | `aiAct` | Describe a goal in natural language and let the Agent plan and execute multiple steps. | | Direct interaction | `aiTap`, `aiInput` | Locate a UI element by description and perform a single specified action without multi-step planning. | | Data extraction | `aiQuery`, `aiString`, `aiNumber`, `aiBoolean` | Extract structured or primitive data from the current UI for further processing in code. | | Assertions | `aiAssert` | Verify that the current UI meets an expectation; throws an error if it does not. | | Waiting | `aiWaitFor` | Wait until the UI meets a specified condition; throws an error on timeout. | In practice, you typically perform actions with `aiAct` or direct interaction methods and then verify the outcome with `aiAssert`—completing an action does not guarantee that the expected UI state was reached. For full parameter and return value details, see the [Agent API reference](/reference/index.md#interaction-methods). ## Lifecycle and exclusive device access - **Isolate Agents per test**: Create a new Agent for each test case. Each Device instance belongs to a single Agent, and `agent.destroy()` cleans up the associated Device as well—do not reuse a destroyed instance in subsequent tests. - **Manage application state explicitly**: Destroying an Agent does not reset app data or close the app. Each test should explicitly prepare the required initial screen and data, and clean up state as needed so tests can be retried or run individually. - **Avoid device contention across processes**: The runner's sequential settings only apply to the current test runner process; other local processes, CI jobs, or manual input can still contend for the same device. To run tests in parallel, assign a dedicated device or desktop session to each worker and explicitly specify its connection target in code. For complete working projects, see the Vitest examples for [Android](https://github.com/web-infra-dev/midscene-example/tree/main/android/vitest-demo), [iOS](https://github.com/web-infra-dev/midscene-example/tree/main/ios/vitest-demo), [HarmonyOS](https://github.com/web-infra-dev/midscene-example/tree/main/harmony/vitest-demo), and [desktop](https://github.com/web-infra-dev/midscene-example/tree/main/computer/vitest-demo). --- url: /showcases-android.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # **Prompt** : Open the Booking App, search for a hotel in Tokyo for four adults on Christmas, with a score of 8 or above. View the full report of this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/booking.html) --- url: /showcases-computer.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # **macOS** **Prompt:** Help me post a tweet promoting Midscene's support for AutoGLM through safari, with the following requirements: 1. Text content: Midscene now supports AutoGLM! 2. Media content: Use the AutoGLM video from the download folder! View the full report for this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/pc-twitter2-midscene_report.html) **Prompt:** Open Google and query San Jose tomorrow weather temperature View the full report for this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/weather-computer-2026-01-14_11-26-38-9592ecf5.html) **Windows** **Prompt:** Open Sauce Demo e-commerce site, login and add items to cart View the full report for this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/shop-computer-2026-01-14_11-57-36-f8411b8f.html) **Linux** **Prompt:** Open TodoMVC, add multiple tasks and filter them View the full report for this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/todo-computer-2026-01-13_15-40-37-6f45fb0f.html) --- url: /showcases-harmony.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # **Prompt** : Open Settings, scroll to find "About phone", view device information. View the full report of this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/harmony.html) --- url: /showcases-ios.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # **Prompt** : Open Twitter and auto-like the first tweet by [@midscene_ai](https://x.com/midscene_ai) View the full report of this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/x.html) --- url: /showcases-web.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # **Prompt:** Fill out the GitHub sign-up form and pass validation, but do not submit it. Midscene generates a complete report for every task so developers can review the operation process. See the report for the demo above: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/github.html) --- url: /showcases.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Showcases This page introduces cross-platform GUI Agent, E2E test, and community showcases built with Midscene. ## Cross-platform GUI Agent Showcases ### Web **Prompt:** Fill out the GitHub sign-up form and pass validation, but do not submit it. Midscene generates a complete report for every task so developers can review the operation process. See the report for the demo above: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/github.html) ### iOS **Prompt** : Open Twitter and auto-like the first tweet by [@midscene_ai](https://x.com/midscene_ai) View the full report of this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/x.html) ### Android **Prompt** : Open the Booking App, search for a hotel in Tokyo for four adults on Christmas, with a score of 8 or above. View the full report of this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/booking.html) ### HarmonyOS **Prompt** : Open Settings, scroll to find "About phone", view device information. View the full report of this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/harmony.html) ### Desktop **macOS** **Prompt:** Help me post a tweet promoting Midscene's support for AutoGLM through safari, with the following requirements: 1. Text content: Midscene now supports AutoGLM! 2. Media content: Use the AutoGLM video from the download folder! View the full report for this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/1.0-showcases/pc-twitter2-midscene_report.html) **Prompt:** Open Google and query San Jose tomorrow weather temperature View the full report for this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/weather-computer-2026-01-14_11-26-38-9592ecf5.html) **Windows** **Prompt:** Open Sauce Demo e-commerce site, login and add items to cart View the full report for this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/shop-computer-2026-01-14_11-57-36-f8411b8f.html) **Linux** **Prompt:** Open TodoMVC, add multiple tasks and filter them View the full report for this task: [report.html](https://lf3-static.bytednsdoc.com/obj/eden-cn/nupipfups/Midscene/todo-computer-2026-01-13_15-40-37-6f45fb0f.html) ### In-vehicle systems x robotic arms (community showcase) Some community developers have successfully built on Midscene's capability to [integrate with any interface](/integrate-with-any-interface.md), extending it with a robotic arm plus vision and voice models for in-vehicle large-screen testing scenarios. ## E2E Test Scenarios ### Dongchedi App: Doubao Seed 2.1 Turbo The following five test cases use `doubao-seed-2-1-turbo-260628` to test the ranking filters in the Android Dongchedi app on a device with a 720 × 1600 resolution. #### Case 1: Sales ranking test - **Test scope:** Verify that the sales ranking correctly applies the combined filters for sedan, the month before last, fuel, and a preset CNY 180,000–250,000 price range, and displays the corresponding results - **Steps:** 8 / 16 (script / model calls) - **Tokens:** Input 126,935 (89,760 cached) / output 3,109 - **Cost:** $0.0312 - **Test report:** [View report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/dongchedi/01-sales-sedan-fuel-preset-price.html) #### Case 2: Sales ranking combined-filter test - **Test scope:** Verify that the sales ranking correctly applies the combined filters for SUV, the previous month, and plug-in hybrid, and displays the corresponding results - **Steps:** 4 / 14 (script / model calls) - **Tokens:** Input 137,310 (100,000 cached) / output 2,472 - **Cost:** $0.0307 - **Test report:** [View report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/dongchedi/02-sales-suv-hybrid.html) #### Case 3: New-energy ranking test - **Test scope:** Verify that the new-energy ranking correctly applies the combined filters for SUV, the last six months, battery electric, and a preset CNY 180,000–250,000 price range, and displays the corresponding results - **Steps:** 8 / 18 (script / model calls) - **Tokens:** Input 149,996 (103,896 cached) / output 6,279 - **Cost:** $0.0434 - **Test report:** [View report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/dongchedi/03-new-energy-suv-pure-electric-preset-price.html) #### Case 4: Price-drop ranking test - **Test scope:** Verify that the price-drop ranking correctly applies the combined filters for MPV, the last year, new energy, and a custom CNY 150,000–300,000 price range, and displays the corresponding results - **Steps:** 13 / 29 (script / model calls) - **Tokens:** Input 253,991 (174,176 cached) / output 8,203 - **Cost:** $0.0687 - **Test report:** [View report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/dongchedi/04-price-drop-mpv-new-energy-custom-price.html) #### Case 5: Ranking switch and filter reset test - **Test scope:** Verify that switching from the sales ranking to the new-energy ranking resets dependent filters correctly, and that subsequent filtering and reset-to-default behavior work as expected - **Steps:** 16 / 28 (script / model calls) - **Tokens:** Input 217,283 (151,848 cached) / output 5,688 - **Cost:** $0.0548 - **Test report:** [View report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/dongchedi/05-switch-and-reset.html) :::info Doubao pricing assumptions Pricing was checked on September 3, 2026, and Doubao costs use [Volcengine's official pricing](https://ark.volcengine.com/region:cn-beijing/model/detail?name=doubao-seed-2-1-turbo). Standard inference rates are CNY `¥3 / M input tokens`, `¥0.6 / M cached input tokens`, and `¥15 / M output tokens`; USD costs use `¥6.8 / $1`. The five cases cost approximately `¥1.5556 ($0.2288)` in total and average `¥0.3111 ($0.0458)` per case. These figures reflect this test run only; actual costs vary with task complexity, cache hit rate, and model pricing. ::: ### Reddit App: Qwen 3.7 Plus The following two test cases use [`qwen/qwen3.7-plus`](https://openrouter.ai/qwen/qwen3.7-plus) to test community search, joining, and post upvoting in the Android Reddit app on a device with a 720 × 1600 resolution. #### Case 1: Search for and join the Midscene community - **Test scope:** Search Reddit for Midscene, open the exact `r/midscene` community, join it if needed, and verify that the account has joined - **Steps:** 7 / 17 (script / model calls) - **Tokens:** Input 147,127 (34,816 cached) / output 3,418 - **Cost:** $0.0425 - **Test report:** [View report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/reddit/01-search-and-join-midscene-community.html) #### Case 2: Upvote the first post in the Midscene community - **Test scope:** Open the exact `r/midscene` community, upvote the first post in its post list if needed, and verify that it is upvoted - **Steps:** 6 / 12 (script / model calls) - **Tokens:** Input 103,231 (8,704 cached) / output 3,142 - **Cost:** $0.0348 - **Test report:** [View report](https://lf3-static.bytednsdoc.com/obj/eden-cn/luljzkpt/ljhwZthlaukjlkulzlp/showcases/reddit/02-upvote-first-post-in-midscene-community.html) :::info Qwen pricing assumptions Pricing was checked on August 21, 2026 and sourced from [OpenRouter](https://openrouter.ai/qwen/qwen3.7-plus). Input tokens are priced at `$0.32 / M tokens`, cache reads at `$0.064 / M tokens`, and output tokens at `$1.28 / M tokens`. The two cases cost approximately `$0.0774` in total and average `$0.0387` per case. These figures reflect this test run only; actual costs vary with task complexity, cache hit rate, and model pricing. ::: --- url: /skills.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Control any platform with Skills [Agent Skills](https://github.com/anthropics/skills) are a format for extending AI coding agents with specialized capabilities. Midscene provides Agent Skills that let AI coding tools (like Claude Code, Cline, etc.) drive UI automation through CLI commands. Skills work by running CLI commands directly in the terminal. The AI agent acts as the brain: it takes screenshots, analyzes the UI, and decides which actions to perform next. ## Supported platforms | Skill | Package | CLI command | Description | | --------------------------- | -------------------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | Browser Automation | `@midscene/web` | `npx @midscene/web` | Browser automation with three modes: default Puppeteer headless, `--bridge` to use your own Chrome, `--cdp <ws-endpoint>` to connect via CDP | | Desktop Computer Automation | `@midscene/computer` | `npx @midscene/computer` | macOS, Windows, Linux desktop control | | Android Device Automation | `@midscene/android` | `npx @midscene/android` | Android device control via ADB | | iOS Device Automation | `@midscene/ios` | `npx @midscene/ios` | iOS device control via WebDriverAgent | | HarmonyOS Device Automation | `@midscene/harmony` | `npx @midscene/harmony` | HarmonyOS device control via HDC | ## Installation Make sure [Node.js](https://nodejs.org) is installed, then run: ```bash # General installation npx skills add web-infra-dev/midscene-skills # Claude Code npx skills add web-infra-dev/midscene-skills -a claude-code # OpenClaw npx skills add web-infra-dev/midscene-skills -a openclaw ``` Skills repository: [github.com/web-infra-dev/midscene-skills](https://github.com/web-infra-dev/midscene-skills) ## Model configuration Midscene skills require a multimodal model with strong UI localization. Configure the following environment variables — either as system environment variables or in a `.env` file in the current working directory (Midscene loads `.env` automatically): ```bash MIDSCENE_MODEL_API_KEY="your-api-key" MIDSCENE_MODEL_NAME="model-name" MIDSCENE_MODEL_BASE_URL="https://..." MIDSCENE_MODEL_FAMILY="family-identifier" ``` For supported models and configuration details, see [Use a model API key](/model-api-setup.md). ## Use skills Once installed, just describe the task in natural language to your AI coding agent. It picks the right Skill, runs the CLI, reads the screenshots, and decides what to do next — for example: > Open the photo app and tell me the first photo in the album. ## Example: Coding Agent self-verifies after writing code In this example, we ask Claude Code to develop an Electron Todo app, and after writing the code, it uses the `desktop-computer-automation` Skill to launch the app, interact with the UI, and take screenshots to verify the feature works as expected — no manual intervention or test scripts needed. **Prompt:** ``` Build an Electron Todo app with add, toggle, and delete functionality. After development, launch the app and verify with desktop automation: add 3 todos, check one off, delete one, and take a screenshot to confirm the final state is correct. ``` The coding agent autonomously completes the entire workflow: write the Todo component → launch the Electron app → connect to the desktop → take screenshots to understand the UI → interact via natural language → take screenshots to verify results. The developer only describes the intent, and Skills give the agent the ability to "see the screen and move the mouse", letting it verify its own code just like a human would. ## More use cases Skills go beyond local desktop testing. By combining different Skills, you can cover a wide range of automation scenarios: - **Desktop app testing** — Verify functionality of Electron, Qt, WPF and other desktop applications - **Remote computer control** — Operate applications on remote machines via remote desktop connections for remote ops and debugging - **Mobile app testing** — Use `@midscene/android` and `@midscene/ios` Skills to test mobile apps on real devices or simulators - **Cross-app workflows** — Chain operations across multiple apps, e.g. fetch data from browser → paste into Excel → take screenshot and send to Slack - **CI/CD integration** — Run desktop automation in headless mode on Linux CI via Xvfb, no physical display needed - **Daily task automation** — Batch form filling, scheduled screenshot monitoring, automatic file organization, etc. ## Browser connection options (optional) In default Puppeteer mode, you can override the default `1440x800` viewport with `--viewport-width <width>` and `--viewport-height <height>`. These flags are only supported in default Puppeteer mode, not in `--bridge` or `--cdp` mode. In CDP mode, use a separate `--extra-http-header 'Name:Value'` option for each HTTP header added to page requests. Repeat the option on every separate CLI command that may issue requests because each command creates a new CDP session: ```bash npx @midscene/web connect \ --cdp ws://127.0.0.1:9222/devtools/browser \ --extra-http-header 'x-use-ppe:1' \ --extra-http-header 'x-tt-env:ppe_example' \ --url https://example.com npx @midscene/web act \ --cdp ws://127.0.0.1:9222/devtools/browser \ --extra-http-header 'x-use-ppe:1' \ --extra-http-header 'x-tt-env:ppe_example' \ --prompt "click the button" ``` The headers are applied before `connect --url` navigates, so the initial document request includes them. Avoid putting sensitive authentication values directly in shell history. If Chrome is installed in a non-standard location, set `MIDSCENE_CHROME_PATH` to the Chrome executable path. `MIDSCENE_MCP_CHROME_PATH` is still accepted as a temporary migration alias. ## Switch browser tabs Use `tabs` to list open tabs and `switch-tab --id <id>` to select one. Save the original tab ID before clicking a link that opens a new tab, then list tabs again to find the new tab: ```bash npx @midscene/web tabs # After opening the new tab: npx @midscene/web tabs npx @midscene/web switch-tab --id <new-tab-id> npx @midscene/web take_screenshot # Return to the original tab after working in the new tab: npx @midscene/web switch-tab --id <original-tab-id> ``` `tabs` returns a JSON array with `id`, `title`, `url`, and `active`. `active` identifies the page controlled by Midscene. Switching selects an existing tab without navigating or reloading it, preserving page state. Missing or closed IDs produce an error. If a site opens a tab asynchronously, run `tabs` again after it appears. Keep the connection mode consistent across commands. In default Puppeteer and CDP modes, subsequent commands use the selected tab. These modes preserve newly opened tabs without switching to them automatically. In CDP mode, pass `--cdp <endpoint>` on each command, or set `MIDSCENE_CDP_ENDPOINT` and pass `--cdp`. In Bridge mode, pass `--bridge` on each command and use an updated Midscene Chrome extension. Switching activates the selected tab in the current Chrome window. Subsequent commands connect to the foreground tab, so manually switching tabs also changes which page the next command controls. `disconnect` releases the connection. In default Puppeteer mode, `close` closes the entire browser, including all tabs. ## More Please refer to the [Skills Repository](https://github.com/web-infra-dev/midscene-skills) for more details. --- url: /yaml-script-runner.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # YAML script runner :::info Compatibility remains; migrate to Midscene Test for new work “Legacy YAML” specifically means the YAML automation protocol provided by `@midscene/cli`: a workflow uses top-level `tasks`, each task contains `flow`, platform and Agent runtime configuration commonly lives in YAML, and execution uses the `midscene` command or YAML batch configuration with fields such as `files`, `setup`, and `concurrent`. The legacy path is now in maintenance mode. Existing projects remain compatible and necessary issues will be fixed, but it will not receive new syntax, capabilities, configuration fields, or CLI options. Existing cases, batch configuration, directory layout, and the `midscene` command can remain unchanged. Upgraded versions execute them through the shared kernel and generate the new Test report page. Use Midscene Test for new projects, new cases, and future capability development. Run legacy files and YAML batch configuration with `midscene`; run native `cases/steps` files and TypeScript project configuration with `midscene-test`. The two formats may live in separate directories in one repository, but a file or command invocation must not mix them. Start with [Midscene Test overview](/midscene-test/overview.md), then follow [Migrate to Midscene Test](/migrate-to-midscene-test.md) to convert fields and switch commands. ::: Midscene defines a YAML-based scripting format so you can quickly author automation scripts, then run them from the command line without extra setup. For more details on YAML scripts, see [Automate with scripts in YAML](/automate-with-scripts-in-yaml.md). For example, you can write a YAML script like this: ```yaml page: url: https://www.bing.com tasks: - name: Search for weather flow: - ai: Search for "today's weather" - sleep: 3000 - aiAssert: The results show weather information ``` Run it with one command: ```bash midscene ./bing-search.yaml ``` The CLI prints execution progress and generates a visual report when it finishes, while keeping setup simple. ## Configure environment variables with `.env` The Midscene CLI uses [dotenv](https://www.npmjs.com/package/dotenv) to load a `.env` file from the directory where you run the tool. Create a `.env` file and add: ```ini filename=.env MIDSCENE_MODEL_BASE_URL="replace with your model service URL/v1" MIDSCENE_MODEL_API_KEY="replace with your API Key" MIDSCENE_MODEL_NAME="replace with your model name" MIDSCENE_MODEL_FAMILY="replace with your model family" ``` For supported models and complete setup examples, see [Use a model API key](/model-api-setup.md). Notes: - The file is optional; you can also set global environment variables instead. - Do not add an `export` prefix—this is how dotenv expects values. - Place `.env` in the directory where you run the tool, not necessarily next to the YAML file. - These values do **not** override existing global environment variables unless you enable `--dotenv-override` (see below). - Use `--dotenv-debug` if you need to debug how environment variables load. ## Get started ### Install the CLI Before installing the CLI, make sure the terminal that runs `midscene` uses Node.js `20.19+`, `22.12+`, or `24+`. Some CLI execution paths use the Rstest/Rspack toolchain, which rejects older Node 20 patch versions such as `20.17.0`. If you see an `Unsupported Node.js version` message from Rspack, upgrade Node.js and reinstall the global CLI or project dependencies. Install `@midscene/cli` globally (recommended for first-time users): ```bash npm i -g @midscene/cli ``` Or install it per project: ```bash npm i @midscene/cli --save-dev ``` ### Write your first script Create `bing-search.yaml` to drive a web browser: ```yaml page: url: https://www.bing.com tasks: - name: Search for weather flow: - ai: Search for "today's weather" - sleep: 3000 - aiAssert: The results show weather information ``` Drive an Android device connected over adb: ```yaml android: deviceId: s4ey59 # find the device id with `adb devices` tasks: - name: Maps Navigation flow: - ai: Open the Maps app - ai: Input 'West Lake, Hangzhou' in the search bar, and click the search button - ai: Click the first search result, enter the details page - ai: Click "Directions" button, enter the route planning page - ai: Click "Start" button to start navigation ``` Or drive an iOS device with WebDriverAgent configured: ```yaml ios: wdaPort: 8100 tasks: - name: Change System Settings flow: - ai: Open the Settings app - ai: Tap "Display & Brightness" - ai: Turn on "Dark Mode" - aiAssert: Dark Mode is enabled ``` ### Run the script ```bash midscene ./bing-search.yaml # If Midscene is installed in your project npx midscene ./bing-search.yaml ``` The CLI prints execution progress and generates a visual report when it finishes. ## Advanced usage of the command-line tool ### Use environment variables in `.yaml` Reference environment variables in your scripts with `${variable-name}`. Environment-variable interpolation is applied before YAML task execution, including task strings. ```ini filename=.env topic=weather today ``` ```yaml # ... - ai: type ${topic} in input box # ... ``` ### Run multiple scripts `@midscene/cli` supports glob patterns to batch-execute scripts, which is a shorthand for the `--files` argument. ```bash # Run a single script midscene ./bing-search.yaml # Use a glob pattern to run all matching scripts midscene './scripts/**/*.yaml' ``` ### Analyze command-line output After execution, the output directory contains: - A JSON summary specified by `--summary` (defaults to `index.json`) with execution status and statistics for all scripts. - Individual execution results for each YAML file (JSON). - Visual reports for each script (HTML). ### Run in headed mode > Web page scenarios only Headed mode opens the browser window. By default, scripts run headless. ```bash # Run in headed mode midscene /path/to/yaml --headed # Run in headed mode and keep the window after finishing midscene /path/to/yaml --keep-window ``` ### Use CDP connection mode > `web` scenarios only CDP mode lets YAML scripts connect to an existing browser instance via Chrome DevTools Protocol, without launching a new browser. This is useful for reusing an existing browser session, connecting to remote browsers, or cloud browser services. Set `cdpEndpoint` in the `page` section: ```diff page: url: https://www.bing.com + cdpEndpoint: ws://localhost:9222/devtools/browser ``` :::info CDP mode and bridge mode are mutually exclusive. In CDP mode, Midscene will only disconnect from the browser, not close it. ::: ### Use bridge mode After [Chrome Bridge environment setup](/bridge-mode.md), select the current tab or a new tab in YAML. See [Chrome Bridge in YAML](/automate-with-scripts-in-yaml.md#chrome-bridge) for fields, examples, and unsupported options. ### Run YAML scripts with JavaScript Call the Agent's [`runYaml`](/reference.md#runyaml) method to execute YAML from JavaScript. This runs only the `tasks` section of the script. ## Command-line options The CLI provides parameters to control how scripts run: - `--files <file1> <file2> ...`: List of script files. Executes in order, sequentially by default (`--concurrent` is `1`), or concurrently when `--concurrent` is set. Supports [glob](https://www.npmjs.com/package/glob) patterns; when a glob pattern or directory matches multiple files, matched files are added to the execution list in lexicographic path order. - `--setup <file>`: A setup script that runs before the main `--files` for any supported target. If all setup attempts fail, the batch is aborted and the main scripts are reported as not executed. Puppeteer Web setup requires `--share-browser-context`; each retry then starts with a clean BrowserContext and Page, and the successful context is shared with the main scripts. Every YAML script runs in its own Page by default. Add `--reuse-page` to continue on the setup Page in a sequential batch. Bridge mode and non-Web targets must omit these sharing options; their retries create a new player and Agent but do not reset the underlying browser, device, desktop, or external interface state. - `--concurrent <number>`: Number of concurrent executions. Default `1`. - `--continue-on-error`: Continue running remaining scripts even if one fails. Default off. - `--retry <number>`: Number of extra attempts for a failed script. Only failed scripts are retried, which helps with unstable networks or unstable model output. Default `0`. Puppeteer Web setup retries use a clean BrowserContext and Page, while main-script retries preserve the successful setup context. Other targets create a new player and Agent for each retry without resetting their underlying environment. - `--share-browser-context`: Share one Puppeteer BrowserContext (cookies, same-origin `localStorage`, etc.) across scripts while giving every YAML script an independent Page. Page-scoped state such as `sessionStorage`, the DOM, URL, and `window.name` is not shared, even with `--concurrent 1`. Every setup and main script in the batch must use a Puppeteer Web target. Bridge mode and non-Web targets are not supported. Because the browser is created or connected only once, put browser-level options (`cdpEndpoint`, `chromeArgs`, `acceptInsecureCerts`, and `downloadPath`) in the batch config's global Web target, not in an individual setup or main script. Default off. - `--reuse-page`: Reuse the same Puppeteer Page object across scripts. This preserves page-scoped state such as `sessionStorage` and `window.name`. It requires `--share-browser-context` and `--concurrent 1`. Default off. - `--summary <filename>`: Path for the JSON summary report. - `--headed`: Run in a headed browser instead of headless. - `--keep-window`: Keep the browser window after execution; enables `--headed` automatically. - `--config <filename>`: Config file whose values become defaults for CLI arguments. - `--web.userAgent <ua>`: Override `web.userAgent` for all scripts. - `--web.viewportWidth <width>`: Override `web.viewportWidth` for all scripts. - `--web.viewportHeight <height>`: Override `web.viewportHeight` for all scripts. - `--android.deviceId <device-id>`: Override `android.deviceId` for all scripts. - `--harmony.deviceId <device-id>`: Override `harmony.deviceId` for all scripts. - `--ios.wdaPort <port>`: Override `ios.wdaPort` for all scripts. - `--ios.wdaHost <host>`: Override `ios.wdaHost` for all scripts. - `--computer.displayId <display-id>`: Override `computer.displayId` for all scripts. - `--dotenv-debug`: Enable dotenv debug logs. Default off. - `--dotenv-override`: Allow dotenv to override global environment variables. Default off. Examples: Use `--files` to specify execution order: ```bash midscene --files ./login.yaml ./buy/*.yaml ./checkout.yaml ``` Run multiple independent search scripts with a concurrency of 4 and continue when errors occur: ```bash midscene --files './scripts/search-*.yaml' --concurrent 4 --continue-on-error ``` ### Write command-line arguments in a file You can place arguments in a YAML config file and reference it with `--config`. Command-line arguments take priority over the config file. A config file can also contain one global target section: `page`, `browser`, `web`, the deprecated `target`, `android`, `ios`, `harmony`, `computer`, or `interface`. Its fields are deep-merged over the corresponding target section in every script. The complete priority order is command-line target options, then the config file's target section, then each script's target section. Fields that are not overridden are preserved. Each resulting script must still resolve to exactly one target type. ```yaml files: - './scripts/search-iphone.yaml' - './scripts/search-laptop.yaml' - './scripts/search-headphones.yaml' - './scripts/search-camera.yaml' concurrent: 4 continueOnError: true retry: 2 ``` For example, this config selects one HarmonyOS device for every matched script while allowing individual scripts to keep other HarmonyOS settings that are not overridden: ```yaml files: - './scripts/harmony/*.yaml' harmony: deviceId: '127.0.0.1:5555' autoDismissKeyboard: true ``` Run with: ```bash midscene --config ./config.yaml ``` Set `concurrent: 1` (the default) when scripts must run in the exact order of the `files` list. With a value greater than `1`, execution order is unspecified; scripts must not depend on another script's start or completion order. #### Run a setup before parallel scripts When several independent Puppeteer Web scripts all depend on the same prerequisite (for example a login), put the prerequisite under `setup`. The setup script runs before the main `files`; once it succeeds, the main scripts run with the configured concurrency. Set `shareBrowserContext: true` so the successful setup attempt's browser context, including cookies and same-origin `localStorage`, is carried over. Every script receives an independent Page, so the setup Page's `sessionStorage`, DOM, URL, `window.name`, and other page-scoped state are not copied into main Pages. Every script in this shared batch must use a Puppeteer Web target; bridge mode is not supported. The shared Browser is launched or connected from the batch config once. Configure `cdpEndpoint`, `chromeArgs`, `acceptInsecureCerts`, and `downloadPath` in the batch config's global Web target. Defining any of these browser-level options in an individual setup or main script is rejected because it cannot be applied to the already-created shared Browser. ```yaml setup: ./scripts/login.yaml files: - ./scripts/search.yaml - ./scripts/report.yaml - ./scripts/settings.yaml shareBrowserContext: true concurrent: 3 retry: 2 ``` `retry` is the number of extra attempts, so `retry: 2` allows up to three attempts. Every setup retry gets a new BrowserContext and Page, preventing cookies, local storage, navigation state, and other browser-side effects from a failed attempt from leaking into the next one. After setup succeeds, its context is shared with the main scripts. A failed main script is retried in that same context so the successful setup state is preserved. If all setup attempts fail, the batch is aborted and the main scripts are reported as not executed. :::warning Page-scoped state is not shared `shareBrowserContext` follows browser-native storage boundaries: it does not copy or synchronize `sessionStorage` between Pages. If setup establishes authentication only in `sessionStorage`, the main scripts will not inherit that login. Prefer cookies, same-origin `localStorage`, or backend state for prerequisites that must be visible to multiple scripts. When scripts run concurrently, shared-state writes can race, so coordinate them explicitly. ::: For a sequential workflow that must keep using the Page created for setup, enable page reuse explicitly: ```yaml setup: ./scripts/login.yaml files: - ./scripts/web_format.yaml shareBrowserContext: true reusePage: true concurrent: 1 ``` The main script still applies its own Web target configuration and navigates to its configured `url`, but it does so in the same Page object created for setup. In `browser` mode, pages opened later by popups or new-tab actions do not replace this reusable Page. `setup` also works with bridge mode, Android, iOS, HarmonyOS, Computer, and custom Interface targets. Omit `shareBrowserContext` for those targets. A retry creates a new script player and Agent, but the underlying browser profile, device, desktop session, or custom interface is not automatically reset. If a clean retry environment is required, make the setup script restore that environment explicitly. ## FAQ **How can I export cookies from Chrome as JSON?** Use this [Chrome extension](https://chromewebstore.google.com/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc) to export cookies. **How can I view dotenv debug logs?** Use the `--dotenv-debug` flag: ```bash midscene /path/to/yaml --dotenv-debug=true ``` --- url: /get-started/web-playground-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Web · Playground · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Web** with **Playground** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install the Chrome extension 1. Install Midscene from the Chrome Web Store: [Install the Midscene extension from the Chrome Web Store](https://chromewebstore.google.com/detail/midscene/gbldofcpkknbggpkmbdaefngejllnief) 2. Open **Midscene** from the Chrome extensions list. The Midscene sidebar appears on the right side of the browser. If you cannot access the Chrome Web Store, see [Can I install the Chrome extension manually?](/platforms/web.md#chrome-extension-faq) ## Sign in with your ChatGPT subscription 1. In the Midscene sidebar, click the settings icon to open the model configuration dialog, then click **Use your ChatGPT plan** and follow the on-screen instructions to sign in and authorize plan usage. 2. Paste the following configuration into the same dialog: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` 3. Click **Verify** to test the connection. For failed checks, see [Model advanced configuration and debugging](/model-config.md#verify-model-connectivity). Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Run an action and verify the result Open [TodoMVC](https://todomvc.com/examples/react/dist/#/) in the current tab and keep the page visible. 1. Select `aiAct` in the side panel, enter the following instruction, and run it: ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, inspect the failed step and error message. For model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity) and [Common configuration errors](/model-config.md#common-configuration-errors). For extension errors when accessing a page or Ollama, see the [Web FAQ](/platforms/web.md#chrome-extension-faq). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/web-test-chatgpt.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Playwright Test**: [Call Midscene from your Playwright tests](/get-started/web-sdk-chatgpt.md) with the same model. - **Control this browser from scripts**: [Chrome Bridge](/bridge-mode.md) lets Node.js scripts control your desktop Chrome and reuse its login sessions and cookies. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/web-test-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Web · Midscene Test · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Web** with **Midscene Test** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform web \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then, in the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Leave `MIDSCENE_MODEL_BASE_URL` and `MIDSCENE_MODEL_API_KEY` empty. Set `MIDSCENE_MODEL_NAME` and `MIDSCENE_MODEL_FAMILY`, and add `MIDSCENE_MODEL_AUTH_MODE`: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). Install Chromium for Playwright: ```bash pnpm exec playwright install chromium ``` ## Run the example and inspect the report The example opens React TodoMVC in Chromium, seeds three todos, and changes them with `aiAct` and `aiAssert`. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own site**: In `cases/todo.yaml`, replace the TodoMVC setup in `beforeEach` with a `gotoUrl` Node for your URL, then describe the steps with `aiAct` and `aiAssert`. See [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md). - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/web-playground-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Web · Playground · Model API Key {#get-started} These are the setup steps for Midscene on **Web** with **Playground** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install the Chrome extension 1. Install Midscene from the Chrome Web Store: [Install the Midscene extension from the Chrome Web Store](https://chromewebstore.google.com/detail/midscene/gbldofcpkknbggpkmbdaefngejllnief) 2. Open **Midscene** from the Chrome extensions list. The Midscene sidebar appears on the right side of the browser. If you cannot access the Chrome Web Store, see [Can I install the Chrome extension manually?](/platforms/web.md#chrome-extension-faq) ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). In the Midscene sidebar, click the settings icon, paste the configuration, and save. ## Run an action and verify the result Open [TodoMVC](https://todomvc.com/examples/react/dist/#/) in the current tab and keep the page visible. 1. Select `aiAct` in the side panel, enter the following instruction, and run it: ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, inspect the failed step and error message. For model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity) and [Common configuration errors](/model-config.md#common-configuration-errors). For extension errors when accessing a page or Ollama, see the [Web FAQ](/platforms/web.md#chrome-extension-faq). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/web-test-api-key.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Playwright Test**: [Call Midscene from your Playwright tests](/get-started/web-sdk-api-key.md) with the same model. - **Control this browser from scripts**: [Chrome Bridge](/bridge-mode.md) lets Node.js scripts control your desktop Chrome and reuse its login sessions and cookies. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/web-sdk-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Web · Playwright Test · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Web** with **Playwright Test** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then write these lines to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). ### Install dependencies and configure Playwright If the directory does not have a Playwright Test project yet, add Playwright Test and its Chromium browser first: ```bash pnpm add -D @playwright/test pnpm exec playwright install chromium ``` ```sh [npm] npm install @midscene/web dotenv --save-dev ``` ```sh [yarn] yarn add @midscene/web dotenv --save-dev ``` ```sh [pnpm] pnpm add @midscene/web dotenv --save-dev ``` ```sh [bun] bun add @midscene/web dotenv --save-dev ``` ```sh [deno] deno add npm:@midscene/web npm:dotenv --save-dev ``` Add the following configuration to `playwright.config.ts` (create the file if your project does not have one yet), while keeping your project's other settings and reporters: ```typescript title="playwright.config.ts" import 'dotenv/config'; import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './e2e', timeout: 90_000, use: { browserName: 'chromium' }, reporter: [ ['list'], ['@midscene/web/playwright-reporter'], ], }); ``` `dotenv/config` loads model settings from the project's `.env` file (settings in the Chrome extension Playground are not automatically shared with test runs). Because model calls take longer than standard DOM operations, increase `timeout` as needed for your tests. ### Create a fixture Create `e2e/fixture.ts` to extend Playwright's `test` with `PlaywrightAiFixture`: ```typescript title="e2e/fixture.ts" import { test as base } from '@playwright/test'; import { PlaywrightAiFixture, type PlayWrightAiFixtureType, } from '@midscene/web/playwright'; export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture(), ); ``` In tests that use Midscene, import `test` from `./fixture` while continuing to import `expect` from `@playwright/test`. ## Write a test ```typescript title="e2e/todo.spec.ts" import { expect } from '@playwright/test'; import { test } from './fixture'; test('add a todo', async ({ page, aiAct, aiAssert }) => { await page.goto('https://todomvc.com/examples/react/dist/'); await expect(page).toHaveTitle(/TodoMVC/); await aiAct('Add a todo named Try Midscene'); await aiAssert('The todo list contains Try Midscene'); }); ``` You can combine Playwright's `page` and `expect` with Midscene's AI methods in the same test. In this example, Playwright opens the page and checks its title, while Midscene adds a todo item and asserts the result on the page. Beyond `aiAct` and `aiAssert`, the fixture also provides `aiTap`, `aiInput`, `aiQuery`, `aiWaitFor`, and more; see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report Run the test from the project directory: ```bash pnpm exec playwright test e2e/todo.spec.ts ``` After the test finishes, the Midscene reporter prints the report path in the terminal (saved under `midscene_run/report/` by default). Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Configure the fixture and reporter**: [Further configuration](/integrate-with-playwright.md#further-configuration) covers Agent options, working with a specific page, and report options. --- url: /get-started/web-test-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Web · Midscene Test · Model API Key {#get-started} These are the setup steps for Midscene on **Web** with **Midscene Test** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform web \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Configure a model In the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Fill in the four `MIDSCENE_MODEL_*` values in `.env` with this configuration. ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). Install Chromium for Playwright: ```bash pnpm exec playwright install chromium ``` ## Run the example and inspect the report The example opens React TodoMVC in Chromium, seeds three todos, and changes them with `aiAct` and `aiAssert`. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own site**: In `cases/todo.yaml`, replace the TodoMVC setup in `beforeEach` with a `gotoUrl` Node for your URL, then describe the steps with `aiAct` and `aiAssert`. See [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md). - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/web-sdk-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Web · Playwright Test · Model API Key {#get-started} These are the setup steps for Midscene on **Web** with **Playwright Test** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Write the four values to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). ### Install dependencies and configure Playwright If the directory does not have a Playwright Test project yet, add Playwright Test and its Chromium browser first: ```bash pnpm add -D @playwright/test pnpm exec playwright install chromium ``` ```sh [npm] npm install @midscene/web dotenv --save-dev ``` ```sh [yarn] yarn add @midscene/web dotenv --save-dev ``` ```sh [pnpm] pnpm add @midscene/web dotenv --save-dev ``` ```sh [bun] bun add @midscene/web dotenv --save-dev ``` ```sh [deno] deno add npm:@midscene/web npm:dotenv --save-dev ``` Add the following configuration to `playwright.config.ts` (create the file if your project does not have one yet), while keeping your project's other settings and reporters: ```typescript title="playwright.config.ts" import 'dotenv/config'; import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './e2e', timeout: 90_000, use: { browserName: 'chromium' }, reporter: [ ['list'], ['@midscene/web/playwright-reporter'], ], }); ``` `dotenv/config` loads model settings from the project's `.env` file (settings in the Chrome extension Playground are not automatically shared with test runs). Because model calls take longer than standard DOM operations, increase `timeout` as needed for your tests. ### Create a fixture Create `e2e/fixture.ts` to extend Playwright's `test` with `PlaywrightAiFixture`: ```typescript title="e2e/fixture.ts" import { test as base } from '@playwright/test'; import { PlaywrightAiFixture, type PlayWrightAiFixtureType, } from '@midscene/web/playwright'; export const test = base.extend<PlayWrightAiFixtureType>( PlaywrightAiFixture(), ); ``` In tests that use Midscene, import `test` from `./fixture` while continuing to import `expect` from `@playwright/test`. ## Write a test ```typescript title="e2e/todo.spec.ts" import { expect } from '@playwright/test'; import { test } from './fixture'; test('add a todo', async ({ page, aiAct, aiAssert }) => { await page.goto('https://todomvc.com/examples/react/dist/'); await expect(page).toHaveTitle(/TodoMVC/); await aiAct('Add a todo named Try Midscene'); await aiAssert('The todo list contains Try Midscene'); }); ``` You can combine Playwright's `page` and `expect` with Midscene's AI methods in the same test. In this example, Playwright opens the page and checks its title, while Midscene adds a todo item and asserts the result on the page. Beyond `aiAct` and `aiAssert`, the fixture also provides `aiTap`, `aiInput`, `aiQuery`, `aiWaitFor`, and more; see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report Run the test from the project directory: ```bash pnpm exec playwright test e2e/todo.spec.ts ``` After the test finishes, the Midscene reporter prints the report path in the terminal (saved under `midscene_run/report/` by default). Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Configure the fixture and reporter**: [Further configuration](/integrate-with-playwright.md#further-configuration) covers Agent options, working with a specific page, and report options. --- url: /get-started/android-playground-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Android · Playground · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Android** with **Playground** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Connect the Android device Midscene uses `adb` on your computer to communicate with the target Android device over either USB or wireless `adb`. If `adb` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install adb - Install `adb` via [Android Studio](https://developer.android.com/studio) or the standalone [Android command-line tools](https://developer.android.com/studio#command-line-tools-only). - Run the following command to verify the installation: ```bash adb --version ``` Output similar to the following confirms a working installation: ```log Android Debug Bridge version 1.0.41 Version 34.0.4-10411341 Installed as /usr/local/bin/adb Running on Darwin 24.3.0 (arm64) ``` - Configure the `ANDROID_HOME` environment variable as described in [Android environment variables](https://developer.android.com/tools/variables), then check that it takes effect: ```bash echo $ANDROID_HOME ``` The output should point to your local Android SDK directory, for example: ```log /Users/your_username/Library/Android/sdk ``` ### Enable debugging and connect the device The steps below use a USB connection as an example. If your device is already connected over wireless `adb`, you can keep using that connection. 1. In your phone's **Developer options**, enable **USB debugging** (and **USB debugging (Security settings)** if available, so Midscene can inject touch events). 2. Connect the phone to your computer using a USB cable that supports data transfer. 3. Keep the phone unlocked and accept the **Allow USB debugging** prompt on the screen. ![android usb debug](/images/android-usb-debug-en.png) ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash adb devices -l ``` When the device status shows `device`, the connection is ready: ```log List of devices attached s4ey59 device usb:34603008X product:cezanne model:M2006J device:cezan transport_id:3 ``` If multiple devices are connected, note the device ID in the first column (such as `s4ey59` above) so you can select the target device in Playground or your project configuration. If the target device does not appear with the `device` status, check the following: - **Empty list**: For USB, check the data cable (ensure it is not charge-only), USB connection mode, and **USB debugging** toggle; for wireless `adb`, check the network and `adb connect` status. - **`unauthorized`**: Unlock the phone screen and accept the **Allow USB debugging** prompt on the device. - **`offline`**: Reconnect the USB cable or wireless `adb` session, and restart `adb` if needed. Proceed only after the status shows `device`. ## Sign in with your ChatGPT subscription The login command needs Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. Check that `node -v` works in your terminal. If pnpm is not installed yet, run `npm install -g pnpm`. First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Playground reads the credentials saved by this command. Keep the following lines at hand. You will paste them into Playground settings in a later step: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Launch Playground Make sure Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`) is installed and `node -v` works in your terminal. The command below uses pnpm. If it is not installed yet, run `npm install -g pnpm`. 1. Start the Android Playground CLI: ```bash pnpm dlx @midscene/android-playground ``` 2. In the Playground window that opens, click the gear icon in the top-right corner, paste your model configuration, and save. ![](/images/android-set-env.png) 3. If your browser does not open automatically, visit the local Playground URL printed in the terminal, and keep the terminal process running. 4. In the connection panel on the left, select your target **ADB device** and create the Agent (if multiple devices are connected, match the device ID against `adb devices -l`). 5. Confirm that the preview area displays your phone's current screen. If no screen appears, check the `adb` connection and screenshot permissions first. ## Run an action and verify the result On your Android device, open the browser app and complete any first-run prompts. Enter the following TodoMVC URL in the address bar: ```text https://todomvc.com/examples/react/dist/#/ ``` Keep the device unlocked with the browser in the foreground. 1. In Playground, select `aiAct`, enter the following instruction, and run it: ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. At this point, device connectivity, screen capture, touch input, and model calls have all been verified together. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, check the failed step and error message: for missing screenshots or unresponsive touch input, see the [FAQ](/platforms/android.md#faq); for model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity). After verification, delete the "Try Midscene" item in TodoMVC. If you plan to run the Midscene Test Android example next, switch to the **All** filter and make sure the list is completely empty (including completed items), as the example template checks for an empty list before running and does not overwrite existing items. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/android-test-chatgpt.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Rstest or Vitest**: [Call Midscene from your Vitest tests](/get-started/android-sdk-chatgpt.md) with the same platform and model. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/android-playground-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Android · Playground · Model API Key {#get-started} These are the setup steps for Midscene on **Android** with **Playground** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Connect the Android device Midscene uses `adb` on your computer to communicate with the target Android device over either USB or wireless `adb`. If `adb` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install adb - Install `adb` via [Android Studio](https://developer.android.com/studio) or the standalone [Android command-line tools](https://developer.android.com/studio#command-line-tools-only). - Run the following command to verify the installation: ```bash adb --version ``` Output similar to the following confirms a working installation: ```log Android Debug Bridge version 1.0.41 Version 34.0.4-10411341 Installed as /usr/local/bin/adb Running on Darwin 24.3.0 (arm64) ``` - Configure the `ANDROID_HOME` environment variable as described in [Android environment variables](https://developer.android.com/tools/variables), then check that it takes effect: ```bash echo $ANDROID_HOME ``` The output should point to your local Android SDK directory, for example: ```log /Users/your_username/Library/Android/sdk ``` ### Enable debugging and connect the device The steps below use a USB connection as an example. If your device is already connected over wireless `adb`, you can keep using that connection. 1. In your phone's **Developer options**, enable **USB debugging** (and **USB debugging (Security settings)** if available, so Midscene can inject touch events). 2. Connect the phone to your computer using a USB cable that supports data transfer. 3. Keep the phone unlocked and accept the **Allow USB debugging** prompt on the screen. ![android usb debug](/images/android-usb-debug-en.png) ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash adb devices -l ``` When the device status shows `device`, the connection is ready: ```log List of devices attached s4ey59 device usb:34603008X product:cezanne model:M2006J device:cezan transport_id:3 ``` If multiple devices are connected, note the device ID in the first column (such as `s4ey59` above) so you can select the target device in Playground or your project configuration. If the target device does not appear with the `device` status, check the following: - **Empty list**: For USB, check the data cable (ensure it is not charge-only), USB connection mode, and **USB debugging** toggle; for wireless `adb`, check the network and `adb connect` status. - **`unauthorized`**: Unlock the phone screen and accept the **Allow USB debugging** prompt on the device. - **`offline`**: Reconnect the USB cable or wireless `adb` session, and restart `adb` if needed. Proceed only after the status shows `device`. ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Keep the configuration at hand. You will paste it into Playground in a later step. ## Launch Playground Make sure Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`) is installed and `node -v` works in your terminal. The command below uses pnpm. If it is not installed yet, run `npm install -g pnpm`. 1. Start the Android Playground CLI: ```bash pnpm dlx @midscene/android-playground ``` 2. In the Playground window that opens, click the gear icon in the top-right corner, paste your model configuration, and save. ![](/images/android-set-env.png) 3. If your browser does not open automatically, visit the local Playground URL printed in the terminal, and keep the terminal process running. 4. In the connection panel on the left, select your target **ADB device** and create the Agent (if multiple devices are connected, match the device ID against `adb devices -l`). 5. Confirm that the preview area displays your phone's current screen. If no screen appears, check the `adb` connection and screenshot permissions first. ## Run an action and verify the result On your Android device, open the browser app and complete any first-run prompts. Enter the following TodoMVC URL in the address bar: ```text https://todomvc.com/examples/react/dist/#/ ``` Keep the device unlocked with the browser in the foreground. 1. In Playground, select `aiAct`, enter the following instruction, and run it: ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. At this point, device connectivity, screen capture, touch input, and model calls have all been verified together. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, check the failed step and error message: for missing screenshots or unresponsive touch input, see the [FAQ](/platforms/android.md#faq); for model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity). After verification, delete the "Try Midscene" item in TodoMVC. If you plan to run the Midscene Test Android example next, switch to the **All** filter and make sure the list is completely empty (including completed items), as the example template checks for an empty list before running and does not overwrite existing items. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/android-test-api-key.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Rstest or Vitest**: [Call Midscene from your Vitest tests](/get-started/android-sdk-api-key.md) with the same platform and model. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/android-test-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Android · Midscene Test · Model API Key {#get-started} These are the setup steps for Midscene on **Android** with **Midscene Test** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the Android device Midscene uses `adb` on your computer to communicate with the target Android device over either USB or wireless `adb`. If `adb` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install adb - Install `adb` via [Android Studio](https://developer.android.com/studio) or the standalone [Android command-line tools](https://developer.android.com/studio#command-line-tools-only). - Run the following command to verify the installation: ```bash adb --version ``` Output similar to the following confirms a working installation: ```log Android Debug Bridge version 1.0.41 Version 34.0.4-10411341 Installed as /usr/local/bin/adb Running on Darwin 24.3.0 (arm64) ``` - Configure the `ANDROID_HOME` environment variable as described in [Android environment variables](https://developer.android.com/tools/variables), then check that it takes effect: ```bash echo $ANDROID_HOME ``` The output should point to your local Android SDK directory, for example: ```log /Users/your_username/Library/Android/sdk ``` ### Enable debugging and connect the device The steps below use a USB connection as an example. If your device is already connected over wireless `adb`, you can keep using that connection. 1. In your phone's **Developer options**, enable **USB debugging** (and **USB debugging (Security settings)** if available, so Midscene can inject touch events). 2. Connect the phone to your computer using a USB cable that supports data transfer. 3. Keep the phone unlocked and accept the **Allow USB debugging** prompt on the screen. ![android usb debug](/images/android-usb-debug-en.png) ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash adb devices -l ``` When the device status shows `device`, the connection is ready: ```log List of devices attached s4ey59 device usb:34603008X product:cezanne model:M2006J device:cezan transport_id:3 ``` If multiple devices are connected, note the device ID in the first column (such as `s4ey59` above) so you can select the target device in Playground or your project configuration. If the target device does not appear with the `device` status, check the following: - **Empty list**: For USB, check the data cable (ensure it is not charge-only), USB connection mode, and **USB debugging** toggle; for wireless `adb`, check the network and `adb connect` status. - **`unauthorized`**: Unlock the phone screen and accept the **Allow USB debugging** prompt on the device. - **`offline`**: Reconnect the USB cable or wireless `adb` session, and restart `adb` if needed. Proceed only after the status shows `device`. ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform android \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Configure a model In the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Fill in the four `MIDSCENE_MODEL_*` values in `.env` with this configuration. ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). If more than one device is connected, set `ANDROID_DEVICE_ID` in `.env` to an ID from `adb devices -l`. ## Run the example and inspect the report The example opens React TodoMVC in the device's browser and first checks that the list is empty. Keep the device unlocked. If todos remain from an earlier run, select **All** and delete every todo, including completed ones. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own app**: In `cases/todo.yaml`, replace the TodoMVC setup in `beforeEach` with a `launch` Node that opens your app: ```yaml beforeEach: - launch: com.example.app cases: - name: Open the home screen steps: - aiAssert: The home screen of the app is visible ``` Use the package name on Android, the bundle identifier on iOS, or the bundle name on HarmonyOS. See [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md) for other system operations. - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/android-sdk-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Android · Rstest / Vitest · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Android** with **Rstest / Vitest** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the Android device Midscene uses `adb` on your computer to communicate with the target Android device over either USB or wireless `adb`. If `adb` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install adb - Install `adb` via [Android Studio](https://developer.android.com/studio) or the standalone [Android command-line tools](https://developer.android.com/studio#command-line-tools-only). - Run the following command to verify the installation: ```bash adb --version ``` Output similar to the following confirms a working installation: ```log Android Debug Bridge version 1.0.41 Version 34.0.4-10411341 Installed as /usr/local/bin/adb Running on Darwin 24.3.0 (arm64) ``` - Configure the `ANDROID_HOME` environment variable as described in [Android environment variables](https://developer.android.com/tools/variables), then check that it takes effect: ```bash echo $ANDROID_HOME ``` The output should point to your local Android SDK directory, for example: ```log /Users/your_username/Library/Android/sdk ``` ### Enable debugging and connect the device The steps below use a USB connection as an example. If your device is already connected over wireless `adb`, you can keep using that connection. 1. In your phone's **Developer options**, enable **USB debugging** (and **USB debugging (Security settings)** if available, so Midscene can inject touch events). 2. Connect the phone to your computer using a USB cable that supports data transfer. 3. Keep the phone unlocked and accept the **Allow USB debugging** prompt on the screen. ![android usb debug](/images/android-usb-debug-en.png) ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash adb devices -l ``` When the device status shows `device`, the connection is ready: ```log List of devices attached s4ey59 device usb:34603008X product:cezanne model:M2006J device:cezan transport_id:3 ``` If multiple devices are connected, note the device ID in the first column (such as `s4ey59` above) so you can select the target device in Playground or your project configuration. If the target device does not appear with the `device` status, check the following: - **Empty list**: For USB, check the data cable (ensure it is not charge-only), USB connection mode, and **USB debugging** toggle; for wireless `adb`, check the network and `adb connect` status. - **`unauthorized`**: Unlock the phone screen and accept the **Allow USB debugging** prompt on the device. - **`offline`**: Reconnect the USB cable or wireless `adb` session, and restart `adb` if needed. Proceed only after the status shows `device`. ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then write these lines to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for device tests. The steps below use Vitest; the Rstest guide covers the equivalent setup with the same platform Agents. ### Install dependencies ```bash pnpm add -D vitest dotenv @midscene/android ``` ### Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromAdbDevice } from '@midscene/android'; let agent: Awaited<ReturnType<typeof agentFromAdbDevice>> | undefined; beforeEach(async () => { agent = await agentFromAdbDevice(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.android.settings'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` If multiple devices are connected, pass a device ID to `agentFromAdbDevice(deviceId)`. See the [Android SDK guide](/sdk/android.md) for connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Share a device across tests**: [Lifecycle and exclusive device access](/sdk/vitest.md#lifecycle-and-exclusive-device-access) explains how to create and destroy Agents when tests share one device. --- url: /get-started/android-sdk-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Android · Rstest / Vitest · Model API Key {#get-started} These are the setup steps for Midscene on **Android** with **Rstest / Vitest** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the Android device Midscene uses `adb` on your computer to communicate with the target Android device over either USB or wireless `adb`. If `adb` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install adb - Install `adb` via [Android Studio](https://developer.android.com/studio) or the standalone [Android command-line tools](https://developer.android.com/studio#command-line-tools-only). - Run the following command to verify the installation: ```bash adb --version ``` Output similar to the following confirms a working installation: ```log Android Debug Bridge version 1.0.41 Version 34.0.4-10411341 Installed as /usr/local/bin/adb Running on Darwin 24.3.0 (arm64) ``` - Configure the `ANDROID_HOME` environment variable as described in [Android environment variables](https://developer.android.com/tools/variables), then check that it takes effect: ```bash echo $ANDROID_HOME ``` The output should point to your local Android SDK directory, for example: ```log /Users/your_username/Library/Android/sdk ``` ### Enable debugging and connect the device The steps below use a USB connection as an example. If your device is already connected over wireless `adb`, you can keep using that connection. 1. In your phone's **Developer options**, enable **USB debugging** (and **USB debugging (Security settings)** if available, so Midscene can inject touch events). 2. Connect the phone to your computer using a USB cable that supports data transfer. 3. Keep the phone unlocked and accept the **Allow USB debugging** prompt on the screen. ![android usb debug](/images/android-usb-debug-en.png) ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash adb devices -l ``` When the device status shows `device`, the connection is ready: ```log List of devices attached s4ey59 device usb:34603008X product:cezanne model:M2006J device:cezan transport_id:3 ``` If multiple devices are connected, note the device ID in the first column (such as `s4ey59` above) so you can select the target device in Playground or your project configuration. If the target device does not appear with the `device` status, check the following: - **Empty list**: For USB, check the data cable (ensure it is not charge-only), USB connection mode, and **USB debugging** toggle; for wireless `adb`, check the network and `adb connect` status. - **`unauthorized`**: Unlock the phone screen and accept the **Allow USB debugging** prompt on the device. - **`offline`**: Reconnect the USB cable or wireless `adb` session, and restart `adb` if needed. Proceed only after the status shows `device`. ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Write the four values to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for device tests. The steps below use Vitest; the Rstest guide covers the equivalent setup with the same platform Agents. ### Install dependencies ```bash pnpm add -D vitest dotenv @midscene/android ``` ### Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromAdbDevice } from '@midscene/android'; let agent: Awaited<ReturnType<typeof agentFromAdbDevice>> | undefined; beforeEach(async () => { agent = await agentFromAdbDevice(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.android.settings'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` If multiple devices are connected, pass a device ID to `agentFromAdbDevice(deviceId)`. See the [Android SDK guide](/sdk/android.md) for connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Share a device across tests**: [Lifecycle and exclusive device access](/sdk/vitest.md#lifecycle-and-exclusive-device-access) explains how to create and destroy Agents when tests share one device. --- url: /get-started/ios-playground-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: iOS · Playground · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **iOS** with **Playground** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Connect the iOS device through WDA Midscene communicates with iOS physical devices and simulators through a running WebDriverAgent (WDA) service. If WDA is already running and reachable from your computer, skip directly to [Verify the WDA service status](#verify-wda-status). ### Build and start WebDriverAgent Before you begin, prepare the following iOS development environment: - macOS (required for iOS development and device debugging) - Xcode and Xcode Command Line Tools - An iOS Simulator or physical iOS device :::info Version requirement WebDriverAgent version must be **>= 7.0.0**. ::: Follow the official Appium documentation to build and start WebDriverAgent (WDA): - **Simulator setup**: [Run Prebuilt WDA](https://appium.github.io/appium-xcuitest-driver/latest/guides/run-prebuilt-wda/) - **Physical device setup**: [Real Device Configuration](https://appium.github.io/appium-xcuitest-driver/latest/getting-started/device-setup/) ### Configure a physical device and forward the port iOS Simulators expose WDA directly on `localhost` and do not require port forwarding—if you are using a simulator or a remote WDA service, skip to [Verify the WDA service status](#verify-wda-status). When using a physical iOS device: 1. Connect the device to your Mac via USB and tap **Trust This Computer** when prompted on the device. 2. Enable **Developer Mode** (**Settings > Privacy & Security > Developer Mode**) and **UI Automation** (**Settings > Developer > Enable UI Automation**) on the device. 3. After signing and starting WDA on the device, use `iproxy` (installable via `brew install libimobiledevice`) to forward the WDA port (`8100` by default) from the device to your Mac: ```bash iproxy 8100 8100 YOUR_DEVICE_ID ``` Replace `YOUR_DEVICE_ID` with your device's UDID, and keep both WDA and `iproxy` running. When connecting multiple devices or using custom ports, forward each device to a distinct local port and use that port in Playground or your project configuration. ### Verify the WDA service status {#verify-wda-status} Open the WDA `/status` endpoint in your browser or terminal from the computer running Midscene: - **Default local URL**: `http://localhost:8100/status` (if using a custom port, remote host, or gateway, use the actual service address) - **Expected JSON response**: ```json { "value": { "build": { "version": "10.1.1", "time": "Sep 24 2025 18:56:41", "productBundleIdentifier": "com.facebook.WebDriverAgentRunner" }, "os": { "testmanagerdVersion": 65535, "name": "iOS", "sdkVersion": "26.0", "version": "26.0" }, "device": "iphone", "ios": { "ip": "10.91.115.63" }, "message": "WebDriverAgent is ready to accept commands", "state": "success", "ready": true }, "sessionId": "BCAD9603-F714-447C-A9E6-07D58267966B" } ``` A JSON response containing `"ready": true` confirms that WDA is ready to accept commands. Note the WDA host and port (or gateway base URL) so you can use the same connection settings in Playground and your project. ## Sign in with your ChatGPT subscription The login command needs Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. Check that `node -v` works in your terminal. If pnpm is not installed yet, run `npm install -g pnpm`. First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Playground reads the credentials saved by this command. Keep the following lines at hand. You will paste them into Playground settings in a later step: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Launch Playground Make sure Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`) is installed and `node -v` works in your terminal. The command below uses pnpm. If it is not installed yet, run `npm install -g pnpm`. 1. Start the iOS Playground CLI: ```bash pnpm dlx @midscene/ios-playground ``` 2. In the Playground window that opens, click the gear icon in the top-right corner, paste your model configuration, and save. 3. If your browser does not open automatically, visit the local Playground URL printed in the terminal, and keep the terminal process running. 4. If the connection panel appears, enter your WDA host and port (`localhost` and `8100` by default) and create the Agent (if WDA is already running on the default local port, Playground may connect automatically; when connecting through a gateway, enter the full **WebDriverAgent base URL** instead of host / port). 5. Confirm that the preview area displays your device or simulator screen. If no screen appears, check your WDA service and port forwarding first. ## Run an action and verify the result On your iOS device or simulator, open Safari and complete any first-run prompts. Enter the following TodoMVC URL in the address bar: ```text https://todomvc.com/examples/react/dist/#/ ``` Keep the device unlocked with Safari in the foreground. 1. In Playground, select `aiAct`, enter the following instruction, and run it: ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. At this point, WDA connectivity, screen capture, touch input, and model calls have all been verified together. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, check the failed step and error message: for missing screenshots or unresponsive touch input, see the [FAQ](/platforms/ios.md#faq); for model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity). After verification, delete the "Try Midscene" item in TodoMVC. If you plan to run the Midscene Test iOS example next, switch to the **All** filter and make sure the list is completely empty (including completed items), as the example template checks for an empty list before running and does not overwrite existing items. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/ios-test-chatgpt.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Rstest or Vitest**: [Call Midscene from your Vitest tests](/get-started/ios-sdk-chatgpt.md) with the same platform and model. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/ios-playground-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: iOS · Playground · Model API Key {#get-started} These are the setup steps for Midscene on **iOS** with **Playground** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Connect the iOS device through WDA Midscene communicates with iOS physical devices and simulators through a running WebDriverAgent (WDA) service. If WDA is already running and reachable from your computer, skip directly to [Verify the WDA service status](#verify-wda-status). ### Build and start WebDriverAgent Before you begin, prepare the following iOS development environment: - macOS (required for iOS development and device debugging) - Xcode and Xcode Command Line Tools - An iOS Simulator or physical iOS device :::info Version requirement WebDriverAgent version must be **>= 7.0.0**. ::: Follow the official Appium documentation to build and start WebDriverAgent (WDA): - **Simulator setup**: [Run Prebuilt WDA](https://appium.github.io/appium-xcuitest-driver/latest/guides/run-prebuilt-wda/) - **Physical device setup**: [Real Device Configuration](https://appium.github.io/appium-xcuitest-driver/latest/getting-started/device-setup/) ### Configure a physical device and forward the port iOS Simulators expose WDA directly on `localhost` and do not require port forwarding—if you are using a simulator or a remote WDA service, skip to [Verify the WDA service status](#verify-wda-status). When using a physical iOS device: 1. Connect the device to your Mac via USB and tap **Trust This Computer** when prompted on the device. 2. Enable **Developer Mode** (**Settings > Privacy & Security > Developer Mode**) and **UI Automation** (**Settings > Developer > Enable UI Automation**) on the device. 3. After signing and starting WDA on the device, use `iproxy` (installable via `brew install libimobiledevice`) to forward the WDA port (`8100` by default) from the device to your Mac: ```bash iproxy 8100 8100 YOUR_DEVICE_ID ``` Replace `YOUR_DEVICE_ID` with your device's UDID, and keep both WDA and `iproxy` running. When connecting multiple devices or using custom ports, forward each device to a distinct local port and use that port in Playground or your project configuration. ### Verify the WDA service status {#verify-wda-status} Open the WDA `/status` endpoint in your browser or terminal from the computer running Midscene: - **Default local URL**: `http://localhost:8100/status` (if using a custom port, remote host, or gateway, use the actual service address) - **Expected JSON response**: ```json { "value": { "build": { "version": "10.1.1", "time": "Sep 24 2025 18:56:41", "productBundleIdentifier": "com.facebook.WebDriverAgentRunner" }, "os": { "testmanagerdVersion": 65535, "name": "iOS", "sdkVersion": "26.0", "version": "26.0" }, "device": "iphone", "ios": { "ip": "10.91.115.63" }, "message": "WebDriverAgent is ready to accept commands", "state": "success", "ready": true }, "sessionId": "BCAD9603-F714-447C-A9E6-07D58267966B" } ``` A JSON response containing `"ready": true` confirms that WDA is ready to accept commands. Note the WDA host and port (or gateway base URL) so you can use the same connection settings in Playground and your project. ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Keep the configuration at hand. You will paste it into Playground in a later step. ## Launch Playground Make sure Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`) is installed and `node -v` works in your terminal. The command below uses pnpm. If it is not installed yet, run `npm install -g pnpm`. 1. Start the iOS Playground CLI: ```bash pnpm dlx @midscene/ios-playground ``` 2. In the Playground window that opens, click the gear icon in the top-right corner, paste your model configuration, and save. 3. If your browser does not open automatically, visit the local Playground URL printed in the terminal, and keep the terminal process running. 4. If the connection panel appears, enter your WDA host and port (`localhost` and `8100` by default) and create the Agent (if WDA is already running on the default local port, Playground may connect automatically; when connecting through a gateway, enter the full **WebDriverAgent base URL** instead of host / port). 5. Confirm that the preview area displays your device or simulator screen. If no screen appears, check your WDA service and port forwarding first. ## Run an action and verify the result On your iOS device or simulator, open Safari and complete any first-run prompts. Enter the following TodoMVC URL in the address bar: ```text https://todomvc.com/examples/react/dist/#/ ``` Keep the device unlocked with Safari in the foreground. 1. In Playground, select `aiAct`, enter the following instruction, and run it: ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. At this point, WDA connectivity, screen capture, touch input, and model calls have all been verified together. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, check the failed step and error message: for missing screenshots or unresponsive touch input, see the [FAQ](/platforms/ios.md#faq); for model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity). After verification, delete the "Try Midscene" item in TodoMVC. If you plan to run the Midscene Test iOS example next, switch to the **All** filter and make sure the list is completely empty (including completed items), as the example template checks for an empty list before running and does not overwrite existing items. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/ios-test-api-key.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Rstest or Vitest**: [Call Midscene from your Vitest tests](/get-started/ios-sdk-api-key.md) with the same platform and model. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/ios-test-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: iOS · Midscene Test · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **iOS** with **Midscene Test** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the iOS device through WDA Midscene communicates with iOS physical devices and simulators through a running WebDriverAgent (WDA) service. If WDA is already running and reachable from your computer, skip directly to [Verify the WDA service status](#verify-wda-status). ### Build and start WebDriverAgent Before you begin, prepare the following iOS development environment: - macOS (required for iOS development and device debugging) - Xcode and Xcode Command Line Tools - An iOS Simulator or physical iOS device :::info Version requirement WebDriverAgent version must be **>= 7.0.0**. ::: Follow the official Appium documentation to build and start WebDriverAgent (WDA): - **Simulator setup**: [Run Prebuilt WDA](https://appium.github.io/appium-xcuitest-driver/latest/guides/run-prebuilt-wda/) - **Physical device setup**: [Real Device Configuration](https://appium.github.io/appium-xcuitest-driver/latest/getting-started/device-setup/) ### Configure a physical device and forward the port iOS Simulators expose WDA directly on `localhost` and do not require port forwarding—if you are using a simulator or a remote WDA service, skip to [Verify the WDA service status](#verify-wda-status). When using a physical iOS device: 1. Connect the device to your Mac via USB and tap **Trust This Computer** when prompted on the device. 2. Enable **Developer Mode** (**Settings > Privacy & Security > Developer Mode**) and **UI Automation** (**Settings > Developer > Enable UI Automation**) on the device. 3. After signing and starting WDA on the device, use `iproxy` (installable via `brew install libimobiledevice`) to forward the WDA port (`8100` by default) from the device to your Mac: ```bash iproxy 8100 8100 YOUR_DEVICE_ID ``` Replace `YOUR_DEVICE_ID` with your device's UDID, and keep both WDA and `iproxy` running. When connecting multiple devices or using custom ports, forward each device to a distinct local port and use that port in Playground or your project configuration. ### Verify the WDA service status {#verify-wda-status} Open the WDA `/status` endpoint in your browser or terminal from the computer running Midscene: - **Default local URL**: `http://localhost:8100/status` (if using a custom port, remote host, or gateway, use the actual service address) - **Expected JSON response**: ```json { "value": { "build": { "version": "10.1.1", "time": "Sep 24 2025 18:56:41", "productBundleIdentifier": "com.facebook.WebDriverAgentRunner" }, "os": { "testmanagerdVersion": 65535, "name": "iOS", "sdkVersion": "26.0", "version": "26.0" }, "device": "iphone", "ios": { "ip": "10.91.115.63" }, "message": "WebDriverAgent is ready to accept commands", "state": "success", "ready": true }, "sessionId": "BCAD9603-F714-447C-A9E6-07D58267966B" } ``` A JSON response containing `"ready": true` confirms that WDA is ready to accept commands. Note the WDA host and port (or gateway base URL) so you can use the same connection settings in Playground and your project. ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform ios \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then, in the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Leave `MIDSCENE_MODEL_BASE_URL` and `MIDSCENE_MODEL_API_KEY` empty. Set `MIDSCENE_MODEL_NAME` and `MIDSCENE_MODEL_FAMILY`, and add `MIDSCENE_MODEL_AUTH_MODE`: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). The project connects to WDA on `localhost:8100` by default. For another address, set `WDA_HOST` and `WDA_PORT` in `.env`, or `WDA_BASE_URL` when you connect through a gateway. ## Run the example and inspect the report The example opens React TodoMVC in the device's browser and first checks that the list is empty. Keep the device unlocked. If todos remain from an earlier run, select **All** and delete every todo, including completed ones. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own app**: In `cases/todo.yaml`, replace the TodoMVC setup in `beforeEach` with a `launch` Node that opens your app: ```yaml beforeEach: - launch: com.example.app cases: - name: Open the home screen steps: - aiAssert: The home screen of the app is visible ``` Use the package name on Android, the bundle identifier on iOS, or the bundle name on HarmonyOS. See [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md) for other system operations. - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/ios-test-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: iOS · Midscene Test · Model API Key {#get-started} These are the setup steps for Midscene on **iOS** with **Midscene Test** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the iOS device through WDA Midscene communicates with iOS physical devices and simulators through a running WebDriverAgent (WDA) service. If WDA is already running and reachable from your computer, skip directly to [Verify the WDA service status](#verify-wda-status). ### Build and start WebDriverAgent Before you begin, prepare the following iOS development environment: - macOS (required for iOS development and device debugging) - Xcode and Xcode Command Line Tools - An iOS Simulator or physical iOS device :::info Version requirement WebDriverAgent version must be **>= 7.0.0**. ::: Follow the official Appium documentation to build and start WebDriverAgent (WDA): - **Simulator setup**: [Run Prebuilt WDA](https://appium.github.io/appium-xcuitest-driver/latest/guides/run-prebuilt-wda/) - **Physical device setup**: [Real Device Configuration](https://appium.github.io/appium-xcuitest-driver/latest/getting-started/device-setup/) ### Configure a physical device and forward the port iOS Simulators expose WDA directly on `localhost` and do not require port forwarding—if you are using a simulator or a remote WDA service, skip to [Verify the WDA service status](#verify-wda-status). When using a physical iOS device: 1. Connect the device to your Mac via USB and tap **Trust This Computer** when prompted on the device. 2. Enable **Developer Mode** (**Settings > Privacy & Security > Developer Mode**) and **UI Automation** (**Settings > Developer > Enable UI Automation**) on the device. 3. After signing and starting WDA on the device, use `iproxy` (installable via `brew install libimobiledevice`) to forward the WDA port (`8100` by default) from the device to your Mac: ```bash iproxy 8100 8100 YOUR_DEVICE_ID ``` Replace `YOUR_DEVICE_ID` with your device's UDID, and keep both WDA and `iproxy` running. When connecting multiple devices or using custom ports, forward each device to a distinct local port and use that port in Playground or your project configuration. ### Verify the WDA service status {#verify-wda-status} Open the WDA `/status` endpoint in your browser or terminal from the computer running Midscene: - **Default local URL**: `http://localhost:8100/status` (if using a custom port, remote host, or gateway, use the actual service address) - **Expected JSON response**: ```json { "value": { "build": { "version": "10.1.1", "time": "Sep 24 2025 18:56:41", "productBundleIdentifier": "com.facebook.WebDriverAgentRunner" }, "os": { "testmanagerdVersion": 65535, "name": "iOS", "sdkVersion": "26.0", "version": "26.0" }, "device": "iphone", "ios": { "ip": "10.91.115.63" }, "message": "WebDriverAgent is ready to accept commands", "state": "success", "ready": true }, "sessionId": "BCAD9603-F714-447C-A9E6-07D58267966B" } ``` A JSON response containing `"ready": true` confirms that WDA is ready to accept commands. Note the WDA host and port (or gateway base URL) so you can use the same connection settings in Playground and your project. ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform ios \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Configure a model In the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Fill in the four `MIDSCENE_MODEL_*` values in `.env` with this configuration. ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). The project connects to WDA on `localhost:8100` by default. For another address, set `WDA_HOST` and `WDA_PORT` in `.env`, or `WDA_BASE_URL` when you connect through a gateway. ## Run the example and inspect the report The example opens React TodoMVC in the device's browser and first checks that the list is empty. Keep the device unlocked. If todos remain from an earlier run, select **All** and delete every todo, including completed ones. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own app**: In `cases/todo.yaml`, replace the TodoMVC setup in `beforeEach` with a `launch` Node that opens your app: ```yaml beforeEach: - launch: com.example.app cases: - name: Open the home screen steps: - aiAssert: The home screen of the app is visible ``` Use the package name on Android, the bundle identifier on iOS, or the bundle name on HarmonyOS. See [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md) for other system operations. - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/ios-sdk-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: iOS · Rstest / Vitest · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **iOS** with **Rstest / Vitest** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the iOS device through WDA Midscene communicates with iOS physical devices and simulators through a running WebDriverAgent (WDA) service. If WDA is already running and reachable from your computer, skip directly to [Verify the WDA service status](#verify-wda-status). ### Build and start WebDriverAgent Before you begin, prepare the following iOS development environment: - macOS (required for iOS development and device debugging) - Xcode and Xcode Command Line Tools - An iOS Simulator or physical iOS device :::info Version requirement WebDriverAgent version must be **>= 7.0.0**. ::: Follow the official Appium documentation to build and start WebDriverAgent (WDA): - **Simulator setup**: [Run Prebuilt WDA](https://appium.github.io/appium-xcuitest-driver/latest/guides/run-prebuilt-wda/) - **Physical device setup**: [Real Device Configuration](https://appium.github.io/appium-xcuitest-driver/latest/getting-started/device-setup/) ### Configure a physical device and forward the port iOS Simulators expose WDA directly on `localhost` and do not require port forwarding—if you are using a simulator or a remote WDA service, skip to [Verify the WDA service status](#verify-wda-status). When using a physical iOS device: 1. Connect the device to your Mac via USB and tap **Trust This Computer** when prompted on the device. 2. Enable **Developer Mode** (**Settings > Privacy & Security > Developer Mode**) and **UI Automation** (**Settings > Developer > Enable UI Automation**) on the device. 3. After signing and starting WDA on the device, use `iproxy` (installable via `brew install libimobiledevice`) to forward the WDA port (`8100` by default) from the device to your Mac: ```bash iproxy 8100 8100 YOUR_DEVICE_ID ``` Replace `YOUR_DEVICE_ID` with your device's UDID, and keep both WDA and `iproxy` running. When connecting multiple devices or using custom ports, forward each device to a distinct local port and use that port in Playground or your project configuration. ### Verify the WDA service status {#verify-wda-status} Open the WDA `/status` endpoint in your browser or terminal from the computer running Midscene: - **Default local URL**: `http://localhost:8100/status` (if using a custom port, remote host, or gateway, use the actual service address) - **Expected JSON response**: ```json { "value": { "build": { "version": "10.1.1", "time": "Sep 24 2025 18:56:41", "productBundleIdentifier": "com.facebook.WebDriverAgentRunner" }, "os": { "testmanagerdVersion": 65535, "name": "iOS", "sdkVersion": "26.0", "version": "26.0" }, "device": "iphone", "ios": { "ip": "10.91.115.63" }, "message": "WebDriverAgent is ready to accept commands", "state": "success", "ready": true }, "sessionId": "BCAD9603-F714-447C-A9E6-07D58267966B" } ``` A JSON response containing `"ready": true` confirms that WDA is ready to accept commands. Note the WDA host and port (or gateway base URL) so you can use the same connection settings in Playground and your project. ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then write these lines to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for device tests. The steps below use Vitest; the Rstest guide covers the equivalent setup with the same platform Agents. ### Install dependencies ```bash pnpm add -D vitest dotenv @midscene/ios ``` ### Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromWebDriverAgent } from '@midscene/ios'; let agent: Awaited<ReturnType<typeof agentFromWebDriverAgent>> | undefined; beforeEach(async () => { agent = await agentFromWebDriverAgent({ wdaHost: 'localhost', wdaPort: 8100, }); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.apple.Preferences'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` Replace `wdaHost` and `wdaPort` with your verified WebDriverAgent service endpoint. See the [iOS SDK guide](/sdk/ios.md) for connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Share a device across tests**: [Lifecycle and exclusive device access](/sdk/vitest.md#lifecycle-and-exclusive-device-access) explains how to create and destroy Agents when tests share one device. --- url: /get-started/ios-sdk-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: iOS · Rstest / Vitest · Model API Key {#get-started} These are the setup steps for Midscene on **iOS** with **Rstest / Vitest** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the iOS device through WDA Midscene communicates with iOS physical devices and simulators through a running WebDriverAgent (WDA) service. If WDA is already running and reachable from your computer, skip directly to [Verify the WDA service status](#verify-wda-status). ### Build and start WebDriverAgent Before you begin, prepare the following iOS development environment: - macOS (required for iOS development and device debugging) - Xcode and Xcode Command Line Tools - An iOS Simulator or physical iOS device :::info Version requirement WebDriverAgent version must be **>= 7.0.0**. ::: Follow the official Appium documentation to build and start WebDriverAgent (WDA): - **Simulator setup**: [Run Prebuilt WDA](https://appium.github.io/appium-xcuitest-driver/latest/guides/run-prebuilt-wda/) - **Physical device setup**: [Real Device Configuration](https://appium.github.io/appium-xcuitest-driver/latest/getting-started/device-setup/) ### Configure a physical device and forward the port iOS Simulators expose WDA directly on `localhost` and do not require port forwarding—if you are using a simulator or a remote WDA service, skip to [Verify the WDA service status](#verify-wda-status). When using a physical iOS device: 1. Connect the device to your Mac via USB and tap **Trust This Computer** when prompted on the device. 2. Enable **Developer Mode** (**Settings > Privacy & Security > Developer Mode**) and **UI Automation** (**Settings > Developer > Enable UI Automation**) on the device. 3. After signing and starting WDA on the device, use `iproxy` (installable via `brew install libimobiledevice`) to forward the WDA port (`8100` by default) from the device to your Mac: ```bash iproxy 8100 8100 YOUR_DEVICE_ID ``` Replace `YOUR_DEVICE_ID` with your device's UDID, and keep both WDA and `iproxy` running. When connecting multiple devices or using custom ports, forward each device to a distinct local port and use that port in Playground or your project configuration. ### Verify the WDA service status {#verify-wda-status} Open the WDA `/status` endpoint in your browser or terminal from the computer running Midscene: - **Default local URL**: `http://localhost:8100/status` (if using a custom port, remote host, or gateway, use the actual service address) - **Expected JSON response**: ```json { "value": { "build": { "version": "10.1.1", "time": "Sep 24 2025 18:56:41", "productBundleIdentifier": "com.facebook.WebDriverAgentRunner" }, "os": { "testmanagerdVersion": 65535, "name": "iOS", "sdkVersion": "26.0", "version": "26.0" }, "device": "iphone", "ios": { "ip": "10.91.115.63" }, "message": "WebDriverAgent is ready to accept commands", "state": "success", "ready": true }, "sessionId": "BCAD9603-F714-447C-A9E6-07D58267966B" } ``` A JSON response containing `"ready": true` confirms that WDA is ready to accept commands. Note the WDA host and port (or gateway base URL) so you can use the same connection settings in Playground and your project. ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Write the four values to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for device tests. The steps below use Vitest; the Rstest guide covers the equivalent setup with the same platform Agents. ### Install dependencies ```bash pnpm add -D vitest dotenv @midscene/ios ``` ### Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromWebDriverAgent } from '@midscene/ios'; let agent: Awaited<ReturnType<typeof agentFromWebDriverAgent>> | undefined; beforeEach(async () => { agent = await agentFromWebDriverAgent({ wdaHost: 'localhost', wdaPort: 8100, }); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.apple.Preferences'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` Replace `wdaHost` and `wdaPort` with your verified WebDriverAgent service endpoint. See the [iOS SDK guide](/sdk/ios.md) for connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Share a device across tests**: [Lifecycle and exclusive device access](/sdk/vitest.md#lifecycle-and-exclusive-device-access) explains how to create and destroy Agents when tests share one device. --- url: /get-started/harmonyos-playground-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: HarmonyOS · Playground · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **HarmonyOS** with **Playground** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Connect the HarmonyOS device Midscene uses `hdc` on your computer to communicate with the target HarmonyOS NEXT device. If `hdc` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install HDC HDC (HarmonyOS Device Connector) is the official command-line tool for communicating with HarmonyOS devices. Install it using either of the following methods: - Via [DevEco Studio](https://developer.huawei.com/consumer/en/deveco-studio/) (recommended) - Via the standalone [HarmonyOS Command Line Tools](https://developer.huawei.com/consumer/en/download/) Run the following command to verify the installation: ```bash hdc version ``` A version number in the terminal output confirms a working installation. :::info Configuring the HDC path If `hdc` is not in your system `PATH`, set the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` ::: ### Enable debugging and connect the device 1. On your HarmonyOS device, open **Settings > System > Developer options** and enable **USB debugging**. 2. Connect the device to your computer using a USB cable that supports data transfer. 3. Keep the device unlocked and accept the debugging authorization prompt on the screen. ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash hdc list targets ``` A device ID in the output confirms that the device is connected and ready: ```log 0123456789ABCDEF ``` If multiple devices are connected, note the target device ID so you can select it in Playground or your project configuration. If the output is empty or `[Empty]`, check the USB cable, USB connection mode, **USB debugging** toggle, and the authorization prompt on the device. ## Sign in with your ChatGPT subscription The login command needs Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. Check that `node -v` works in your terminal. If pnpm is not installed yet, run `npm install -g pnpm`. First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Playground reads the credentials saved by this command. Keep the following lines at hand. You will paste them into Playground settings in a later step: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Launch Playground Make sure Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`) is installed and `node -v` works in your terminal. The command below uses pnpm. If it is not installed yet, run `npm install -g pnpm`. 1. Start the HarmonyOS Playground CLI: ```bash pnpm dlx @midscene/harmony-playground ``` 2. In the Playground window that opens, click the gear icon in the top-right corner, paste your model configuration, and save. 3. If your browser does not open automatically, visit the local Playground URL printed in the terminal, and keep the terminal process running. 4. In the connection panel on the left, select your target HDC device (matching the ID from `hdc list targets`) and create the Agent. 5. Confirm that the preview area displays your device's current screen. If no screen appears, check the HDC connection and device debugging authorization first. ## Run an action and verify the result On your HarmonyOS device, open the system browser and complete any first-run prompts. Enter the following TodoMVC URL in the address bar: ```text https://todomvc.com/examples/react/dist/#/ ``` Keep the device unlocked with the browser in the foreground. 1. In Playground, select `aiAct`, enter the following instruction, and run it: ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. At this point, HDC connectivity, screen capture, touch input, and model calls have all been verified together. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, check the failed step and error message: for missing screenshots or unresponsive touch input, see the [FAQ](/platforms/harmonyos.md#faq); for model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity). After verification, delete the "Try Midscene" item in TodoMVC. If you plan to run the Midscene Test HarmonyOS example next, switch to the **All** filter and make sure the list is completely empty (including completed items), as the example template checks for an empty list before running and does not overwrite existing items. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/harmonyos-test-chatgpt.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Rstest or Vitest**: [Call Midscene from your Vitest tests](/get-started/harmonyos-sdk-chatgpt.md) with the same platform and model. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/harmonyos-playground-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: HarmonyOS · Playground · Model API Key {#get-started} These are the setup steps for Midscene on **HarmonyOS** with **Playground** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Connect the HarmonyOS device Midscene uses `hdc` on your computer to communicate with the target HarmonyOS NEXT device. If `hdc` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install HDC HDC (HarmonyOS Device Connector) is the official command-line tool for communicating with HarmonyOS devices. Install it using either of the following methods: - Via [DevEco Studio](https://developer.huawei.com/consumer/en/deveco-studio/) (recommended) - Via the standalone [HarmonyOS Command Line Tools](https://developer.huawei.com/consumer/en/download/) Run the following command to verify the installation: ```bash hdc version ``` A version number in the terminal output confirms a working installation. :::info Configuring the HDC path If `hdc` is not in your system `PATH`, set the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` ::: ### Enable debugging and connect the device 1. On your HarmonyOS device, open **Settings > System > Developer options** and enable **USB debugging**. 2. Connect the device to your computer using a USB cable that supports data transfer. 3. Keep the device unlocked and accept the debugging authorization prompt on the screen. ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash hdc list targets ``` A device ID in the output confirms that the device is connected and ready: ```log 0123456789ABCDEF ``` If multiple devices are connected, note the target device ID so you can select it in Playground or your project configuration. If the output is empty or `[Empty]`, check the USB cable, USB connection mode, **USB debugging** toggle, and the authorization prompt on the device. ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Keep the configuration at hand. You will paste it into Playground in a later step. ## Launch Playground Make sure Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`) is installed and `node -v` works in your terminal. The command below uses pnpm. If it is not installed yet, run `npm install -g pnpm`. 1. Start the HarmonyOS Playground CLI: ```bash pnpm dlx @midscene/harmony-playground ``` 2. In the Playground window that opens, click the gear icon in the top-right corner, paste your model configuration, and save. 3. If your browser does not open automatically, visit the local Playground URL printed in the terminal, and keep the terminal process running. 4. In the connection panel on the left, select your target HDC device (matching the ID from `hdc list targets`) and create the Agent. 5. Confirm that the preview area displays your device's current screen. If no screen appears, check the HDC connection and device debugging authorization first. ## Run an action and verify the result On your HarmonyOS device, open the system browser and complete any first-run prompts. Enter the following TodoMVC URL in the address bar: ```text https://todomvc.com/examples/react/dist/#/ ``` Keep the device unlocked with the browser in the foreground. 1. In Playground, select `aiAct`, enter the following instruction, and run it: ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. At this point, HDC connectivity, screen capture, touch input, and model calls have all been verified together. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, check the failed step and error message: for missing screenshots or unresponsive touch input, see the [FAQ](/platforms/harmonyos.md#faq); for model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity). After verification, delete the "Try Midscene" item in TodoMVC. If you plan to run the Midscene Test HarmonyOS example next, switch to the **All** filter and make sure the list is completely empty (including completed items), as the example template checks for an empty list before running and does not overwrite existing items. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/harmonyos-test-api-key.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Rstest or Vitest**: [Call Midscene from your Vitest tests](/get-started/harmonyos-sdk-api-key.md) with the same platform and model. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/harmonyos-test-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: HarmonyOS · Midscene Test · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **HarmonyOS** with **Midscene Test** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the HarmonyOS device Midscene uses `hdc` on your computer to communicate with the target HarmonyOS NEXT device. If `hdc` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install HDC HDC (HarmonyOS Device Connector) is the official command-line tool for communicating with HarmonyOS devices. Install it using either of the following methods: - Via [DevEco Studio](https://developer.huawei.com/consumer/en/deveco-studio/) (recommended) - Via the standalone [HarmonyOS Command Line Tools](https://developer.huawei.com/consumer/en/download/) Run the following command to verify the installation: ```bash hdc version ``` A version number in the terminal output confirms a working installation. :::info Configuring the HDC path If `hdc` is not in your system `PATH`, set the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` ::: ### Enable debugging and connect the device 1. On your HarmonyOS device, open **Settings > System > Developer options** and enable **USB debugging**. 2. Connect the device to your computer using a USB cable that supports data transfer. 3. Keep the device unlocked and accept the debugging authorization prompt on the screen. ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash hdc list targets ``` A device ID in the output confirms that the device is connected and ready: ```log 0123456789ABCDEF ``` If multiple devices are connected, note the target device ID so you can select it in Playground or your project configuration. If the output is empty or `[Empty]`, check the USB cable, USB connection mode, **USB debugging** toggle, and the authorization prompt on the device. ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform harmony \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then, in the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Leave `MIDSCENE_MODEL_BASE_URL` and `MIDSCENE_MODEL_API_KEY` empty. Set `MIDSCENE_MODEL_NAME` and `MIDSCENE_MODEL_FAMILY`, and add `MIDSCENE_MODEL_AUTH_MODE`: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). If more than one device is connected, set `HARMONY_DEVICE_ID` in `.env` to an ID from `hdc list targets`. If `hdc` is not on `PATH`, set `HDC_HOME`. ## Run the example and inspect the report The example opens React TodoMVC in the device's browser and first checks that the list is empty. Keep the device unlocked. If todos remain from an earlier run, select **All** and delete every todo, including completed ones. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own app**: In `cases/todo.yaml`, replace the TodoMVC setup in `beforeEach` with a `launch` Node that opens your app: ```yaml beforeEach: - launch: com.example.app cases: - name: Open the home screen steps: - aiAssert: The home screen of the app is visible ``` Use the package name on Android, the bundle identifier on iOS, or the bundle name on HarmonyOS. See [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md) for other system operations. - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/harmonyos-test-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: HarmonyOS · Midscene Test · Model API Key {#get-started} These are the setup steps for Midscene on **HarmonyOS** with **Midscene Test** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the HarmonyOS device Midscene uses `hdc` on your computer to communicate with the target HarmonyOS NEXT device. If `hdc` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install HDC HDC (HarmonyOS Device Connector) is the official command-line tool for communicating with HarmonyOS devices. Install it using either of the following methods: - Via [DevEco Studio](https://developer.huawei.com/consumer/en/deveco-studio/) (recommended) - Via the standalone [HarmonyOS Command Line Tools](https://developer.huawei.com/consumer/en/download/) Run the following command to verify the installation: ```bash hdc version ``` A version number in the terminal output confirms a working installation. :::info Configuring the HDC path If `hdc` is not in your system `PATH`, set the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` ::: ### Enable debugging and connect the device 1. On your HarmonyOS device, open **Settings > System > Developer options** and enable **USB debugging**. 2. Connect the device to your computer using a USB cable that supports data transfer. 3. Keep the device unlocked and accept the debugging authorization prompt on the screen. ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash hdc list targets ``` A device ID in the output confirms that the device is connected and ready: ```log 0123456789ABCDEF ``` If multiple devices are connected, note the target device ID so you can select it in Playground or your project configuration. If the output is empty or `[Empty]`, check the USB cable, USB connection mode, **USB debugging** toggle, and the authorization prompt on the device. ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform harmony \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Configure a model In the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Fill in the four `MIDSCENE_MODEL_*` values in `.env` with this configuration. ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). If more than one device is connected, set `HARMONY_DEVICE_ID` in `.env` to an ID from `hdc list targets`. If `hdc` is not on `PATH`, set `HDC_HOME`. ## Run the example and inspect the report The example opens React TodoMVC in the device's browser and first checks that the list is empty. Keep the device unlocked. If todos remain from an earlier run, select **All** and delete every todo, including completed ones. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own app**: In `cases/todo.yaml`, replace the TodoMVC setup in `beforeEach` with a `launch` Node that opens your app: ```yaml beforeEach: - launch: com.example.app cases: - name: Open the home screen steps: - aiAssert: The home screen of the app is visible ``` Use the package name on Android, the bundle identifier on iOS, or the bundle name on HarmonyOS. See [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md) for other system operations. - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/harmonyos-sdk-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: HarmonyOS · Rstest / Vitest · Model API Key {#get-started} These are the setup steps for Midscene on **HarmonyOS** with **Rstest / Vitest** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the HarmonyOS device Midscene uses `hdc` on your computer to communicate with the target HarmonyOS NEXT device. If `hdc` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install HDC HDC (HarmonyOS Device Connector) is the official command-line tool for communicating with HarmonyOS devices. Install it using either of the following methods: - Via [DevEco Studio](https://developer.huawei.com/consumer/en/deveco-studio/) (recommended) - Via the standalone [HarmonyOS Command Line Tools](https://developer.huawei.com/consumer/en/download/) Run the following command to verify the installation: ```bash hdc version ``` A version number in the terminal output confirms a working installation. :::info Configuring the HDC path If `hdc` is not in your system `PATH`, set the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` ::: ### Enable debugging and connect the device 1. On your HarmonyOS device, open **Settings > System > Developer options** and enable **USB debugging**. 2. Connect the device to your computer using a USB cable that supports data transfer. 3. Keep the device unlocked and accept the debugging authorization prompt on the screen. ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash hdc list targets ``` A device ID in the output confirms that the device is connected and ready: ```log 0123456789ABCDEF ``` If multiple devices are connected, note the target device ID so you can select it in Playground or your project configuration. If the output is empty or `[Empty]`, check the USB cable, USB connection mode, **USB debugging** toggle, and the authorization prompt on the device. ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Write the four values to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for device tests. The steps below use Vitest; the Rstest guide covers the equivalent setup with the same platform Agents. ### Install dependencies ```bash pnpm add -D vitest dotenv @midscene/harmony ``` ### Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromHdcDevice } from '@midscene/harmony'; let agent: Awaited<ReturnType<typeof agentFromHdcDevice>> | undefined; beforeEach(async () => { agent = await agentFromHdcDevice(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.huawei.hmos.settings'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` If multiple devices are connected, pass a device ID to `agentFromHdcDevice(deviceId)`. See the [HarmonyOS SDK guide](/sdk/harmonyos.md) for connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Share a device across tests**: [Lifecycle and exclusive device access](/sdk/vitest.md#lifecycle-and-exclusive-device-access) explains how to create and destroy Agents when tests share one device. --- url: /get-started/desktop-playground-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Desktop · Playground · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Desktop** with **Playground** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Grant desktop permissions - **macOS**: Grant two separate system permissions to the terminal or IDE that launches Playground or runs your scripts (such as Terminal, iTerm2, VS Code, Cursor, or WebStorm): 1. **Accessibility** (for mouse and keyboard control): Enable your terminal or IDE in **System Settings > Privacy & Security > Accessibility** (see [nut.js macOS setup](https://github.com/nut-tree/nut.js#macos)). 2. **Screen Recording** (for desktop screenshots): Enable your terminal or IDE in **System Settings > Privacy & Security > Screen Recording**. **After granting access, completely quit and relaunch the terminal or IDE** before starting Playground. - **Windows**: No extra setup is required for standard applications. However, Windows User Interface Privilege Isolation (UIPI) blocks non-elevated processes from injecting mouse clicks or keystrokes into windows running **as Administrator** (the cursor still moves to the target coordinates, but clicks and key presses are silently dropped). Prefer running the target app without Administrator privileges; if it must run elevated, launch the terminal or Node.js process running Midscene **as Administrator** as well (see [Windows: clicks have no effect on some apps](/platforms/desktop.md#windows-clicks-have-no-effect-on-some-apps)). - **Linux (desktop GUI)**: Install [ImageMagick](https://imagemagick.org/script/download.php) for screen capture support. - **Linux (headless server / CI)**: To run desktop automation on a headless Linux host (such as GitHub Actions), install Xvfb and ImageMagick, then enable headless mode to start a virtual display automatically: ```bash # Install dependencies sudo apt-get install -y xvfb x11-xserver-utils imagemagick ``` When using Xvfb, make sure the target application is started inside the same virtual display environment (not needed on machines with a physical display). To control a remote Windows desktop over RDP, see [Desktop environment setup](/platforms/desktop.md#connect-device). ## Sign in with your ChatGPT subscription The login command needs Node.js `^20.19.0 || ^22.12.0 || >=24.0.0` and pnpm. Check that `node -v` works in your terminal. If pnpm is not installed yet, run `npm install -g pnpm`. First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Playground reads the credentials saved by this command. Keep the following lines at hand. You will paste them into Playground settings in a later step: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Launch Playground Make sure Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`) is installed and `node -v` works in your terminal. The command below uses pnpm. If it is not installed yet, run `npm install -g pnpm`. 1. Start the Desktop Playground CLI: ```bash pnpm dlx @midscene/computer-playground ``` On headless Linux, enable a virtual display with the following command and run the target application in that same display: ```bash MIDSCENE_COMPUTER_HEADLESS_LINUX=true pnpm dlx @midscene/computer-playground ``` 2. In the Playground window that opens, click the gear icon in the top-right corner, paste your model configuration, and save. 3. If your browser does not open automatically, visit the local Playground URL printed in the terminal, and keep the terminal process running. 4. In the connection panel on the left, select the target **Display** to control, create the Agent, and place the target application window on that display. 5. Confirm that the preview area shows the live screen of the selected display. If the preview is blank or fails to load, check the Screen Recording permission or Linux dependencies above. ## Run an action and verify the result Open a browser window on the target display and enter the following TodoMVC URL in the address bar: ```text https://todomvc.com/examples/react/dist/#/ ``` Position the windows so that the Playground tab does not cover the TodoMVC page. 1. In Playground, select `aiAct`, enter the following instruction, and run it (avoid moving the mouse or typing while the action is running): ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. At this point, desktop screen capture, mouse/keyboard input, and model calls have all been verified together. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, check the failed step and error message: for missing screenshots or unresponsive mouse/keyboard input, see the [FAQ](/platforms/desktop.md#faq); for model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity). After verification, delete the "Try Midscene" item in TodoMVC. If you plan to run the Midscene Test Desktop example next, switch to the **All** filter and make sure the list is completely empty (including completed items), as the example template checks for an empty list before running and does not overwrite existing items. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/desktop-test-chatgpt.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Rstest or Vitest**: [Call Midscene from your Vitest tests](/get-started/desktop-sdk-chatgpt.md) with the same platform and model. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/desktop-playground-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Desktop · Playground · Model API Key {#get-started} These are the setup steps for Midscene on **Desktop** with **Playground** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Grant desktop permissions - **macOS**: Grant two separate system permissions to the terminal or IDE that launches Playground or runs your scripts (such as Terminal, iTerm2, VS Code, Cursor, or WebStorm): 1. **Accessibility** (for mouse and keyboard control): Enable your terminal or IDE in **System Settings > Privacy & Security > Accessibility** (see [nut.js macOS setup](https://github.com/nut-tree/nut.js#macos)). 2. **Screen Recording** (for desktop screenshots): Enable your terminal or IDE in **System Settings > Privacy & Security > Screen Recording**. **After granting access, completely quit and relaunch the terminal or IDE** before starting Playground. - **Windows**: No extra setup is required for standard applications. However, Windows User Interface Privilege Isolation (UIPI) blocks non-elevated processes from injecting mouse clicks or keystrokes into windows running **as Administrator** (the cursor still moves to the target coordinates, but clicks and key presses are silently dropped). Prefer running the target app without Administrator privileges; if it must run elevated, launch the terminal or Node.js process running Midscene **as Administrator** as well (see [Windows: clicks have no effect on some apps](/platforms/desktop.md#windows-clicks-have-no-effect-on-some-apps)). - **Linux (desktop GUI)**: Install [ImageMagick](https://imagemagick.org/script/download.php) for screen capture support. - **Linux (headless server / CI)**: To run desktop automation on a headless Linux host (such as GitHub Actions), install Xvfb and ImageMagick, then enable headless mode to start a virtual display automatically: ```bash # Install dependencies sudo apt-get install -y xvfb x11-xserver-utils imagemagick ``` When using Xvfb, make sure the target application is started inside the same virtual display environment (not needed on machines with a physical display). To control a remote Windows desktop over RDP, see [Desktop environment setup](/platforms/desktop.md#connect-device). ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Keep the configuration at hand. You will paste it into Playground in a later step. ## Launch Playground Make sure Node.js (`^20.19.0 || ^22.12.0 || >=24.0.0`) is installed and `node -v` works in your terminal. The command below uses pnpm. If it is not installed yet, run `npm install -g pnpm`. 1. Start the Desktop Playground CLI: ```bash pnpm dlx @midscene/computer-playground ``` On headless Linux, enable a virtual display with the following command and run the target application in that same display: ```bash MIDSCENE_COMPUTER_HEADLESS_LINUX=true pnpm dlx @midscene/computer-playground ``` 2. In the Playground window that opens, click the gear icon in the top-right corner, paste your model configuration, and save. 3. If your browser does not open automatically, visit the local Playground URL printed in the terminal, and keep the terminal process running. 4. In the connection panel on the left, select the target **Display** to control, create the Agent, and place the target application window on that display. 5. Confirm that the preview area shows the live screen of the selected display. If the preview is blank or fails to load, check the Screen Recording permission or Linux dependencies above. ## Run an action and verify the result Open a browser window on the target display and enter the following TodoMVC URL in the address bar: ```text https://todomvc.com/examples/react/dist/#/ ``` Position the windows so that the Playground tab does not cover the TodoMVC page. 1. In Playground, select `aiAct`, enter the following instruction, and run it (avoid moving the mouse or typing while the action is running): ```text Add a todo named "Try Midscene", then mark it as completed. ``` 2. Once the completed todo item appears on the page, switch to `aiAssert`, enter the following assertion, and run it: ```text The list contains a todo named "Try Midscene", and it is marked as completed. ``` 3. Confirm that the assertion passes and inspect the step-by-step screenshots in the results panel. At this point, desktop screen capture, mouse/keyboard input, and model calls have all been verified together. 4. (Optional) Switch to `aiQuery`, enter the following query, and run it: ```text Return the visible todo items as {name: string, completed: boolean}[]. ``` The result contains each todo item's name and completion status. `aiQuery` extracts data from the current UI without changing the page. If execution fails, check the failed step and error message: for missing screenshots or unresponsive mouse/keyboard input, see the [FAQ](/platforms/desktop.md#faq); for model request errors, see [Verify model connectivity](/model-config.md#verify-model-connectivity). After verification, delete the "Try Midscene" item in TodoMVC. If you plan to run the Midscene Test Desktop example next, switch to the **All** filter and make sure the list is completely empty (including completed items), as the example template checks for an empty list before running and does not overwrite existing items. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Write repeatable cases**: [Create a Midscene Test project](/get-started/desktop-test-api-key.md) with the same platform and model. Cases are YAML files that you can run locally or in CI. - **Add to Rstest or Vitest**: [Call Midscene from your Vitest tests](/get-started/desktop-sdk-api-key.md) with the same platform and model. - **Learn how Midscene works**: [The Basics](/basics.md) explains the vision-based approach and when to use `aiAct`, instant actions, and insight APIs. --- url: /get-started/desktop-test-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Desktop · Midscene Test · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Desktop** with **Midscene Test** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Grant desktop permissions - **macOS**: Grant two separate system permissions to the terminal or IDE that launches Playground or runs your scripts (such as Terminal, iTerm2, VS Code, Cursor, or WebStorm): 1. **Accessibility** (for mouse and keyboard control): Enable your terminal or IDE in **System Settings > Privacy & Security > Accessibility** (see [nut.js macOS setup](https://github.com/nut-tree/nut.js#macos)). 2. **Screen Recording** (for desktop screenshots): Enable your terminal or IDE in **System Settings > Privacy & Security > Screen Recording**. **After granting access, completely quit and relaunch the terminal or IDE** before starting Playground. - **Windows**: No extra setup is required for standard applications. However, Windows User Interface Privilege Isolation (UIPI) blocks non-elevated processes from injecting mouse clicks or keystrokes into windows running **as Administrator** (the cursor still moves to the target coordinates, but clicks and key presses are silently dropped). Prefer running the target app without Administrator privileges; if it must run elevated, launch the terminal or Node.js process running Midscene **as Administrator** as well (see [Windows: clicks have no effect on some apps](/platforms/desktop.md#windows-clicks-have-no-effect-on-some-apps)). - **Linux (desktop GUI)**: Install [ImageMagick](https://imagemagick.org/script/download.php) for screen capture support. - **Linux (headless server / CI)**: To run desktop automation on a headless Linux host (such as GitHub Actions), install Xvfb and ImageMagick, then enable headless mode to start a virtual display automatically: ```bash # Install dependencies sudo apt-get install -y xvfb x11-xserver-utils imagemagick ``` When using Xvfb, make sure the target application is started inside the same virtual display environment (not needed on machines with a physical display). To control a remote Windows desktop over RDP, see [Desktop environment setup](/platforms/desktop.md#connect-device). ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform computer \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then, in the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Leave `MIDSCENE_MODEL_BASE_URL` and `MIDSCENE_MODEL_API_KEY` empty. Set `MIDSCENE_MODEL_NAME` and `MIDSCENE_MODEL_FAMILY`, and add `MIDSCENE_MODEL_AUTH_MODE`: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). To control a display other than the primary one, set `COMPUTER_DISPLAY_ID` in `.env`. On headless Linux, also set `MIDSCENE_COMPUTER_HEADLESS_LINUX=true`. ## Run the example and inspect the report The example opens React TodoMVC in a browser on the target display and first checks that the list is empty. Do not move the mouse or type while it runs. If todos remain from an earlier run, select **All** and delete every todo, including completed ones. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own app**: Open the target application on the controlled display, then describe the steps with `aiAct` and `aiAssert`. To start or reset the app from a case, [develop a custom Node](/midscene-test/extend.md). - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/harmonyos-sdk-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: HarmonyOS · Rstest / Vitest · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **HarmonyOS** with **Rstest / Vitest** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the HarmonyOS device Midscene uses `hdc` on your computer to communicate with the target HarmonyOS NEXT device. If `hdc` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install HDC HDC (HarmonyOS Device Connector) is the official command-line tool for communicating with HarmonyOS devices. Install it using either of the following methods: - Via [DevEco Studio](https://developer.huawei.com/consumer/en/deveco-studio/) (recommended) - Via the standalone [HarmonyOS Command Line Tools](https://developer.huawei.com/consumer/en/download/) Run the following command to verify the installation: ```bash hdc version ``` A version number in the terminal output confirms a working installation. :::info Configuring the HDC path If `hdc` is not in your system `PATH`, set the `HDC_HOME` environment variable to the directory containing the `hdc` executable: ```bash export HDC_HOME=/path/to/hdc/directory ``` ::: ### Enable debugging and connect the device 1. On your HarmonyOS device, open **Settings > System > Developer options** and enable **USB debugging**. 2. Connect the device to your computer using a USB cable that supports data transfer. 3. Keep the device unlocked and accept the debugging authorization prompt on the screen. ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash hdc list targets ``` A device ID in the output confirms that the device is connected and ready: ```log 0123456789ABCDEF ``` If multiple devices are connected, note the target device ID so you can select it in Playground or your project configuration. If the output is empty or `[Empty]`, check the USB cable, USB connection mode, **USB debugging** toggle, and the authorization prompt on the device. ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then write these lines to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for device tests. The steps below use Vitest; the Rstest guide covers the equivalent setup with the same platform Agents. ### Install dependencies ```bash pnpm add -D vitest dotenv @midscene/harmony ``` ### Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentFromHdcDevice } from '@midscene/harmony'; let agent: Awaited<ReturnType<typeof agentFromHdcDevice>> | undefined; beforeEach(async () => { agent = await agentFromHdcDevice(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.launch('com.huawei.hmos.settings'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` If multiple devices are connected, pass a device ID to `agentFromHdcDevice(deviceId)`. See the [HarmonyOS SDK guide](/sdk/harmonyos.md) for connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Share a device across tests**: [Lifecycle and exclusive device access](/sdk/vitest.md#lifecycle-and-exclusive-device-access) explains how to create and destroy Agents when tests share one device. --- url: /get-started/desktop-test-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Desktop · Midscene Test · Model API Key {#get-started} These are the setup steps for Midscene on **Desktop** with **Midscene Test** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Grant desktop permissions - **macOS**: Grant two separate system permissions to the terminal or IDE that launches Playground or runs your scripts (such as Terminal, iTerm2, VS Code, Cursor, or WebStorm): 1. **Accessibility** (for mouse and keyboard control): Enable your terminal or IDE in **System Settings > Privacy & Security > Accessibility** (see [nut.js macOS setup](https://github.com/nut-tree/nut.js#macos)). 2. **Screen Recording** (for desktop screenshots): Enable your terminal or IDE in **System Settings > Privacy & Security > Screen Recording**. **After granting access, completely quit and relaunch the terminal or IDE** before starting Playground. - **Windows**: No extra setup is required for standard applications. However, Windows User Interface Privilege Isolation (UIPI) blocks non-elevated processes from injecting mouse clicks or keystrokes into windows running **as Administrator** (the cursor still moves to the target coordinates, but clicks and key presses are silently dropped). Prefer running the target app without Administrator privileges; if it must run elevated, launch the terminal or Node.js process running Midscene **as Administrator** as well (see [Windows: clicks have no effect on some apps](/platforms/desktop.md#windows-clicks-have-no-effect-on-some-apps)). - **Linux (desktop GUI)**: Install [ImageMagick](https://imagemagick.org/script/download.php) for screen capture support. - **Linux (headless server / CI)**: To run desktop automation on a headless Linux host (such as GitHub Actions), install Xvfb and ImageMagick, then enable headless mode to start a virtual display automatically: ```bash # Install dependencies sudo apt-get install -y xvfb x11-xserver-utils imagemagick ``` When using Xvfb, make sure the target application is started inside the same virtual display environment (not needed on machines with a physical display). To control a remote Windows desktop over RDP, see [Desktop environment setup](/platforms/desktop.md#connect-device). ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform computer \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Configure a model In the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Fill in the four `MIDSCENE_MODEL_*` values in `.env` with this configuration. ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). To control a display other than the primary one, set `COMPUTER_DISPLAY_ID` in `.env`. On headless Linux, also set `MIDSCENE_COMPUTER_HEADLESS_LINUX=true`. ## Run the example and inspect the report The example opens React TodoMVC in a browser on the target display and first checks that the list is empty. Do not move the mouse or type while it runs. If todos remain from an earlier run, select **All** and delete every todo, including completed ones. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own app**: Open the target application on the controlled display, then describe the steps with `aiAct` and `aiAssert`. To start or reset the app from a case, [develop a custom Node](/midscene-test/extend.md). - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions). --- url: /get-started/desktop-sdk-api-key.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Desktop · Rstest / Vitest · Model API Key {#get-started} These are the setup steps for Midscene on **Desktop** with **Rstest / Vitest** and a **Model API Key**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Grant desktop permissions - **macOS**: Grant two separate system permissions to the terminal or IDE that launches Playground or runs your scripts (such as Terminal, iTerm2, VS Code, Cursor, or WebStorm): 1. **Accessibility** (for mouse and keyboard control): Enable your terminal or IDE in **System Settings > Privacy & Security > Accessibility** (see [nut.js macOS setup](https://github.com/nut-tree/nut.js#macos)). 2. **Screen Recording** (for desktop screenshots): Enable your terminal or IDE in **System Settings > Privacy & Security > Screen Recording**. **After granting access, completely quit and relaunch the terminal or IDE** before starting Playground. - **Windows**: No extra setup is required for standard applications. However, Windows User Interface Privilege Isolation (UIPI) blocks non-elevated processes from injecting mouse clicks or keystrokes into windows running **as Administrator** (the cursor still moves to the target coordinates, but clicks and key presses are silently dropped). Prefer running the target app without Administrator privileges; if it must run elevated, launch the terminal or Node.js process running Midscene **as Administrator** as well (see [Windows: clicks have no effect on some apps](/platforms/desktop.md#windows-clicks-have-no-effect-on-some-apps)). - **Linux (desktop GUI)**: Install [ImageMagick](https://imagemagick.org/script/download.php) for screen capture support. - **Linux (headless server / CI)**: To run desktop automation on a headless Linux host (such as GitHub Actions), install Xvfb and ImageMagick, then enable headless mode to start a virtual display automatically: ```bash # Install dependencies sudo apt-get install -y xvfb x11-xserver-utils imagemagick ``` When using Xvfb, make sure the target application is started inside the same virtual display environment (not needed on machines with a physical display). To control a remote Windows desktop over RDP, see [Desktop environment setup](/platforms/desktop.md#connect-device). ## Configure a model Choose a model below. Its configuration has four values. Open **Get API key** to create a key with the provider, then replace `......` in `MIDSCENE_MODEL_API_KEY` with it. The configuration below is for Doubao-Seed-2.1 Turbo. Other recommended models: - [Qwen3.7 Plus](/model-api-setup.md#qwen) (Alibaba) - [DeepSeek V4.1 Flash](/model-api-setup.md#deepseek) (DeepSeek) - [Gemini 3.5 Flash](/model-api-setup.md#gemini) (Google) - [GPT-6 Sol](/model-api-setup.md#gpt) (OpenAI) - [Kimi K3](/model-api-setup.md#kimi) (Moonshot AI) - [MiMo V2.6 Pro](/model-api-setup.md#xiaomi-mimo) (Xiaomi) - [GLM-5V-Turbo](/model-api-setup.md#glm-v) (Zhipu AI) - [Ling-3.2-flash](/model-api-setup.md#ant-ling) (Ant Group) - [Tencent HY4](/model-api-setup.md#tencent-hy) (undefined) **Volcano Engine** ([Get API key](https://console.volcengine.com/ark)) ```bash MIDSCENE_MODEL_BASE_URL="https://ark.cn-beijing.volces.com/api/v3" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="doubao-seed-2-1-turbo-260628" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` **OpenRouter** ([Get API key](https://openrouter.ai/settings/keys)) ```bash MIDSCENE_MODEL_BASE_URL="https://openrouter.ai/api/v1" MIDSCENE_MODEL_API_KEY="......" MIDSCENE_MODEL_NAME="bytedance-seed/seed-2-1-turbo" MIDSCENE_MODEL_FAMILY="doubao-seed" ``` For other versions and usage notes, see [Doubao Seed series](/model-api-setup.md#doubao-seed-model). To compare models, see the [Model selection guide](/model-selection.md). For compatible models such as UI-TARS, see [Use a model API key](/model-api-setup.md#supported-models). Write the four values to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for device tests. The steps below use Vitest; the Rstest guide covers the equivalent setup with the same platform Agents. ### Install dependencies ```bash pnpm add -D vitest dotenv @midscene/computer ``` ### Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentForComputer } from '@midscene/computer'; let agent: Awaited<ReturnType<typeof agentForComputer>> | undefined; beforeEach(async () => { agent = await agentForComputer(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` Before running the test, open your system Settings app and bring a scrollable settings page to the foreground. Keep it visible during the test. See the [desktop SDK guide](/sdk/desktop.md) for permissions and connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Share a device across tests**: [Lifecycle and exclusive device access](/sdk/vitest.md#lifecycle-and-exclusive-device-access) explains how to create and destroy Agents when tests share one device. --- url: /get-started/desktop-sdk-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Desktop · Rstest / Vitest · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Desktop** with **Rstest / Vitest** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Grant desktop permissions - **macOS**: Grant two separate system permissions to the terminal or IDE that launches Playground or runs your scripts (such as Terminal, iTerm2, VS Code, Cursor, or WebStorm): 1. **Accessibility** (for mouse and keyboard control): Enable your terminal or IDE in **System Settings > Privacy & Security > Accessibility** (see [nut.js macOS setup](https://github.com/nut-tree/nut.js#macos)). 2. **Screen Recording** (for desktop screenshots): Enable your terminal or IDE in **System Settings > Privacy & Security > Screen Recording**. **After granting access, completely quit and relaunch the terminal or IDE** before starting Playground. - **Windows**: No extra setup is required for standard applications. However, Windows User Interface Privilege Isolation (UIPI) blocks non-elevated processes from injecting mouse clicks or keystrokes into windows running **as Administrator** (the cursor still moves to the target coordinates, but clicks and key presses are silently dropped). Prefer running the target app without Administrator privileges; if it must run elevated, launch the terminal or Node.js process running Midscene **as Administrator** as well (see [Windows: clicks have no effect on some apps](/platforms/desktop.md#windows-clicks-have-no-effect-on-some-apps)). - **Linux (desktop GUI)**: Install [ImageMagick](https://imagemagick.org/script/download.php) for screen capture support. - **Linux (headless server / CI)**: To run desktop automation on a headless Linux host (such as GitHub Actions), install Xvfb and ImageMagick, then enable headless mode to start a virtual display automatically: ```bash # Install dependencies sudo apt-get install -y xvfb x11-xserver-utils imagemagick ``` When using Xvfb, make sure the target application is started inside the same virtual display environment (not needed on machines with a physical display). To control a remote Windows desktop over RDP, see [Desktop environment setup](/platforms/desktop.md#connect-device). ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then write these lines to a `.env` file in your project directory. If you are starting without a project, create a directory and run `pnpm init` in it first. ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Set up the project In the project directory that contains `.env`, verify the model configuration: ```bash pnpm dlx @midscene/test@latest model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). We recommend [Rstest](/sdk/rstest.md) or [Vitest](/sdk/vitest.md) for device tests. The steps below use Vitest; the Rstest guide covers the equivalent setup with the same platform Agents. ### Install dependencies ```bash pnpm add -D vitest dotenv @midscene/computer ``` ### Configure Vitest Create `vitest.config.ts`. If your project already uses Vitest for unit tests, you can save this configuration separately as `vitest.device.config.ts` and pass `--config vitest.device.config.ts` when running device tests, leaving your existing test configuration untouched. ```typescript title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { include: ['e2e/**/*.test.ts'], environment: 'node', testTimeout: 90_000, hookTimeout: 90_000, fileParallelism: false, sequence: { concurrent: false }, }, }); ``` Because model calls and device connections take longer than standard unit tests, adjust `testTimeout` and `hookTimeout` to fit your test cases. When running against a single shared device, disable file parallelism (`fileParallelism: false`) and run tests sequentially (`sequence.concurrent: false`), and avoid `test.concurrent` or `describe.concurrent`. For details, see the Vitest documentation on [fileParallelism](https://vitest.dev/config/fileparallelism), [testTimeout](https://vitest.dev/config/testtimeout), and [hookTimeout](https://vitest.dev/config/hooktimeout). ## Write a test Create `e2e/settings.test.ts`, initializing a new Agent for each test in `beforeEach` and destroying it in `afterEach`: ```typescript title=e2e/settings.test.ts import 'dotenv/config'; import { afterEach, beforeEach, test } from 'vitest'; import { agentForComputer } from '@midscene/computer'; let agent: Awaited<ReturnType<typeof agentForComputer>> | undefined; beforeEach(async () => { agent = await agentForComputer(); }); afterEach(async () => { const currentAgent = agent; agent = undefined; await currentAgent?.destroy(); }); test('scroll through settings', async () => { if (!agent) throw new Error('Agent was not initialized'); await agent.aiWaitFor('The Settings app is visible'); await agent.aiAct('Scroll down one screen'); await agent.aiAssert('The Settings app is still visible'); }); ``` Before running the test, open your system Settings app and bring a scrollable settings page to the foreground. Keep it visible during the test. See the [desktop SDK guide](/sdk/desktop.md) for permissions and connection options. `dotenv/config` loads model settings from the project's `.env` file (settings in the Playground are not automatically shared with test runs). When an `aiAssert` check fails, it throws an error, causing the test runner to mark the test as failed before running `afterEach` to clean up the Agent. You can also extract data from the screen with methods like `aiQuery` and pass the result to the test runner's `expect`. For more interaction and extraction methods, see the [Agent API reference](/reference/index.md#interaction-methods). ## Run the test and inspect the report ```bash pnpm exec vitest run e2e/settings.test.ts ``` Vitest prints the pass or fail status of each test in the terminal, while the Midscene SDK generates an execution report for each Agent under `midscene_run/report/` by default and prints the report path. Open the generated HTML file in a browser to inspect step-by-step screenshots, AI execution details, and assertion results. Unlike Playwright Test, Vitest integration uses the SDK's built-in report generation directly and does not require a custom reporter. Vitest test results and Midscene Agent reports are generated separately; to merge or further process report files, see [Process report files](/consume-report-file.md). When the test passes and the report shows each step with screenshots, your model, environment, and project are all working. ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Look up APIs**: [API reference](/reference.md) lists every Agent method and its options. - **Combine AI calls with code**: [Key APIs](/basics.md#javascript-orchestration) explains when to use `aiAct`, instant actions, and insight APIs. - **Share a device across tests**: [Lifecycle and exclusive device access](/sdk/vitest.md#lifecycle-and-exclusive-device-access) explains how to create and destroy Agents when tests share one device. --- url: /get-started/android-test-chatgpt.md --- > For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt. # Get started: Android · Midscene Test · ChatGPT subscription {#get-started} These are the setup steps for Midscene on **Android** with **Midscene Test** and a **ChatGPT subscription**. To choose another combination, see [all setup paths](/get-started.md#all-setup-paths). ## Install Node.js Install Node.js `^20.19.0 || ^22.12.0 || >=24.0.0`, then check that `node -v` works in your terminal. The commands below use pnpm. If it is not installed yet, run `npm install -g pnpm`. ## Connect the Android device Midscene uses `adb` on your computer to communicate with the target Android device over either USB or wireless `adb`. If `adb` is already installed and your device is connected, skip directly to [Verify the device connection](#verify-device-connection). ### Install adb - Install `adb` via [Android Studio](https://developer.android.com/studio) or the standalone [Android command-line tools](https://developer.android.com/studio#command-line-tools-only). - Run the following command to verify the installation: ```bash adb --version ``` Output similar to the following confirms a working installation: ```log Android Debug Bridge version 1.0.41 Version 34.0.4-10411341 Installed as /usr/local/bin/adb Running on Darwin 24.3.0 (arm64) ``` - Configure the `ANDROID_HOME` environment variable as described in [Android environment variables](https://developer.android.com/tools/variables), then check that it takes effect: ```bash echo $ANDROID_HOME ``` The output should point to your local Android SDK directory, for example: ```log /Users/your_username/Library/Android/sdk ``` ### Enable debugging and connect the device The steps below use a USB connection as an example. If your device is already connected over wireless `adb`, you can keep using that connection. 1. In your phone's **Developer options**, enable **USB debugging** (and **USB debugging (Security settings)** if available, so Midscene can inject touch events). 2. Connect the phone to your computer using a USB cable that supports data transfer. 3. Keep the phone unlocked and accept the **Allow USB debugging** prompt on the screen. ![android usb debug](/images/android-usb-debug-en.png) ### Verify the device connection {#verify-device-connection} Run the following command to check the connection status: ```bash adb devices -l ``` When the device status shows `device`, the connection is ready: ```log List of devices attached s4ey59 device usb:34603008X product:cezanne model:M2006J device:cezan transport_id:3 ``` If multiple devices are connected, note the device ID in the first column (such as `s4ey59` above) so you can select the target device in Playground or your project configuration. If the target device does not appear with the `device` status, check the following: - **Empty list**: For USB, check the data cable (ensure it is not charge-only), USB connection mode, and **USB debugging** toggle; for wireless `adb`, check the network and `adb connect` status. - **`unauthorized`**: Unlock the phone screen and accept the **Allow USB debugging** prompt on the device. - **`offline`**: Reconnect the USB cable or wireless `adb` session, and restart `adb` if needed. Proceed only after the status shows `device`. ## Create a test project ```bash pnpm dlx @midscene/test create my-tests \ --platform android \ --package-manager pnpm cd my-tests ``` The command generates the project files, installs dependencies, and generates the Node Spec. It does not run tests. For the generated files, see [Project structure](/midscene-test/use.md#project-structure). ## Sign in with your ChatGPT subscription First, run the following command in your terminal: ```bash pnpm dlx @midscene/cli model siwc login ``` Follow the terminal instructions to sign in to ChatGPT in your browser and authorize plan usage. You can choose a name for your Agent during authorization. Once authorized, the Agent appears on your ChatGPT usage page. The command saves credentials to `~/.midscene/siwc.json`. Complete this sign-in manually before first use. Then, in the `my-tests` directory, copy `.env.example` to `.env`: ```bash cp .env.example .env ``` Leave `MIDSCENE_MODEL_BASE_URL` and `MIDSCENE_MODEL_API_KEY` empty. Set `MIDSCENE_MODEL_NAME` and `MIDSCENE_MODEL_FAMILY`, and add `MIDSCENE_MODEL_AUTH_MODE`: ```bash MIDSCENE_MODEL_AUTH_MODE="siwc" MIDSCENE_MODEL_NAME="gpt-6-sol" MIDSCENE_MODEL_FAMILY="gpt-6" ``` Available models depend on your ChatGPT account. For credentials and usage, see [Use a ChatGPT subscription](/chatgpt-subscription.md#usage-and-credentials). ## Verify the model and finish setup Verify model connectivity and Midscene compatibility. The command reads `.env` from the current directory and does not need a browser or device: ```bash pnpm exec midscene-test model verify ``` If the check fails, see [Verify model connectivity](/model-config.md#verify-model-connectivity). If more than one device is connected, set `ANDROID_DEVICE_ID` in `.env` to an ID from `adb devices -l`. ## Run the example and inspect the report The example opens React TodoMVC in the device's browser and first checks that the list is empty. Keep the device unlocked. If todos remain from an earlier run, select **All** and delete every todo, including completed ones. ```bash pnpm test ``` The terminal prints the results and a `Report:` path. Open the HTML report, then select a case and a step to inspect screenshots, inputs, outputs, and errors. Reports are written to `midscene_run/report/` by default. When the case passes, your model, environment, and project are all working. For execution options, see [Run tests](/midscene-test/running.md). ## Next steps - **Explore more examples**: [Showcases](/showcases.md) includes demo videos and full execution reports across platforms. - **Test your own app**: In `cases/todo.yaml`, replace the TodoMVC setup in `beforeEach` with a `launch` Node that opens your app: ```yaml beforeEach: - launch: com.example.app cases: - name: Open the home screen steps: - aiAssert: The home screen of the app is visible ``` Use the package name on Android, the bundle identifier on iOS, or the bundle name on HarmonyOS. See [Built-in Nodes across platforms](/midscene-test/builtin-nodes.md) for other system operations. - **Write and organize cases**: [Write YAML cases](/midscene-test/writing.md) covers inputs, variables, tags, and hooks. - **Run in CI**: [Run in GitHub Actions](/midscene-test/running.md#run-in-github-actions).