diff --git a/.github/workflows/screen-relay.yml b/.github/workflows/screen-relay.yml new file mode 100644 index 00000000..e6909f6c --- /dev/null +++ b/.github/workflows/screen-relay.yml @@ -0,0 +1,83 @@ +name: Screen Relay desktop + +on: + pull_request: + paths: + - 'packages/screen-relay/**' + - 'packages/shared/utils/**' + - '.github/workflows/screen-relay.yml' + - 'pnpm-lock.yaml' + push: + branches: [main] + paths: + - 'packages/screen-relay/**' + - 'packages/shared/utils/**' + - '.github/workflows/screen-relay.yml' + - 'pnpm-lock.yaml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + desktop: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: '22' + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm --filter @midscene/screen-relay... -r build + - name: Install the publishable tarball in a clean project + working-directory: packages/screen-relay + run: | + pnpm --dir ../shared/utils pack --pack-destination "$RUNNER_TEMP" + pnpm pack --pack-destination "$RUNNER_TEMP" + consumer="$RUNNER_TEMP/relay-consumer" + mkdir -p "$consumer" + npm install --prefix "$consumer" --no-audit --no-fund "$RUNNER_TEMP"/midscene-{robotics-shared,screen-relay}-*.tgz + cli="$consumer/node_modules/.bin/midscene-screen-relay" + "$cli" --help + echo "SCREEN_RELAY_TEST_CLI=$cli" >> "$GITHUB_ENV" + - name: Start the X11 virtual desktop + working-directory: packages/screen-relay + run: | + relay=./node_modules/.bin/screen-relay + "$relay" install --backend x11 --desktop none --yes + url=http://127.0.0.1:18080 + if ! output=$(SCREEN_RELAY_RESOLUTION=1280x720 "$relay" up -d --backend x11 --desktop none --port 18080 --allow-origin "$url" --yes 2>&1); then + printf '%s\n' "$output" | sed -E 's/[[:xdigit:]]{64}/[redacted]/g' >&2 + exit 1 + fi + pattern='#token=([[:xdigit:]]{64})' + [[ $output =~ $pattern ]] || { echo 'Missing relay session token'; exit 1; } + token=${BASH_REMATCH[1]} + echo "::add-mask::$token" + echo "MIDSCENE_SCREEN_RELAY_URL=$url/#token=$token" >> "$GITHUB_ENV" + - name: Test desktop actions and configured visual model + run: pnpm --filter @midscene/screen-relay test:desktop + env: + # Ark IPv4 connections from GitHub runners can take longer than Node's default 250 ms. + NODE_OPTIONS: ${{ env.NODE_OPTIONS }} --network-family-autoselection-attempt-timeout=2000 + MIDSCENE_RUN_DIR: ${{ runner.temp }}/midscene_run + MIDSCENE_MODEL_API_KEY: ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && secrets.MIDSCENE_MODEL_API_KEY || '' }} + MIDSCENE_MODEL_BASE_URL: ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && secrets.MIDSCENE_MODEL_BASE_URL || '' }} + MIDSCENE_MODEL_NAME: ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && secrets.MIDSCENE_MODEL_NAME || '' }} + MIDSCENE_MODEL_FAMILY: ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && secrets.MIDSCENE_MODEL_FAMILY || '' }} + - name: Upload AI report + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: screen-relay-ai-report + path: ${{ runner.temp }}/midscene_run/report/*.html + if-no-files-found: ignore + retention-days: 7 + - name: Stop desktop + if: always() + run: pnpm --filter @midscene/screen-relay exec screen-relay down diff --git a/AGENTS.md b/AGENTS.md index ea4c0cca..4a461e41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,7 @@ # AGENTS.md - Use the Node.js and pnpm versions specified in the root `package.json`. See [CONTRIBUTING.md](./CONTRIBUTING.md) for development commands and package boundaries. +- Use Rslib to build new workspace packages and Rstest to run their tests. - Build affected workspace packages and their dependencies before running tests. Tests consume compiled output. - Keep tests minimal and focused on observable behavior. Avoid redundant coverage, assertions tied to implementation details, and unnecessary complexity. - Follow [.github/pull_request_template.md](./.github/pull_request_template.md) when drafting PR descriptions, and verify each applicable checklist item before checking it off. diff --git a/README.md b/README.md index 631e5550..2bd400f6 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Automate physical touchscreens (car cockpits, industrial panels) via a robotic a - + @@ -77,6 +77,16 @@ With [esp32-iphone-agent](https://github.com/onehumanbeing/esp32-iphone-agent), [Set up the board and run your first test →](./packages/ios-esp32/README.md) +### 🖥️ Screen Relay × Remote Desktop + +Midscene Connect uses [screen-relay](https://github.com/vercel-labs/screen-relay) to control local, remote, or virtual desktops across Windows, macOS, and Linux. In this demo on a remote Windows desktop, the agent creates `README.txt`, writes a URL in Notepad, then checks the filename and the full URL. + + + +
+ +[Connect a remote desktop and run your first test →](./packages/screen-relay/README.md) + ### 🤝 Showcase your solution We warmly welcome community contributions of successful integrations across different devices and scenarios! If you have built an alternative hardware solution, connectivity protocol, or unique platform practice, feel free to [open an issue](https://github.com/web-infra-dev/midscene-test-everything/issues/new) to let us know. We would love to feature and link your project right here for the community to see. @@ -168,6 +178,7 @@ iOS AirLink and the MG400 service host many devices. Each one is at `http:// - + @@ -75,6 +75,16 @@ [配置开发板并运行第一个测试 →](./packages/ios-esp32/README.zh.md) +### 🖥️ Screen Relay × 远程桌面 + +Midscene Connect 通过 [screen-relay](https://github.com/vercel-labs/screen-relay) 操作 Windows、macOS 或 Linux 上的本机、远程与虚拟桌面。在这个远程 Windows 桌面演示中,Agent 新建 `README.txt`,在记事本里写入网址,再核对文件名和完整网址。 + + + +
+ +[连接远程桌面并运行第一个测试 →](./packages/screen-relay/README.zh.md) + ### 🤝 欢迎贡献你的成功案例 我们非常欢迎社区贡献更多不同设备与场景的成功接入实践!如果你有其他优秀的硬件方案、连接协议或独特平台的实战经验,欢迎[提交 Issue](https://github.com/web-infra-dev/midscene-test-everything/issues/new) 告诉我们。我们会把你的方案链接展示在这个版块,让更多开发者看到你的精彩实践。 @@ -164,7 +174,8 @@ iOS AirLink 与 MG400 服务会同时托管多台设备,每台设备的地址 | --- | --- | | [`mg400-service`](./packages/robot-arm/mg400-service/README.zh.md) | DOBOT MG400 设备服务,提供配置、校准和触屏操作 | | [`arm-kit`](./packages/robot-arm/arm-kit/README.zh.md) | 机械臂适配器接口,可用于接入自定义机械臂 | -| [`ios-airlink`](./packages/ios-airlink/README.md) | 在 macOS 上连接和控制 iPhone 真机 | +| [`screen-relay`](./packages/screen-relay/README.zh.md) | 通过 Midscene Connect 操作本机、远程或虚拟桌面 | +| [`ios-airlink`](./packages/ios-airlink/README.zh.md) | 在 macOS 上连接和控制 iPhone 真机 | | [`ios-esp32`](./packages/ios-esp32/README.zh.md) | 基于 `esp32-iphone-agent` 硬件板子在 iPhone 真机上运行 Midscene E2E 测试 | | [`robotics-vision`](./packages/shared/vision/README.zh.md) | 跨平台摄像头采集、ArUco 屏幕标定与透视校正 | @@ -177,6 +188,7 @@ iOS AirLink 与 MG400 服务会同时托管多台设备,每台设备的地址 - 特别感谢来自社区的贡献者 [阿维塔科技 Robotic 团队](https://www.avatr.com):主导研发了机械臂物理触屏自动化方案的核心架构、相机标定与运动控制能力,并在真实车载座舱测试场景中完成了全面落地验证。 - iOS AirLink 的部分蓝牙 HID 描述符改编自 [iphone-use](https://github.com/xhoantran/iphone-use)。 - `ios-esp32` 的底层设备能力,包括屏幕采集与蓝牙 HID 控制,均来自开源项目 [esp32-iphone-agent](https://github.com/onehumanbeing/esp32-iphone-agent)。 +- `@midscene/screen-relay` 的底层桌面截图与键鼠控制能力来自开源项目 [screen-relay](https://github.com/vercel-labs/screen-relay)。 ## 📖 许可证 diff --git a/packages/ios-esp32/package.json b/packages/ios-esp32/package.json index 436276b5..92d3c69c 100644 --- a/packages/ios-esp32/package.json +++ b/packages/ios-esp32/package.json @@ -34,8 +34,8 @@ "dependencies": { "@clack/prompts": "^0.11.0", "@midscene/connect": "1.19.0", + "@midscene/robotics-shared": "workspace:*", "chalk": "5.6.2", - "commander": "13.1.0", "execa": "8.0.1" }, "devDependencies": { diff --git a/packages/ios-esp32/src/commands.ts b/packages/ios-esp32/src/commands.ts index 9bfadbb2..441567e0 100644 --- a/packages/ios-esp32/src/commands.ts +++ b/packages/ios-esp32/src/commands.ts @@ -1,31 +1,28 @@ #!/usr/bin/env node -import { serveDevice } from '@midscene/connect/server'; -import chalk, { chalkStderr } from 'chalk'; -import { Command } from 'commander'; +import { + createConnectCommand, + reportCliError, + serveConnectCli, +} from '@midscene/robotics-shared/connect-cli'; +import chalk from 'chalk'; import esp32Device from './device.js'; import { getBoardIdentity, resolveDevice } from './esp32agent.js'; async function main() { - const values = new Command() - .name('ios-esp32') - .description('Connect an iPhone to Midscene through an ESP32 board') + const values = createConnectCommand( + 'ios-esp32', + 'Connect an iPhone to Midscene through an ESP32 board', + ) .option( '--device ', 'Board ID (also ESP32AGENT_DEVICE); omit to discover boards', ) - .option('--host ', 'Listen address', '127.0.0.1') - .option('--port ', 'Listen port', Number, 5820) - .option( - '--token ', - 'Bearer token for API access (generated automatically on non-loopback hosts)', - ) .option( '--stale-retry-ms ', 'Additional screenshot retry time in milliseconds', Number, 10_000, ) - .allowExcessArguments(false) .parse() .opts<{ device?: string; @@ -35,48 +32,16 @@ async function main() { staleRetryMs: number; }>(); - if (values.token !== undefined && !values.token.trim()) { - throw new Error('Token must not be empty.'); - } - const board = await resolveDevice(values.device); - const served = await serveDevice(esp32Device, { + await serveConnectCli(esp32Device, { host: values.host, port: values.port, token: values.token, options: { device: board.id, staleRetryMs: values.staleRetryMs }, }); - const { url, token } = served; - - const stop = () => { - served.close().finally(() => process.exit(0)); - }; - process.once('SIGINT', stop); - process.once('SIGTERM', stop); - const interactive = process.stdout.isTTY; - const row = (label: string, value: string) => - ` ${chalk.dim(label.padEnd(9))}${value}`; - - if (interactive) { - console.log( - `\n ${chalk.bold('Midscene Connect')}\n ${chalk.bold.cyan(url)}\n`, - ); - console.log(row('Docs', chalk.underline(`${url}/api/docs/`))); - console.log( - row( - 'Token', - token ? chalk.yellow(token) : chalk.dim('Not required on localhost'), - ), - ); - } else { - console.log(`Connect URL: ${url}`); - console.log(`API docs: ${url}/api/docs/`); - console.log(`Connect token: ${token ?? 'not required (loopback)'}`); - } - const info = board.name ? board : await getBoardIdentity(board.id).catch(() => undefined); @@ -85,14 +50,10 @@ async function main() { .filter(Boolean) .join(interactive ? chalk.dim(' · ') : ' · '); console.log( - interactive ? `\n${row('Device', identity)}\n` : `Device: ${identity}`, + interactive + ? `\n ${chalk.dim('Device ')}${identity}\n` + : `Device: ${identity}`, ); } -main().catch((error: unknown) => { - const message = error instanceof Error ? error.message : String(error); - console.error( - message.replace(/`[^`\n]+`/g, (command) => chalkStderr.cyan(command)), - ); - process.exitCode = 1; -}); +main().catch(reportCliError); diff --git a/packages/screen-relay/README.md b/packages/screen-relay/README.md new file mode 100644 index 00000000..aafe03d8 --- /dev/null +++ b/packages/screen-relay/README.md @@ -0,0 +1,118 @@ +

+ Midscene Test Everything
+

+ +

Screen Relay

+ +

+ Test local, remote, or virtual desktop apps with Midscene
+ Connects a desktop to Midscene's GUI Agent through Midscene Connect, using screen-relay to capture screenshots and send mouse and keyboard input. +

+ +

+ Midscene Test Everything · + English / 简体中文 +

+ + + +
+ +## 🔌 How it works + +```text +Test machine / CI Target desktop (local / remote / virtual) + +---------------------------------------+ +Midscene GUI Agent | | + | Midscene Connect | | + v | | +@midscene/screen-relay --- mouse & keyboard -->| screen-relay <--> desktop app | + <-- screenshots --------| | + +---------------------------------------+ +``` + +## 📋 Requirements + +- **Desktop under test**: Linux, macOS, or Windows with Node.js `22+` and the app you want to test (or a headless Linux virtual desktop in CI). Run `npx screen-relay install --yes` on this machine once to install the desktop components. On macOS, grant screen recording and accessibility permissions to the terminal. +- **Test machine**: Node.js `22.12+` (22.x) or `24+`. To run Agent scripts, configure a vision model in your test project's `.env` file (see [Model setup](https://midscenejs.com/model-api-setup)). + +## ⚡ Quick start + +### 1. Share the desktop + +```sh +npx screen-relay up -d +``` + +On the same machine, use the full **Viewer URL** printed in the terminal. For testing from another machine, see [Remote access](https://screen-relay.dev/docs/remote-access). + +### 2. Start Midscene Connect on the test machine + +Replace `` with the full **Viewer URL** from step 1 and run the command below. + +```sh +npx @midscene/screen-relay --relay-url "" +``` + +Leave the service running. Copy the **Connect URL** from the terminal into your test script. + +To preview the desktop in Playground, replace `` with the printed **Connect URL** and run this command in another terminal. + +```sh +npx @midscene/connect playground --url "" +``` + +
+Optional settings + +- In CI or a shared shell, supply the Viewer URL through the `MIDSCENE_SCREEN_RELAY_URL` environment variable and omit `--relay-url` to keep the desktop access token out of shell history. +- Connect listens on `127.0.0.1:5820` by default. Use `--host` and `--port` to change the address and port. +- Use `--token` to set the Connect API bearer token. On non-loopback addresses, Connect generates and prints this token by default. + +
+ +
+Run from a repository checkout + +See the [contributing guide](../../CONTRIBUTING.md) to set up pnpm, then build and run from the repo root: + +```sh +pnpm install --frozen-lockfile +pnpm --filter @midscene/screen-relay... -r build +pnpm --filter @midscene/screen-relay exec midscene-screen-relay --relay-url "" +``` + +
+ +## 🧪 Run a test + +Open a browser on the desktop under test. In your test project, run `npm install @midscene/connect` and save the script as `desktop-test.mjs`. + +```js +import { agentOverConnectProtocol } from '@midscene/connect'; + +const agent = await agentOverConnectProtocol({ + url: 'http://127.0.0.1:5820', + // token: process.env.MIDSCENE_CONNECT_TOKEN, // required when listening on a non-loopback host +}); +try { + await agent.aiAct('Click the browser address bar, enter https://example.com and press Enter'); + await agent.aiAssert('The page displays the heading Example Domain'); +} finally { + await agent.destroy(); +} +``` + +```sh +node --env-file=.env desktop-test.mjs +``` + +Press Ctrl+C in the adapter terminal to close the Connect service. Run `npx screen-relay down` on the desktop to stop sharing it. + +## 🛠️ Troubleshooting + +| Symptom | What to check | +| --- | --- | +| Screenshots work, but input fails with `Another controller holds control` or `A viewer took control` | A viewer can take control automatically when the desktop is idle. Select **Release control** in the viewer or close it, then retry. | +| A Mac shows a black screen or ignores input | In **System Settings → Privacy & Security** on the Mac under test, grant screen recording and accessibility permissions to the terminal running the relay, then restart the relay. | +| Text input fails with a clipboard error | When clipboard access is available, Windows prefers pasting all text. Other desktops prefer pasting non-ASCII text when IME support is unavailable. Only plain text is backed up and restored. Check that the clipboard is accessible and that both its existing text and the text to paste are each at most 256 KiB in UTF-8. | diff --git a/packages/screen-relay/README.zh.md b/packages/screen-relay/README.zh.md new file mode 100644 index 00000000..3c4dfe0a --- /dev/null +++ b/packages/screen-relay/README.zh.md @@ -0,0 +1,118 @@ +

+ Midscene Test Everything
+

+ +

Screen Relay

+ +

+ 用 Midscene 测试本机、远程或虚拟桌面应用
+ 底层基于 screen-relay 获取桌面截图、发送键鼠输入,并通过 Midscene Connect 接入 Midscene GUI Agent。 +

+ +

+ Midscene Test Everything · + English / 简体中文 +

+ + + +
+ +## 🔌 工作原理 + +```text +测试机 / CI 被测桌面(本机 / 远程 / 虚拟桌面) + +----------------------------------+ +Midscene GUI Agent | | + | Midscene Connect | | + v | | +@midscene/screen-relay --- 键鼠指令 ---------->| screen-relay <--> 桌面应用 | + <-- 屏幕截图 -----------| | + +----------------------------------+ +``` + +## 📋 环境准备 + +- **被测桌面**:Linux、macOS 或 Windows,安装 Node.js `22+` 和被测应用(也可用于 CI 中的无头 Linux 虚拟桌面)。首次在被测机器上运行 `npx screen-relay install --yes` 安装桌面组件。macOS 还需为终端授予录屏和辅助功能权限。 +- **测试机**:安装 Node.js `22.12+`(22.x)或 `24+`。运行 Agent 脚本时,在测试项目的 `.env` 中配置视觉模型,详见[模型配置指南](https://midscenejs.com/zh/model-api-setup)。 + +## ⚡ 快速开始 + +### 1. 在被测桌面启动共享 + +```sh +npx screen-relay up -d +``` + +同机测试时,直接使用终端打印的完整 **Viewer URL**。跨机测试请参考 [screen-relay 远程访问文档](https://screen-relay.dev/docs/remote-access)。 + +### 2. 在测试机上启动 Midscene Connect + +将 `` 替换为上一步的完整 **Viewer URL**,运行以下命令。 + +```sh +npx @midscene/screen-relay --relay-url "" +``` + +保持服务运行。将终端打印的 **Connect URL** 填入测试脚本。 + +要在 Playground 中预览桌面,请将 `` 替换为上面的 **Connect URL**,再在另一个终端运行以下命令。 + +```sh +npx @midscene/connect playground --url "" +``` + +
+可选配置 + +- 在 CI 或共享终端中,可通过环境变量 `MIDSCENE_SCREEN_RELAY_URL` 传入 Viewer URL,省去 `--relay-url`,避免桌面访问令牌留在命令历史中。 +- Connect 默认监听 `127.0.0.1:5820`。可用 `--host` 和 `--port` 修改监听地址和端口。 +- 用 `--token` 设置 Connect API 的访问令牌。监听非回环地址时,Connect 默认生成并打印该令牌。 + +
+ +
+从本地仓库源码运行 + +参考[贡献指南](../../CONTRIBUTING.md)配置好 pnpm 后,在仓库根目录构建并运行: + +```sh +pnpm install --frozen-lockfile +pnpm --filter @midscene/screen-relay... -r build +pnpm --filter @midscene/screen-relay exec midscene-screen-relay --relay-url "" +``` + +
+ +## 🧪 运行测试 + +在被测桌面打开浏览器。在测试项目运行 `npm install @midscene/connect`,将以下脚本保存为 `desktop-test.mjs`。 + +```js +import { agentOverConnectProtocol } from '@midscene/connect'; + +const agent = await agentOverConnectProtocol({ + url: 'http://127.0.0.1:5820', + // token: process.env.MIDSCENE_CONNECT_TOKEN, // 监听非回环地址时传入终端打印的 Token +}); +try { + await agent.aiAct('点击浏览器地址栏,输入 https://example.com 并回车'); + await agent.aiAssert('网页正文中显示了 Example Domain 标题'); +} finally { + await agent.destroy(); +} +``` + +```sh +node --env-file=.env desktop-test.mjs +``` + +测试结束后,在适配器终端按 Ctrl+C 关闭 Connect 服务。在被测桌面运行 `npx screen-relay down` 停止共享。 + +## 🛠️ 故障排查 + +| 现象 | 检查方法 | +| --- | --- | +| 有截图,但键鼠操作报 `Another controller holds control` 或 `A viewer took control` | 检查是否有 Viewer 持有控制权。空闲时打开 Viewer 也可能自动取得控制权,点击 **Release control** 或关闭页面后重试。 | +| macOS 上画面黑屏或输入无响应 | 在被测 Mac 的「系统设置 → 隐私与安全性」中,给启动 relay 的终端授予录屏和辅助功能权限,然后重启 relay。 | +| 文本输入报剪贴板错误 | 支持剪贴板时,Windows 优先粘贴所有文本。其他桌面缺少输入法(IME)支持时,优先粘贴含非 ASCII 字符的文本。仅备份和恢复纯文本。请确认剪贴板可访问,且原有文本和待粘贴文本按 UTF-8 编码后均不超过 256 KiB。 | diff --git a/packages/screen-relay/package.json b/packages/screen-relay/package.json new file mode 100644 index 00000000..3714b29c --- /dev/null +++ b/packages/screen-relay/package.json @@ -0,0 +1,46 @@ +{ + "name": "@midscene/screen-relay", + "version": "0.0.0", + "description": "Connect a screen-relay desktop to Midscene Connect", + "license": "MIT", + "type": "module", + "repository": { + "type": "git", + "url": "git+https://github.com/web-infra-dev/midscene-test-everything.git", + "directory": "packages/screen-relay" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "engines": { + "node": "^22.12.0 || >=24.0.0" + }, + "bin": { + "midscene-screen-relay": "./dist/cli.js" + }, + "exports": { + ".": { + "types": "./dist/device.d.ts", + "import": "./dist/device.js" + } + }, + "files": ["dist", "README.zh.md"], + "scripts": { + "build": "rslib build", + "typecheck": "tsc --noEmit", + "test": "rstest run tests/unit", + "test:desktop": "rstest run tests/desktop" + }, + "dependencies": { + "@midscene/connect": "1.19.0", + "@midscene/robotics-shared": "workspace:*", + "screen-relay": "0.1.5" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "typescript": "^5.8.3", + "@rslib/core": "^0.18.3", + "@rstest/core": "0.12.0" + } +} diff --git a/packages/screen-relay/rslib.config.ts b/packages/screen-relay/rslib.config.ts new file mode 100644 index 00000000..ab64b4f5 --- /dev/null +++ b/packages/screen-relay/rslib.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from '@rslib/core'; + +export default defineConfig({ + source: { + entry: { index: './src/**/*.ts' }, + tsconfigPath: './tsconfig.build.json', + }, + lib: [{ format: 'esm', syntax: 'es2022', bundle: false, dts: true }], + output: { target: 'node', distPath: { root: 'dist' } }, +}); diff --git a/packages/screen-relay/rstest.config.ts b/packages/screen-relay/rstest.config.ts new file mode 100644 index 00000000..a9303487 --- /dev/null +++ b/packages/screen-relay/rstest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from '@rstest/core'; + +export default defineConfig({ + name: '@midscene/screen-relay', + include: ['tests/**/*.test.ts'], + testEnvironment: 'node', + testTimeout: 20000, + output: { externals: ['@midscene/connect', 'screen-relay'] }, +}); diff --git a/packages/screen-relay/src/cli.ts b/packages/screen-relay/src/cli.ts new file mode 100644 index 00000000..5b7a9543 --- /dev/null +++ b/packages/screen-relay/src/cli.ts @@ -0,0 +1,29 @@ +#!/usr/bin/env node +import { + createConnectCommand, + reportCliError, + serveConnectCli, +} from '@midscene/robotics-shared/connect-cli'; +import device from './device.js'; + +async function main() { + const values = createConnectCommand( + 'midscene-screen-relay', + 'Start a local Midscene Connect API to control a remote desktop via screen-relay.', + ) + .option( + '--relay-url ', + 'Remote Viewer URL, including #token=... if present (also MIDSCENE_SCREEN_RELAY_URL)', + ) + .parse() + .opts<{ relayUrl?: string; host: string; port: number; token?: string }>(); + + await serveConnectCli(device, { + host: values.host, + port: values.port, + token: values.token, + options: values.relayUrl === undefined ? {} : { relayUrl: values.relayUrl }, + }); +} + +main().catch(reportCliError); diff --git a/packages/screen-relay/src/device.ts b/packages/screen-relay/src/device.ts new file mode 100644 index 00000000..89b36a40 --- /dev/null +++ b/packages/screen-relay/src/device.ts @@ -0,0 +1,262 @@ +import { setTimeout as delay } from 'node:timers/promises'; +import type { + DeviceConnection, + DeviceDefinition, +} from '@midscene/connect/server'; +import { connect, createClient } from 'screen-relay'; + +type Point = { x: number; y: number }; +type Scroll = { + direction?: 'up' | 'down' | 'left' | 'right'; + scrollType?: + | 'singleAction' + | 'scrollToTop' + | 'scrollToBottom' + | 'scrollToLeft' + | 'scrollToRight'; + distance?: number; + locate?: { center: [number, number] }; +}; + +const keyAliases: Record = { + command: 'Meta', + option: 'Alt', + del: 'Delete', + spacebar: 'Space', + ' ': 'Space', +}; + +function keyCombo(value: string) { + const split = value.endsWith('++') + ? value.length - 2 + : value.lastIndexOf('+'); + const alias = (part: string) => keyAliases[part.toLowerCase()] ?? part; + if (split < 0 || value === '+') return alias(value); + const modifiers = value + .slice(0, split) + .split('+') + .map((part) => alias(part.trim())); + const rawKey = value.slice(split + 1); + const key = rawKey === ' ' ? rawKey : rawKey.trim(); + return [ + ...modifiers, + /^[A-Z]$/.test(key) ? key.toLowerCase() : alias(key), + ].join('+'); +} + +const device: DeviceDefinition<{ relayUrl?: string }> = { + name: 'Screen Relay', + description: + 'Controls a local, remote, or virtual desktop via screen-relay with mouse and keyboard input.', + pointerType: 'mouse', + options: { + type: 'object', + properties: { + relayUrl: { + type: 'string', + description: + 'Remote screen-relay Viewer URL, including #token=... if present', + }, + }, + }, + async connect({ relayUrl = process.env.MIDSCENE_SCREEN_RELAY_URL }) { + if (!relayUrl) + throw new Error('Provide --relay-url or set MIDSCENE_SCREEN_RELAY_URL.'); + if ( + !URL.canParse(relayUrl) || + !/^https?:$/i.test(new URL(relayUrl).protocol) + ) { + throw new Error('Expected an HTTP or HTTPS Viewer URL.'); + } + const viewer = new URL(relayUrl); + const options = { + url: viewer.origin, + token: + new URLSearchParams(viewer.hash.slice(1)).get('token') ?? undefined, + }; + const relay = createClient(options); + const caps = await relay.capabilities(); + if (!caps.screenshot) + throw new Error('This desktop does not provide screenshots.'); + let { width, height } = caps; + let pendingScreenshot: Promise | undefined; + async function captureScreenshot() { + const png = Buffer.from(await relay.screenshot()); + // Use the surface shown to Connect, including after a desktop resize. + if (png.length < 24 || png.toString('ascii', 12, 16) !== 'IHDR') + throw new Error('Invalid relay screenshot.'); + width = png.readUInt32BE(16); + height = png.readUInt32BE(20); + return png; + } + function screenshot() { + if (!pendingScreenshot) { + pendingScreenshot = captureScreenshot().finally(() => { + pendingScreenshot = undefined; + }); + } + return pendingScreenshot; + } + async function normalized(point: Point) { + if (!width || !height) await screenshot(); + if (!width || !height) throw new Error('Invalid relay surface size.'); + return { + x: Math.max(0, Math.min(1, point.x / width)), + y: Math.max(0, Math.min(1, point.y / height)), + }; + } + async function click( + point: Point, + button: 'left' | 'middle' | 'right' = 'left', + ) { + const { x, y } = await normalized(point); + await relay.click(x, y, { button }); + } + async function drag(from: Point, to: Point, duration = 180) { + const start = await normalized(from); + const end = await normalized(to); + const session = await connect(options); + let current = start; + let failed = false; + try { + await session.input({ type: 'pointerMove', ...start }); + await session.input({ type: 'buttonDown', button: 1, ...start }); + try { + for (let i = 1; i <= 12; i++) { + current = { + x: start.x + ((end.x - start.x) * i) / 12, + y: start.y + ((end.y - start.y) * i) / 12, + }; + await session.input({ type: 'pointerMove', ...current }); + await delay(duration / 12); + } + } catch (error) { + failed = true; + throw error; + } finally { + await session + .input({ type: 'buttonUp', button: 1, ...current }) + .catch((error) => { + if (!failed) throw error; + }); + } + } finally { + session.close(); + } + } + const actions: NonNullable = {}; + if (caps.input.pointer && caps.input.buttons) { + actions.tap = (p: Point) => click(p); + actions.doubleClick = async (p: Point) => { + await click(p); + await delay(80); + await click(p); + }; + actions.rightClick = (p: Point) => click(p, 'right'); + actions.middleClick = (p: Point) => click(p, 'middle'); + actions.hover = async (p: Point) => { + const { x, y } = await normalized(p); + await relay.move(x, y); + }; + actions.dragAndDrop = drag; + actions.swipe = async ( + from: Point, + to: Point, + opts?: { duration?: number; repeat?: number }, + ) => { + for (let i = 0; i < (opts?.repeat ?? 1); i++) + await drag(from, to, opts?.duration); + }; + } + if (caps.input.keyboard) { + const modifier = /mac|darwin/i.test(caps.backend) ? 'Meta' : 'Control'; + const clear = async () => { + await relay.key(`${modifier}+a`, 'Backspace'); + }; + actions.clearInput = clear; + actions.keyboardPress = async (key: string) => { + await relay.key(keyCombo(key)); + }; + actions.typeText = async ( + text: string, + opts?: { replace?: boolean; focusOnly?: boolean }, + ) => { + if (opts?.focusOnly) return; + const windows = caps.backend === 'windows'; + const paste = async (replace = false) => { + const previous = await relay.clipboard(); + await relay.setClipboard(text); + let failed = false; + try { + if (replace) await clear(); + await relay.key(`${modifier}+v`); + // The key acknowledgement can precede the application's clipboard read. + await delay(200); + } catch (error) { + failed = true; + throw error; + } finally { + await relay.setClipboard(previous).catch((error) => { + if (!failed) throw error; + }); + } + }; + // Windows translates even ASCII into layout keys, which the IME can consume. + if ( + text && + caps.clipboard && + (windows || (!caps.ime && /[\u0080-\u{10ffff}]/u.test(text))) + ) { + return paste(opts?.replace); + } + if (opts?.replace) await clear(); + if (!text) return; + try { + await relay.type(text); + } catch (error) { + if ( + !caps.clipboard || + !(error instanceof Error) || + !('reason' in error) || + error.reason !== 'unsupported_input' || + ('applied' in error && error.applied !== 0) + ) + throw error; + await paste(); + } + }; + } + if (caps.input.wheel) { + actions.scroll = async ({ + direction = 'down', + distance = 480, + scrollType = 'singleAction', + locate, + }: Scroll) => { + const { x, y } = locate + ? await normalized({ x: locate.center[0], y: locate.center[1] }) + : { x: 0.5, y: 0.5 }; + const edges = { + scrollToTop: 'up', + scrollToBottom: 'down', + scrollToLeft: 'left', + scrollToRight: 'right', + } as const; + const edge = scrollType !== 'singleAction'; + const way = edge ? edges[scrollType] : direction; + // Browsers can coalesce a large burst and cap it at one viewport. + const batches = edge ? 12 : 1; + const steps = edge ? 2 : Math.max(1, Math.round(distance / 120)); + for (let i = 0; i < batches; i++) { + if (i > 0) await delay(80); + await relay.scroll(x, y, { + dx: way === 'left' ? -steps : way === 'right' ? steps : 0, + dy: way === 'up' ? -steps : way === 'down' ? steps : 0, + }); + } + }; + } + return { screenshot, actions }; + }, +}; +export default device; diff --git a/packages/screen-relay/tests/cli-harness.ts b/packages/screen-relay/tests/cli-harness.ts new file mode 100644 index 00000000..57759487 --- /dev/null +++ b/packages/screen-relay/tests/cli-harness.ts @@ -0,0 +1,46 @@ +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { resolve } from 'node:path'; +import { createInterface } from 'node:readline'; +import type { TestContext } from '@rstest/core'; + +export async function startCli( + t: TestContext, + args: string[], + env: Record = {}, +) { + const cli = process.env.SCREEN_RELAY_TEST_CLI ?? resolve('dist/cli.js'); + const child = spawn(process.execPath, [cli, '--port', '0', ...args], { + env: { ...process.env, ...env }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + const exit = once(child, 'exit'); + t.onTestFinished(async () => { + child.kill(); + await exit; + }); + let stderr = ''; + child.stderr.setEncoding('utf8').on('data', (chunk) => { + stderr += chunk; + }); + for await (const line of createInterface({ input: child.stdout })) { + if (line.startsWith('Connect URL: ')) + return line.slice('Connect URL: '.length); + } + throw new Error(`CLI exited before serving: ${stderr}`); +} + +export async function request(url: string, route: string, body?: unknown) { + const response = await fetch( + `${url}/api/${route}`, + body === undefined + ? {} + : { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }, + ); + if (!response.ok) throw new Error(await response.text()); + return response.json(); +} diff --git a/packages/screen-relay/tests/desktop/x11.test.ts b/packages/screen-relay/tests/desktop/x11.test.ts new file mode 100644 index 00000000..dd1d18b6 --- /dev/null +++ b/packages/screen-relay/tests/desktop/x11.test.ts @@ -0,0 +1,211 @@ +// Invoked explicitly by the Linux desktop job after screen-relay up. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { type TestContext, test } from '@rstest/core'; +import { request, startCli } from '../cli-harness'; + +const modelConfigured = [ + 'MIDSCENE_MODEL_API_KEY', + 'MIDSCENE_MODEL_BASE_URL', + 'MIDSCENE_MODEL_NAME', + 'MIDSCENE_MODEL_FAMILY', +].every((name) => process.env[name]?.trim()); + +async function waitFor( + check: () => unknown, + description: string, + timeout = 15000, +) { + const deadline = Date.now() + timeout; + while (!(await check())) { + if (Date.now() > deadline) + throw new Error(`Timed out waiting for ${description}`); + await delay(75); + } +} + +type BrowserEvent = { type: string; value?: string }; +async function startDesktop(t: TestContext, useModel: boolean) { + const url = await startCli(t, []); + const screenshot = () => request(url, 'screenshot'); + const { width, height } = await screenshot(); + const html = await readFile( + join(process.cwd(), 'tests/fixtures/desktop.html'), + ); + const events: BrowserEvent[] = []; + let targets: Record; + const server = createServer(async (req, res) => { + if (req.method === 'GET') + return res.writeHead(200, { 'Content-Type': 'text/html' }).end(html); + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + const message = JSON.parse(Buffer.concat(chunks).toString()); + if (req.url === '/ready') targets = message.targets; + else events.push(message); + res.writeHead(204).end(); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.onTestFinished(() => { + server.closeAllConnections(); + server.close(); + }); + const profile = await mkdtemp(join(tmpdir(), 'relay-browser-')); + const browserPid = Number( + execFileSync( + 'screen-relay', + [ + 'run', + '--', + 'google-chrome', + '--no-sandbox', + '--disable-gpu', + '--disable-dev-shm-usage', + '--no-first-run', + '--no-default-browser-check', + '--kiosk', + '--window-position=0,0', + `--window-size=${width},${height}`, + `--user-data-dir=${profile}`, + `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + ], + { encoding: 'utf8' }, + ).trim(), + ); + t.onTestFinished(async () => { + if (browserPid > 1) { + try { + process.kill(browserPid, 'SIGTERM'); + } catch (error) { + if ( + !(error instanceof Error && 'code' in error && error.code === 'ESRCH') + ) + throw error; + } + } + await rm(profile, { recursive: true, force: true, maxRetries: 3 }); + }); + await waitFor(() => targets, 'browser fixture', 60000); + + const point = (name: string) => ({ + x: targets[name][0], + y: targets[name][1], + }); + const action = (name: string, body: object) => + request(url, `primitives/${name}`, body); + const observed = ( + type: string, + predicate: (event: BrowserEvent) => boolean = () => true, + ) => + waitFor( + () => events.some((event) => event.type === type && predicate(event)), + type, + ); + const { agentOverConnectProtocol } = await import('@midscene/connect'); + const agent = await agentOverConnectProtocol({ + url, + agentOptions: { + generateReport: useModel, + modelConfig: useModel + ? undefined + : { + MIDSCENE_MODEL_NAME: 'test-only', + MIDSCENE_MODEL_FAMILY: 'qwen3-vl', + MIDSCENE_MODEL_BASE_URL: 'http://127.0.0.1:1', + MIDSCENE_MODEL_API_KEY: 'test-only', + }, + }, + }); + t.onTestFinished(() => agent.destroy()); + return { + agent, + action, + events, + observed, + point, + screenshot, + targets: targets!, + }; +} + +test('packaged CLI drives a Chromium window on X11', async (t) => { + const { agent, action, events, observed, point, screenshot, targets } = + await startDesktop(t, false); + const before = (await screenshot()).image; + const locate = { + prompt: 'text field', + locatedPixelResult: { center: targets.input }, + }; + await agent.callActionInActionSpace('Tap', { locate }); + await observed('input-focused'); + await agent.callActionInActionSpace('Input', { + value: '北京天气', + mode: 'replace', + }); + await observed('input', (event) => event.value === '北京天气'); + await agent.callActionInActionSpace('KeyboardPress', { keyName: 'Enter' }); + await observed('enter', (event) => event.value === '北京天气'); + for (const [name, target] of [ + ['hover', 'hover'], + ['doubleClick', 'dblclick'], + ['rightClick', 'rightclick'], + ]) { + await action(name, { point: point(target) }); + await observed(target); + } + const scrollTarget = { + center: targets.scroll, + rect: { + left: point('scroll').x, + top: point('scroll').y, + width: 1, + height: 1, + }, + }; + await agent.callActionInActionSpace('Scroll', { + scrollType: 'scrollToBottom', + locate: { + prompt: 'scrollable list', + locatedPixelResult: scrollTarget, + }, + }); + await observed('last-item-visible'); + await action('scroll', { direction: 'up', locate: scrollTarget }); + await observed('scroll-up'); + await action('dragAndDrop', { + from: point('dragSource'), + to: point('dropTarget'), + }); + await observed('target-held'); + await observed('dropped'); + assert.ok(!events.some((event) => event.type === 'drag-lost-button')); + await waitFor( + async () => (await screenshot()).image !== before, + 'updated screenshot', + ); +}, 120000); + +test.skipIf(!modelConfigured)( + 'model-driven aiAct and aiAssert', + async (t) => { + const { agent, events } = await startDesktop(t, true); + await agent.aiAct( + 'Click the text field at the top, replace its contents with RELAY42, then press Enter.', + ); + await agent.aiAssert( + 'The text field contains RELAY42 and the badge next to it reads ENTER:RELAY42.', + ); + assert.equal( + events.filter((event) => event.type === 'enter').at(-1)?.value, + 'RELAY42', + ); + }, + 360000, +); diff --git a/packages/screen-relay/tests/fixtures/desktop.html b/packages/screen-relay/tests/fixtures/desktop.html new file mode 100644 index 00000000..a02b07b5 --- /dev/null +++ b/packages/screen-relay/tests/fixtures/desktop.html @@ -0,0 +1,263 @@ + + + + + Midscene Screen Relay E2E Fixture + + + +
+
+ +
IDLE
+
+ +
HOVER
+
DBLCLICK
+
RIGHTCLICK
+ +
+
+
+ +
+
DRAG SOURCE
+
DROP TARGET
+
+
+ + + + diff --git a/packages/screen-relay/tests/unit/adapter.test.ts b/packages/screen-relay/tests/unit/adapter.test.ts new file mode 100644 index 00000000..0f6f3098 --- /dev/null +++ b/packages/screen-relay/tests/unit/adapter.test.ts @@ -0,0 +1,290 @@ +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { expect, test } from '@rstest/core'; +import device from '../../dist/device.js'; +import { request, startCli } from '../cli-harness'; + +test('published CLI serves screenshots and scales clicks to the captured surface', async (t) => { + const token = 'a'.repeat(64); + const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jH1sAAAAASUVORK5CYII=', + 'base64', + ); + let events: Buffer = Buffer.alloc(0); + let buttons = true; + const server = createServer(async (req, res) => { + if (req.headers.authorization !== `Bearer ${token}`) + return res.writeHead(401).end(); + if (req.url === '/capabilities') + return res.end( + JSON.stringify({ + width: 800, + height: 600, + screenshot: 'png', + max_input_batch: 64, + input: { pointer: true, buttons }, + }), + ); + if (req.url === '/screenshot.png') return res.end(png); + if (req.url === '/input') { + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + events = Buffer.concat(chunks); + return res.end(JSON.stringify({ applied: events.length / 16 })); + } + res.writeHead(404).end(); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.onTestFinished(() => { + server.closeAllConnections(); + server.close(); + }); + const viewer = `http://127.0.0.1:${(server.address() as AddressInfo).port}/#token=${token}`; + await expect( + device.connect({ relayUrl: viewer.replace(token, 'b'.repeat(64)) }), + ).rejects.toMatchObject({ reason: 'unauthorized' }); + const url = await startCli(t, ['--relay-url', viewer], { + MIDSCENE_SCREEN_RELAY_URL: 'invalid', + }); + const tap = (x: number, y: number) => + request(url, 'primitives/tap', { point: { x, y } }); + await tap(400, 150); + expect(events.readUInt16BE(8)).toBe(32768); + expect(events.readUInt16BE(10)).toBe(16384); + const shot = await request(url, 'screenshot'); + expect(shot.image).toBe(`data:image/png;base64,${png.toString('base64')}`); + await tap(1, 1); + expect(events.readUInt16BE(8)).toBe(65535); + const info = await request(url, 'info'); + expect(info.primitives).toContain('dragAndDrop'); + expect(info.primitives).not.toContain('keyboardPress'); + + buttons = false; + const readOnly = await startCli(t, ['--token', ' connect-test-token '], { + MIDSCENE_SCREEN_RELAY_URL: viewer, + }); + const endpoint = `${readOnly}/api/info`; + expect((await fetch(endpoint)).status).toBe(401); + const infoResponse = await fetch(endpoint, { + headers: { Authorization: 'Bearer connect-test-token' }, + }); + expect(infoResponse.status).toBe(200); + expect((await infoResponse.json()).primitives).toEqual([]); +}); + +test('rejects malformed viewer URLs without disclosing credentials', async () => { + await expect( + device.connect({ relayUrl: 'invalid#token=private' }), + ).rejects.toThrow('Expected an HTTP or HTTPS Viewer URL.'); +}); + +const keyCodes = (buf: Buffer) => { + const codes: number[] = []; + for (let i = 0; i < buf.length; i += 16) { + if (buf.readUInt8(i) === 1) codes.push(buf.readUInt16BE(i + 2)); + } + return codes; +}; + +for (const backend of ['x11', 'windows']) { + test(`${backend} restores clipboard text after successful and rejected paste`, async (t) => { + let clipboard = ''; + let rejectPaste = false; + let rejectRead = false; + let rejectRestore = false; + const keys: number[][] = []; + const pasted: string[] = []; + const server = createServer(async (req, res) => { + if (req.url === '/capabilities') + return res.end( + JSON.stringify({ + backend, + screenshot: 'png', + clipboard: true, + ime: backend === 'windows', + input: { keyboard: true }, + max_input_batch: 64, + }), + ); + if (req.url === '/clipboard' && req.method === 'GET') + return rejectRead + ? res.writeHead(503).end() + : res.end(JSON.stringify({ text: clipboard })); + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + const body = Buffer.concat(chunks); + if (req.url === '/clipboard') { + if (rejectRestore && body.toString() === 'prior selection') + return res + .writeHead(503) + .end(JSON.stringify({ error: 'clipboard_unavailable' })); + clipboard = body.toString(); + return res.end(JSON.stringify({ length: body.length })); + } + if (req.url === '/input') { + keys.push(keyCodes(body)); + if (rejectPaste) + return res + .writeHead(409) + .end(JSON.stringify({ error: 'control_taken' })); + pasted.push(clipboard); + return res.end(JSON.stringify({ applied: body.length / 16 })); + } + res.writeHead(404).end(); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.onTestFinished(() => { + server.closeAllConnections(); + server.close(); + }); + const url = await startCli(t, [], { + MIDSCENE_SCREEN_RELAY_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + }); + const type = (text = '北京天气') => + request(url, 'primitives/typeText', { text }); + await type(); + const sample = backend === 'windows' ? 'readme-video.md' : 'café'; + await type(sample); + expect(pasted).toEqual(['北京天气', sample]); + expect(clipboard).toBe(''); + clipboard = 'prior selection'; + if (backend === 'windows') { + const value = + 'https://github.com/web-infra-dev/midscene-test-everything/tree/docs/readme-video'; + const replace = () => + request(url, 'primitives/typeText', { text: value, replace: true }); + await replace(); + expect(keys.slice(-2)).toEqual([ + [224, 4, 42], + [224, 25], + ]); + expect(pasted.at(-1)).toBe(value); + expect(clipboard).toBe('prior selection'); + rejectRead = true; + const count = keys.length; + await expect(replace()).rejects.toThrow(/ACTION_FAILED/); + expect(keys).toHaveLength(count); + expect(clipboard).toBe('prior selection'); + rejectRead = false; + } + rejectPaste = true; + await expect(type()).rejects.toThrow(/ACTION_FAILED/); + expect(clipboard).toBe('prior selection'); + + rejectRestore = true; + await expect(type()).rejects.toThrow(/Another controller holds control/); + + clipboard = 'prior selection'; + rejectPaste = false; + await expect(type()).rejects.toThrow( + /could not reach the desktop clipboard/, + ); + }); +} + +test('translates key combos and scroll parameters for screen-relay', async (t) => { + const inputs: Buffer[] = []; + const server = createServer(async (req, res) => { + if (req.url === '/capabilities') + return res.end( + JSON.stringify({ + backend: 'x11', + width: 1000, + height: 500, + screenshot: 'png', + max_input_batch: 64, + input: { keyboard: true, wheel: true }, + }), + ); + if (req.url === '/input') { + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + const body = Buffer.concat(chunks); + inputs.push(body); + return res.end(JSON.stringify({ applied: body.length / 16 })); + } + res.writeHead(404).end(); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.onTestFinished(() => { + server.closeAllConnections(); + server.close(); + }); + const url = await startCli(t, [], { + MIDSCENE_SCREEN_RELAY_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + }); + await request(url, 'primitives/keyboardPress', { key: 'Control + A' }); + await request(url, 'primitives/keyboardPress', { key: 'Command+V' }); + await request(url, 'primitives/keyboardPress', { key: 'Del' }); + await request(url, 'primitives/keyboardPress', { key: ' ' }); + await request(url, 'primitives/keyboardPress', { key: 'Spacebar' }); + // HID codes: ControlLeft=224, KeyA=4 (no ShiftLeft=225), MetaLeft=227, KeyV=25, Delete=76, Space=44 + expect(keyCodes(inputs[0])).toEqual([224, 4]); + expect(keyCodes(inputs[1])).toEqual([227, 25]); + expect(keyCodes(inputs[2])).toEqual([76]); + expect(keyCodes(inputs[3])).toEqual([44]); + expect(keyCodes(inputs[4])).toEqual([44]); + + await request(url, 'primitives/scroll', { scrollType: 'scrollToTop' }); + const scrollBatch = Buffer.concat(inputs.slice(5)); + let totalDelta = 0; + for (let i = 0; i < scrollBatch.length; i += 16) { + if (scrollBatch.readUInt8(i) === 6) + totalDelta += scrollBatch.readInt32BE(i + 4); + } + expect(totalDelta).toBe(-24 * 120); +}); + +test('coalesces concurrent screenshot requests to avoid engine busy errors', async (t) => { + const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jH1sAAAAASUVORK5CYII=', + 'base64', + ); + let active = 0; + let calls = 0; + const server = createServer((req, res) => { + if (req.url === '/capabilities') + return res.end( + JSON.stringify({ + width: 1, + height: 1, + screenshot: 'png', + max_input_batch: 64, + input: {}, + }), + ); + if (req.url === '/screenshot.png') { + if (active > 0) + return res.writeHead(503).end(JSON.stringify({ error: 'busy' })); + active += 1; + calls += 1; + setTimeout(() => { + active -= 1; + res.end(png); + }, 30); + return; + } + res.writeHead(404).end(); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.onTestFinished(() => { + server.closeAllConnections(); + server.close(); + }); + const url = await startCli(t, [], { + MIDSCENE_SCREEN_RELAY_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + }); + const [first, second] = await Promise.all([ + request(url, 'screenshot'), + request(url, 'screenshot'), + ]); + const expected = `data:image/png;base64,${png.toString('base64')}`; + expect(first.image).toBe(expected); + expect(second.image).toBe(expected); + expect(calls).toBe(1); +}); diff --git a/packages/screen-relay/tsconfig.build.json b/packages/screen-relay/tsconfig.build.json new file mode 100644 index 00000000..f3b41223 --- /dev/null +++ b/packages/screen-relay/tsconfig.build.json @@ -0,0 +1,5 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { "rootDir": "src" }, + "include": ["src"] +} diff --git a/packages/screen-relay/tsconfig.json b/packages/screen-relay/tsconfig.json new file mode 100644 index 00000000..18287dfd --- /dev/null +++ b/packages/screen-relay/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "skipLibCheck": true, + "esModuleInterop": true, + "declaration": true, + "outDir": "dist", + "rootDir": "." + }, + "include": ["src", "tests", "*.config.ts"] +} diff --git a/packages/shared/utils/package.json b/packages/shared/utils/package.json index 44c0e27b..fa1b5775 100644 --- a/packages/shared/utils/package.json +++ b/packages/shared/utils/package.json @@ -71,9 +71,15 @@ "./connect-registry": { "types": "./dist/connect-registry.d.ts", "import": "./dist/connect-registry.js" + }, + "./connect-cli": { + "types": "./dist/connect-cli.d.ts", + "import": "./dist/connect-cli.js" } }, "dependencies": { - "@midscene/connect": "1.19.0" + "@midscene/connect": "1.19.0", + "chalk": "5.6.2", + "commander": "13.1.0" } } diff --git a/packages/shared/utils/src/connect-cli.ts b/packages/shared/utils/src/connect-cli.ts new file mode 100644 index 00000000..ea8f01bb --- /dev/null +++ b/packages/shared/utils/src/connect-cli.ts @@ -0,0 +1,74 @@ +import { serveDevice } from '@midscene/connect/server'; +import chalk, { chalkStderr } from 'chalk'; +import { Command, InvalidArgumentError } from 'commander'; + +export function createConnectCommand(name: string, description: string) { + return new Command(name) + .description(description) + .allowExcessArguments(false) + .option('--host ', 'Listen address for the Connect API', '127.0.0.1') + .option( + '--port ', + 'Port for the Connect API', + (value) => { + const port = Number(value); + if (!/^\d+$/.test(value) || port > 65535) { + throw new InvalidArgumentError( + 'Expected an integer between 0 and 65535.', + ); + } + return port; + }, + 5820, + ) + .option( + '--token ', + 'Bearer token for the Connect API (generated on non-loopback hosts if omitted)', + (value) => { + const token = value.trim(); + if (!token) throw new InvalidArgumentError('Token must not be empty.'); + return token; + }, + ); +} + +export function reportCliError(error: unknown) { + const message = error instanceof Error ? error.message : String(error); + console.error( + message.replace(/`[^`\n]+`/g, (command) => chalkStderr.cyan(command)), + ); + process.exitCode = 1; +} + +/** Start a single-device Connect service in the foreground. */ +export async function serveConnectCli(...args: Parameters) { + const { url, token, close } = await serveDevice(...args); + const stop = () => { + process.removeListener('SIGINT', stop); + process.removeListener('SIGTERM', stop); + void close().then( + () => process.exit(process.exitCode ?? 0), + (error) => { + reportCliError(error); + process.exit(1); + }, + ); + }; + process.once('SIGINT', stop); + process.once('SIGTERM', stop); + + const docs = `${url}/api/docs/`; + if (process.stdout.isTTY) { + console.log( + `\n ${chalk.bold('Midscene Connect')}\n ${chalk.bold.cyan(url)}\n`, + ); + console.log(` ${chalk.dim('Docs ')}${chalk.underline(docs)}`); + console.log( + ` ${chalk.dim('Token ')}${token ? chalk.yellow(token) : chalk.dim('Not required on localhost')}`, + ); + } else { + console.log(`Connect URL: ${url}`); + console.log(`API docs: ${docs}`); + console.log(`Connect token: ${token ?? 'not required (loopback)'}`); + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4d796257..06cf0d3b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -135,12 +135,12 @@ importers: '@midscene/connect': specifier: 1.19.0 version: 1.19.0(@types/node@22.20.5)(ws@8.22.1) + '@midscene/robotics-shared': + specifier: workspace:* + version: link:../shared/utils chalk: specifier: 5.6.2 version: 5.6.2 - commander: - specifier: 13.1.0 - version: 13.1.0 execa: specifier: 8.0.1 version: 8.0.1 @@ -299,6 +299,31 @@ importers: specifier: ^5.8.3 version: 5.9.3 + packages/screen-relay: + dependencies: + '@midscene/connect': + specifier: 1.19.0 + version: 1.19.0(@types/node@22.20.5)(ws@8.22.1) + '@midscene/robotics-shared': + specifier: workspace:* + version: link:../shared/utils + screen-relay: + specifier: 0.1.5 + version: 0.1.5 + devDependencies: + '@rslib/core': + specifier: ^0.18.3 + version: 0.18.6(typescript@5.9.3) + '@rstest/core': + specifier: 0.12.0 + version: 0.12.0(core-js@3.47.0) + '@types/node': + specifier: ^22.0.0 + version: 22.20.5 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + packages/shared/preview-controls: devDependencies: '@types/react': @@ -316,6 +341,12 @@ importers: '@midscene/connect': specifier: 1.19.0 version: 1.19.0(@types/node@22.20.5)(ws@8.22.1) + chalk: + specifier: 5.6.2 + version: 5.6.2 + commander: + specifier: 13.1.0 + version: 13.1.0 devDependencies: '@rslib/core': specifier: ^0.18.3 @@ -601,9 +632,17 @@ packages: '@clack/core@0.5.0': resolution: {integrity: sha512-p3y0FIOwaYRUPRcMO7+dlmLh8PSRcrjuTndsiA0WAFbWES0mLZlrjVoBRZ9DzkPFJZG6KGkJmoEAY0ZcVWTkow==} + '@clack/core@1.6.0': + resolution: {integrity: sha512-4GZynIB2IIe431odxesswvWTCP6orvqd6e2b07b3VFWBQRqUqIHc/EPIZwFoKS692QBp+ooPuXKaJV8g4kXuYA==} + engines: {node: '>= 20.12.0'} + '@clack/prompts@0.11.0': resolution: {integrity: sha512-pMN5FcrEw9hUkZA4f+zLlzivQSeQf5dRGJjSUbvVYDLvpKCdQx5OaknvKzgbtXOizhP+SJJJjqEbOe55uKKfAw==} + '@clack/prompts@1.9.0': + resolution: {integrity: sha512-tEj8X2No2A1c9NDnZECxiiJ8TP3vmFlN9tLlLeSaMqVW4tUmVG2R4qpv/eP4zymWxnymYLkLcIYVV0VcWj3RCQ==} + engines: {node: '>= 20.12.0'} + '@commitlint/cli@19.8.0': resolution: {integrity: sha512-t/fCrLVu+Ru01h0DtlgHZXbHV2Y8gKocTR5elDOqIRUzQd0/6hpt2VIWOj9b3NDo7y4/gfxeR2zRtXq/qO6iUg==} engines: {node: '>=v18'} @@ -1767,6 +1806,10 @@ packages: '@ui-tars/shared@1.2.3': resolution: {integrity: sha512-6FgmBq21M8zB1OemH24+YbMX/H8l/2e2FlBcrVmvc2UqRPBy69UCzZ4dQCe8JIwA4FstHDCmv6a6CrZ/NeNa3g==} + '@vercel/detect-agent@1.2.7': + resolution: {integrity: sha512-5tWaC9V+u4SHcSMKBz9FQb3Dhl/1A2lQ6QqHovu8uQeb8dTyjEevpJMANm/uQEn/usYB63fpdjWYjkJ8/bGtjA==} + engines: {node: '>=14'} + '@webgpu/types@0.1.74': resolution: {integrity: sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==} @@ -2462,9 +2505,18 @@ packages: fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + fast-string-truncated-width@3.0.3: + resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==} + + fast-string-width@3.0.2: + resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==} + fast-uri@3.1.9: resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} + fast-wrap-ansi@0.2.2: + resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==} + fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -3791,6 +3843,11 @@ packages: scheduler@0.23.2: resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==} + screen-relay@0.1.5: + resolution: {integrity: sha512-g0ovySxoYBe6beHO1WiJkx5rKDPl7UdDf2FnQfh1oVjRxsHakEl9HVzQ6VU7FBZMjVuquteZEOU6KnIbYP3s4Q==} + engines: {node: '>=22'} + hasBin: true + scroll-into-view-if-needed@3.1.0: resolution: {integrity: sha512-49oNpRjWRvnU8NyGVmUaYG4jtTkNonFZI86MmGRDqBphEK2EXT9gdEUoQPZhuBM8yWHxCWbobltqYO5M4XrUvQ==} @@ -3873,6 +3930,10 @@ packages: sisteransi@1.0.5: resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} + sisteransi@2.0.1: + resolution: {integrity: sha512-Xeg0ma58PRiVJnAZKotI4Re8LKcjRIvle3ynYviPguyb7NVYgMqnhCf0zQxxkKj26vxL0ZPsC9cicDyRDeZbwA==} + engines: {node: '>=20'} + slice-ansi@5.0.0: resolution: {integrity: sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==} engines: {node: '>=12'} @@ -4457,12 +4518,25 @@ snapshots: picocolors: 1.1.1 sisteransi: 1.0.5 + '@clack/core@1.6.0': + dependencies: + fast-string-width: 3.0.2 + fast-wrap-ansi: 0.2.2 + sisteransi: 2.0.1 + '@clack/prompts@0.11.0': dependencies: '@clack/core': 0.5.0 picocolors: 1.1.1 sisteransi: 1.0.5 + '@clack/prompts@1.9.0': + dependencies: + '@clack/core': 1.6.0 + fast-string-width: 3.0.2 + fast-wrap-ansi: 0.2.2 + sisteransi: 2.0.1 + '@commitlint/cli@19.8.0(@types/node@22.20.5)(typescript@5.9.3)': dependencies: '@commitlint/format': 19.8.1 @@ -5587,6 +5661,8 @@ snapshots: '@ui-tars/shared@1.2.3': {} + '@vercel/detect-agent@1.2.7': {} + '@webgpu/types@0.1.74': {} '@yarnpkg/lockfile@1.1.0': {} @@ -6427,8 +6503,18 @@ snapshots: fast-deep-equal@3.1.3: {} + fast-string-truncated-width@3.0.3: {} + + fast-string-width@3.0.2: + dependencies: + fast-string-truncated-width: 3.0.3 + fast-uri@3.1.9: {} + fast-wrap-ansi@0.2.2: + dependencies: + fast-string-width: 3.0.2 + fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -7905,6 +7991,12 @@ snapshots: dependencies: loose-envify: 1.4.0 + screen-relay@0.1.5: + dependencies: + '@clack/prompts': 1.9.0 + '@vercel/detect-agent': 1.2.7 + yaml: 2.9.1 + scroll-into-view-if-needed@3.1.0: dependencies: compute-scroll-into-view: 3.1.1 @@ -8063,6 +8155,8 @@ snapshots: sisteransi@1.0.5: {} + sisteransi@2.0.1: {} + slice-ansi@5.0.0: dependencies: ansi-styles: 6.2.3