Midscene.js 官方资源
- 🌐 官方网站 : midscenejs.com
- 📦 GitHub 仓库 : web-infra-dev/midscene
- 🚀 快速开始 : midscenejs.com/zh/quick-start
文章目录
-
- [一、Midscene.js 核心概念](#一、Midscene.js 核心概念)
-
- [🎯 什么是 Midscene.js?](#🎯 什么是 Midscene.js?)
- [🏗️ 两种自动化风格](#🏗️ 两种自动化风格)
- [二、学习路径(4 阶段)](#二、学习路径(4 阶段))
-
- [📖 阶段一:基础入门(1-2 天)](#📖 阶段一:基础入门(1-2 天))
-
- [1. 理解核心概念](#1. 理解核心概念)
- [2. 配置 AI 模型](#2. 配置 AI 模型)
- [3. 零代码体验](#3. 零代码体验)
- [📖 阶段二:Web 自动化(2-3 天)](#📖 阶段二:Web 自动化(2-3 天))
-
- [1. Playwright 集成](#1. Playwright 集成)
- [2. Puppeteer 集成](#2. Puppeteer 集成)
- [3. 桥接模式(控制桌面 Chrome)](#3. 桥接模式(控制桌面 Chrome))
- [4. 在 Playwright 测试中集成](#4. 在 Playwright 测试中集成)
- [📖 阶段三:移动端 & 桌面自动化(3-5 天)](#📖 阶段三:移动端 & 桌面自动化(3-5 天))
-
- [1. Android 自动化](#1. Android 自动化)
- [2. iOS 自动化](#2. iOS 自动化)
- [3. HarmonyOS 自动化](#3. HarmonyOS 自动化)
- [4. PC 桌面自动化](#4. PC 桌面自动化)
- [📖 阶段四:高级特性(3-5 天)](#📖 阶段四:高级特性(3-5 天))
-
- [1. YAML 脚本自动化](#1. YAML 脚本自动化)
- [2. 缓存加速](#2. 缓存加速)
- [3. MCP 集成](#3. MCP 集成)
- [4. 自定义界面集成](#4. 自定义界面集成)
- [5. 多模型配合](#5. 多模型配合)
- 三、开发平台流程
-
- [🔄 完整开发流程](#🔄 完整开发流程)
- [📊 各平台对比](#📊 各平台对比)
- [四、核心 API 速查](#四、核心 API 速查)
-
- [🎮 交互 API](#🎮 交互 API)
- [🔍 数据提取 API](#🔍 数据提取 API)
- [🛠️ 工具 API](#🛠️ 工具 API)
- [⚙️ 构造器参数](#⚙️ 构造器参数)
- 五、常见问题与最佳实践
-
- [⚠️ 元素定位偏移排查](#⚠️ 元素定位偏移排查)
- [🚀 性能优化](#🚀 性能优化)
- [📁 运行产物目录](#📁 运行产物目录)
- 六、学习资源
- 七、总结
一、Midscene.js 核心概念
🎯 什么是 Midscene.js?
Midscene.js 是一个 AI 驱动、视觉感知 的 UI 自动化框架,支持 Web、Android、iOS、HarmonyOS、PC 桌面等全平台。
核心特点:
- ✅ 纯视觉路线:元素定位仅基于截图,不依赖 DOM
- ✅ 自然语言编程:用自然语言描述操作,AI 自动规划执行
- ✅ 跨平台统一 API:一套 API 控制所有平台
- ✅ 多模型支持:Qwen3-VL、Doubao-Seed、Gemini、UI-TARS、AutoGLM 等
- ✅ MCP 集成:将 UI 操作暴露为 MCP 工具,供上层 Agent 调用
🏗️ 两种自动化风格
| 风格 | 方法 | 特点 | 适用场景 |
|---|---|---|---|
| 自动规划 | agent.aiAct() / agent.ai() |
AI 自主规划步骤,智能但较慢 | 复杂流程、探索性任务 |
| 工作流风格 | agent.aiTap(), agent.aiQuery() 等 |
手动控制步骤,快速可靠 | 稳定流程、生产环境 |
二、学习路径(4 阶段)
📖 阶段一:基础入门(1-2 天)
1. 理解核心概念
- 阅读 介绍文档
- 理解纯视觉路线 vs DOM 路线的区别
- 了解自动规划 vs 即时操作的区别
2. 配置 AI 模型
- 阅读 模型策略
- 选择默认模型(推荐:Qwen3-VL 或 Doubao-Seed)
- 配置环境变量:
bash
export MIDSCENE_MODEL_BASE_URL="https://你的模型服务地址/v1"
export MIDSCENE_MODEL_API_KEY="你的 API Key"
export MIDSCENE_MODEL_NAME="模型名称"
export MIDSCENE_MODEL_FAMILY="模型系列"
3. 零代码体验
- 安装 Chrome 插件体验 Web 自动化
- 运行 Android Playground:
npx --yes @midscene/android-playground - 运行 iOS Playground:
npx --yes @midscene/ios-playground - 运行 PC Playground:
npx --yes @midscene/computer-playground
📖 阶段二:Web 自动化(2-3 天)
1. Playwright 集成
typescript
// 安装依赖
npm install @midscene/web playwright @playwright/test tsx --save-dev
// demo.ts
import { chromium } from 'playwright';
import { PlaywrightAgent } from '@midscene/web/playwright';
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.setViewportSize({ width: 1280, height: 768 });
await page.goto('https://www.ebay.com');
const agent = new PlaywrightAgent(page);
await agent.aiAct('type "Headphones" in search box, hit Enter');
await agent.aiWaitFor('there is at least one headphone item on page');
const items = await agent.aiQuery(
'{itemTitle: string, price: Number}[], find item in list and corresponding price'
);
console.log('headphones in stock', items);
await agent.aiAssert('There is a category filter on the left');
await browser.close();
2. Puppeteer 集成
typescript
import puppeteer from 'puppeteer';
import { PuppeteerAgent } from '@midscene/web/puppeteer';
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.bing.com');
const agent = new PuppeteerAgent(page);
await agent.ai('type "weather" and hit Enter');
3. 桥接模式(控制桌面 Chrome)
typescript
import { AgentOverChromeBridge } from '@midscene/web/bridge-mode';
const agent = new AgentOverChromeBridge();
await agent.connectNewTabWithUrl('https://www.bing.com');
await agent.ai('type "AI 101" and hit Enter');
await agent.aiAssert('there are some search results');
await agent.destroy();
4. 在 Playwright 测试中集成
typescript
// playwright.config.ts
export default defineConfig({
timeout: 90 * 1000,
reporter: [["list"], ["@midscene/web/playwright-reporter", { type: "merged" }]],
});
📖 阶段三:移动端 & 桌面自动化(3-5 天)
1. Android 自动化
前置准备:
- 安装 adb 并设置
ANDROID_HOME - 开启 USB 调试
- 验证连接:
adb devices -l
typescript
import { AndroidAgent, AndroidDevice, getConnectedDevices } from '@midscene/android';
const devices = await getConnectedDevices();
const device = new AndroidDevice(devices[0].udid);
const agent = new AndroidAgent(device, {
aiActionContext: 'If any popup appears, click agree. If login page pops up, close it.'
});
await device.connect();
await agent.aiAct('open browser and navigate to ebay.com');
await agent.aiAct('type "Headphones" in search box, hit Enter');
await agent.aiWaitFor('There is at least one headphone product');
const items = await agent.aiQuery(
'{itemTitle: string, price: Number}[], find item in list and corresponding price'
);
console.log('headphones in stock', items);
2. iOS 自动化
前置准备:
- macOS + Xcode
- 配置 WebDriverAgent(版本 >= 7.0.0)
- 验证 WDA:访问
http://localhost:8100/status
typescript
import { IOSAgent, IOSDevice, agentFromWebDriverAgent } from '@midscene/ios';
// 方式一:直接创建设备
const page = new IOSDevice({ wdaPort: 8100, wdaHost: 'localhost' });
const agent = new IOSAgent(page, {
aiActionContext: 'If any popup appears, click agree.'
});
await page.connect();
// 方式二:使用便捷函数(推荐)
// const agent = await agentFromWebDriverAgent({ wdaPort: 8100, wdaHost: 'localhost' });
await agent.aiAct('open Safari and navigate to ebay.com');
await agent.aiAct('type "Headphones" in search box, hit Enter');
3. HarmonyOS 自动化
前置准备:
- 安装 HDC(通过 DevEco Studio 或命令行工具)
- 开启开发者模式和 USB 调试
- 验证连接:
hdc list targets
typescript
import { HarmonyAgent, HarmonyDevice, getConnectedDevices } from '@midscene/harmony';
const devices = await getConnectedDevices();
const device = new HarmonyDevice(devices[0].deviceId, {});
const agent = new HarmonyAgent(device, {
aiActionContext: '这是一台鸿蒙设备,系统语言为中文。如果出现弹窗,点击同意或关闭。'
});
await device.connect();
await agent.launch('com.huawei.hmos.settings');
await agent.aiAct('scroll down one screen');
const items = await agent.aiQuery('string[], 列表中的项目');
console.log('列表项目:', items);
4. PC 桌面自动化
前置准备:
- macOS:授予辅助功能权限
- Linux:安装 ImageMagick
- 无头 Linux:安装 Xvfb
typescript
import { agentForComputer } from '@midscene/computer';
const agent = await agentForComputer({
aiActionContext: '你正在控制一台桌面计算机。'
});
const screenInfo = await agent.aiQuery('{width: number, height: number}, 获取屏幕分辨率');
console.log('屏幕分辨率:', screenInfo);
await agent.aiAct('将鼠标移动到屏幕中心');
await agent.aiAssert('屏幕有可见内容');
📖 阶段四:高级特性(3-5 天)
1. YAML 脚本自动化
yaml
# bing-search.yaml
web:
url: https://www.bing.com
tasks:
- name: 搜索天气
flow:
- ai: 搜索 "今日天气"
- sleep: 3000
- aiAssert: 结果显示天气信息
bash
# 安装 CLI
npm i -g @midscene/cli
# 运行脚本
midscene ./bing-search.yaml
# 批量运行
midscene './scripts/**/*.yaml'
# 并发运行
midscene './scripts/**/*.yaml' --concurrent 3
Android YAML 示例:
yaml
android:
deviceId: s4ey59
tasks:
- name: 地图导航
flow:
- ai: 打开地图应用
- ai: 在搜索栏输入 "杭州西湖",然后点击搜索按钮
- ai: 点击第一个搜索结果,进入详情页
- ai: 点击 "路线" 按钮,进入路线规划页面
- ai: 点击 "开始" 按钮开始导航
iOS YAML 示例:
yaml
ios:
wdaPort: 8100
tasks:
- name: 修改系统设置
flow:
- ai: 打开设置应用
- ai: 点击 "显示与亮度"
- ai: 开启 "深色模式"
- aiAssert: 深色模式已开启
2. 缓存加速
typescript
// 读写模式(默认)
const agent = new PlaywrightAgent(page, {
cache: { id: "my-cache-id" }
});
// 只读模式(生产环境推荐)
const agent = new PlaywrightAgent(page, {
cache: { strategy: "read-only", id: "my-cache-id" }
});
await agent.flushCache(); // 手动写入缓存
// 只写模式(建立缓存)
const agent = new PlaywrightAgent(page, {
cache: { strategy: "write-only", id: "my-cache-id" }
});
// 禁用缓存
const agent = new PlaywrightAgent(page, { cache: false });
YAML 缓存配置:
yaml
agent:
cache:
id: "my-cache-test"
strategy: "read-write"
3. MCP 集成
Web Bridge MCP:
json
{
"mcpServers": {
"midscene-web": {
"command": "npx",
"args": ["-y", "@midscene/web-bridge-mcp"],
"env": {
"MIDSCENE_MODEL_BASE_URL": "你的模型服务地址",
"MIDSCENE_MODEL_API_KEY": "你的 API Key",
"MIDSCENE_MODEL_NAME": "模型名称",
"MIDSCENE_MODEL_FAMILY": "模型系列",
"MCP_SERVER_REQUEST_TIMEOUT": "600000"
}
}
}
}
iOS MCP :@midscene/ios-mcp
Android MCP :@midscene/android-mcp
Computer MCP :@midscene/computer-mcp
MCP 工具列表:
web_connect/ios_connect/android_connect/computer_connecttake_screenshotassert- 设备操作(Tap, Scroll, Input 等)
4. 自定义界面集成
实现 AbstractInterface 控制任意界面(IoT、车载、内部应用等):
typescript
import type { DeviceAction, Size } from '@midscene/core';
import { defineActionTap, defineActionInput } from '@midscene/core/device';
export class SampleDevice implements AbstractInterface {
interfaceType = 'sample-device';
async screenshotBase64(): Promise<string> {
// 实现截图逻辑
return 'data:image/png;base64,...';
}
async size(): Promise<Size> {
return { width: 1920, height: 1080 };
}
actionSpace(): DeviceAction[] {
return [
defineActionTap(async (param) => {
// 实现点击逻辑
await this.performTap(param.locate.center[0], param.locate.center[1]);
}),
defineActionInput(async (param) => {
// 实现输入逻辑
await this.performInput(param.locate.center[0], param.locate.center[1], param.value);
}),
];
}
}
5. 多模型配合
typescript
const agent = new PuppeteerAgent(page, {
modelConfig: {
// 默认模型(元素定位)
MIDSCENE_MODEL_NAME: 'qwen3-vl-plus',
MIDSCENE_MODEL_API_KEY: '***',
MIDSCENE_MODEL_BASE_URL: '...',
MIDSCENE_MODEL_FAMILY: 'qwen3-vl',
// Planning 模型(任务规划)
MIDSCENE_PLANNING_MODEL_NAME: 'gpt-5.1',
MIDSCENE_PLANNING_MODEL_API_KEY: '***',
MIDSCENE_PLANNING_MODEL_BASE_URL: '...',
MIDSCENE_PLANNING_MODEL_FAMILY: 'gpt-5',
// Insight 模型(数据提取/断言)
MIDSCENE_INSIGHT_MODEL_NAME: 'qwen-vl-plus',
MIDSCENE_INSIGHT_MODEL_API_KEY: '***',
MIDSCENE_INSIGHT_MODEL_FAMILY: 'qwen2.5-vl'
}
});
三、开发平台流程
🔄 完整开发流程
1. 环境准备
├── 安装 Node.js (>= 18.19.0)
├── 配置 AI 模型环境变量
└── 安装平台依赖 (adb / Xcode+WebDriverAgent / HDC / 辅助功能权限)
2. 快速验证
├── 运行 Playground 验证设备连接
├── 测试截图功能
└── 执行简单操作(点击、输入)
3. 脚本开发
├── 方式一:JavaScript SDK
│ ├── 安装依赖 (@midscene/web | @midscene/android | @midscene/ios | ...)
│ ├── 编写 Agent 脚本
│ └── 运行测试 (npx tsx demo.ts)
│
├── 方式二:YAML 脚本
│ ├── 安装 CLI (@midscene/cli)
│ ├── 编写 YAML 脚本
│ └── 运行 (midscene ./script.yaml)
│
└── 方式三:MCP 集成
├── 配置 MCP 服务器
└── 通过上层 Agent 调用
4. 调试优化
├── 查看可视化报告 (midscene_run/report/*.html)
├── 启用缓存加速调试
├── 优化提示词(使用视觉特征描述)
├── 调整截图缩放因子 (screenshotShrinkFactor)
└── 使用即时操作替代自动规划(提高稳定性)
5. 生产部署
├── 使用只读缓存策略
├── 集成到测试框架 (Playwright / Vitest)
├── 配置 CI/CD 流程
└── 监控执行成功率和性能
📊 各平台对比
| 维度 | Web | Android | iOS | HarmonyOS | PC 桌面 |
|---|---|---|---|---|---|
| 依赖 | Playwright/Puppeteer | adb | Xcode + WebDriverAgent | HDC + DevEco | libnut-core |
| 系统要求 | 任意 OS | 任意 OS | macOS 必需 | 任意 OS | macOS/Linux/Windows |
| 连接方式 | 浏览器自动化 | ADB 协议 | WebDriverAgent (HTTP) | HDC 协议 | 原生 API |
| 真机支持 | ✅ | ✅ | ✅ | ✅ | ✅ (本机) |
| 模拟器支持 | ✅ | ✅ | ✅ | ✅ | ❌ |
| Playground | ✅ Chrome 插件 | ✅ | ✅ | ✅ | ✅ |
| MCP 支持 | ✅ web-bridge-mcp | ✅ android-mcp | ✅ ios-mcp | ❌ | ✅ computer-mcp |
| YAML 支持 | ✅ | ✅ | ✅ | ✅ | ✅ |
四、核心 API 速查
🎮 交互 API
| 方法 | 说明 | 类型 |
|---|---|---|
agent.aiAct(prompt) |
自动规划并执行 | 自动规划 |
agent.ai(prompt) |
aiAct 的简写 |
自动规划 |
agent.aiTap(description) |
点击元素 | 即时操作 |
agent.aiHover(description) |
悬停元素 | 即时操作 |
agent.aiInput(value, description) |
输入文本 | 即时操作 |
agent.aiClearInput(description) |
清空输入 | 即时操作 |
agent.aiKeyboardPress(key) |
按键 | 即时操作 |
agent.aiScroll(direction) |
滚动 | 即时操作 |
agent.aiPinch(scale) |
捏合 | 即时操作 |
agent.aiLongPress(description) |
长按 | 即时操作 |
agent.aiDoubleClick(description) |
双击 | 即时操作 |
agent.aiRightClick(description) |
右键 | 即时操作 |
🔍 数据提取 API
| 方法 | 说明 | 返回值 |
|---|---|---|
agent.aiQuery(demand) |
提取结构化数据 | JSON |
agent.aiAsk(question) |
提问 | string |
agent.aiBoolean(question) |
提取布尔值 | boolean |
agent.aiNumber(question) |
提取数字 | number |
agent.aiString(question) |
提取字符串 | string |
agent.aiLocate(description) |
定位元素坐标 | { center: [x, y], rect: {...} } |
🛠️ 工具 API
| 方法 | 说明 |
|---|---|
agent.aiAssert(assertion) |
AI 断言,不满足则抛错 |
agent.aiWaitFor(condition) |
等待条件满足 |
agent.flushCache() |
手动写入缓存 |
agent.destroy() |
销毁 Agent,释放资源 |
⚙️ 构造器参数
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
generateReport |
boolean | true | 是否生成报告 |
reportFileName |
string | 自动生成 | 报告文件名 |
cache |
false / {id, strategy} | false | 缓存配置 |
aiActContext |
string | '' | AI 背景知识 |
replanningCycleLimit |
number | 20 | 最大重规划次数 |
waitAfterAction |
number | 300 | 动作后等待时间 (ms) |
screenshotShrinkFactor |
number | 1 | 截图缩放比例 |
outputFormat |
'single-html' / 'html-and-external-assets' | 'single-html' | 报告格式 |
modelConfig |
Record<string, string> | - | 自定义模型配置 |
五、常见问题与最佳实践
⚠️ 元素定位偏移排查
-
升级到最新版本
-
使用更好的视觉模型(Qwen3-VL > Qwen2.5-VL,plus > flash)
-
检查
MIDSCENE_MODEL_FAMILY配置是否正确 -
优化提示词 :
typescript// ❌ 功能性描述 await agent.aiTap('个人中心'); // ✅ 视觉特征描述 await agent.aiTap('人形头像 icon'); // ✅ 结合位置信息 await agent.aiTap('页面右上角的人形头像图标'); -
开启
deepLocate:typescriptawait agent.aiTap('搜索按钮', { deepLocate: true });
🚀 性能优化
- 使用即时操作 替代自动规划(
aiTapvsai) - 降低截图分辨率 (设置
screenshotShrinkFactor: 2) - 使用缓存加速调试
- 更换更快的模型服务
- Web 页面设置
deviceScaleFactor: 2提高清晰度
📁 运行产物目录
midscene_run/
├── report/ # 测试报告 (HTML)
├── log/ # 调试日志
└── cache/ # 缓存文件 (.cache.yaml)
可通过 MIDSCENE_RUN_DIR 环境变量自定义路径。
六、学习资源
| 资源 | 链接 |
|---|---|
| 官方文档 | https://midscenejs.com/zh |
| GitHub 仓库 | GitHub - web-infra-dev/midscene: AI-powered, vision-driven UI automation for every platform. |
| 示例项目 | GitHub - web-infra-dev/midscene-example: Examples for midscene |
| API 参考 | https://midscenejs.com/zh/api.html |
| Chrome 插件 | Chrome 应用商店搜索 "Midscene" |
| Discord 社区 | https://discord.gg/2JyBHxszE4 |
| 飞书交流群 | 文档中有二维码 |
七、总结
Midscene.js 提供了一套统一的 AI 驱动 UI 自动化方案,核心优势:
- 纯视觉路线:不依赖 DOM,适用于任意界面(Web/App/桌面/IoT/车载)
- 自然语言编程:降低自动化门槛,新人快速上手
- 跨平台统一:一套 API 控制所有平台
- 灵活集成:JavaScript SDK / YAML / MCP / 自定义界面
- 完善的调试体验:可视化报告 + Playground + Chrome 插件
推荐学习顺序:
基础概念 → 模型配置 → Web 自动化 → 移动端自动化 → YAML 脚本 → MCP 集成 → 自定义界面
祝你学习顺利!🎉