Mobile MCP: let AI agents drive your iOS and Android apps. MCP server for simulators, emulators and real devices. Works with Claude Code, Codex, Cursor and any MCP client.
TypeScript agentandroidandroid-automationappium-alternativeclaude-codecodexcursoremulatoriosios-automationmcpmcp-servermobilemobile-automationmobile-testingreal-devicesimulatorskills
feat: ship mobile-mcp as a Claude Code plugin with /mobile-mirror (#468)
Gil Megidish04bc5faf1188
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 0000000..3e97222--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,14 @@+{+ "name": "mobile-mcp",+ "description": "Mobile automation for AI agents on Android and iOS",+ "owner": {+ "name": "Mobile Next",+ "url": "https://mobilenext.ai"+ },+ "plugins": [+ {+ "name": "mobile-mcp",+ "source": "./plugin"+ }+ ]+}diff --git a/.gitignore b/.gitignoreindex 85b563f..3edf9a0 100644--- a/.gitignore+++ b/.gitignore@@ -4,4 +4,6 @@ lib.vscodecoveragetest-results-playwright-report\ No newline at end of file+playwright-report+# generated by Claude Code when the plugin loads+plugin/.claude-plugin/typesdiff --git a/README.ja.md b/README.ja.mdindex 48f37a1..8868a0c 100644--- a/README.ja.md+++ b/README.ja.md@@ -58,6 +58,11 @@ https://github.com/user-attachments/assets/bb084777-beb3-4930-ae6f-8d3fe694ddde- 🧠 **プラットフォームの専門知識は不要**: XCUITest も Espresso もプラットフォームごとのつなぎコードも不要です。目的を伝えればエージェントが実行します。- 🧰 **完全なデバイス制御**: タップ、スワイプ、ジェスチャー、アプリのインストール / 起動 / 終了、画面録画、ハードウェアボタン、ディープリンク、画面の向き。- 📊 **構造化された決定的な出力**: 実際の UI 要素を読み取って構造化データを抽出し、スクリーンショットのみのアプローチにありがちな曖昧さを削減します。+- 🪞 **Claude Code でのデバイスミラーリング**: Ghostty または kitty で動作する Claude Code 向けです。プラグインをインストールして `/mobile-mirror` を実行すると、デバイスのライブ画面がサイドペインに表示され、ターミナルを離れずにタップ、文字入力、Home/Back の操作ができます。++<p align="center">+ <img alt="/mobile-mirror showing an iOS simulator beside a Claude Code session" src="docs/screenshots/mobile-mirror.png" width="800" />+</p>### 🎯 対応プラットフォーム@@ -208,7 +213,16 @@ Cline をセットアップするには、上記の json を MCP 設定ファイ<details><summary>Claude Code</summary>-Claude Code CLI を使って Mobile MCP サーバーを追加します:+Claude Code 内でプラグインをインストールします。Mobile MCP サーバーと `/mobile-mirror` が追加されます:++```+/plugin marketplace add mobile-next/mobile-mcp+/plugin install mobile-mcp@mobile-mcp+```++`/mobile-mirror [device-id]` を実行すると、デバイスのライブ画面を表示するペインが開きます。画像をクリックするとタップ、キー入力でキーを送信でき、上部の Home、Back、App Switch、URL ボタンも使えます。画像の表示には kitty や Ghostty など、kitty グラフィックスプロトコルに対応したターミナルが必要です。++プラグインを使えない場合は、Claude Code CLI で MCP サーバーのみを追加します:```bashclaude mcp add mobile-mcp -- npx -y @mobilenext/mobile-mcp@latestdiff --git a/README.md b/README.mdindex 75a378c..3c42117 100644--- a/README.md+++ b/README.md@@ -58,6 +58,11 @@ How we help to scale mobile automation:- 🧠 **No platform expertise required**: no XCUITest, no Espresso, no per-platform glue — describe the goal and the agent does it.- 🧰 **Full device control**: taps, swipes, and gestures; app install/launch/terminate; screen recording; hardware buttons; deep links; orientation.- 📊 **Structured, deterministic output**: reads real UI elements and extracts structured data, cutting the ambiguity of screenshot-only approaches.+- 🪞 **Device mirroring in Claude Code**: for Claude Code running in Ghostty or kitty. Install the plugin and run `/mobile-mirror` to see the device's live screen in a side pane, then tap, type and press Home/Back without leaving the terminal.++<p align="center">+ <img alt="/mobile-mirror showing an iOS simulator beside a Claude Code session" src="docs/screenshots/mobile-mirror.png" width="800" />+</p>### 🎯 Platform Support@@ -209,7 +214,16 @@ To setup Cline, just add the json above to your MCP settings file.<details><summary>Claude Code</summary>-Use the Claude Code CLI to add the Mobile MCP server:+Install the plugin from inside Claude Code. It adds the Mobile MCP server and `/mobile-mirror`:++```+/plugin marketplace add mobile-next/mobile-mcp+/plugin install mobile-mcp@mobile-mcp+```++`/mobile-mirror [device-id]` opens a pane with the device's live screen. Click the picture to tap, type to send keys, and use the Home, Back, App Switch and URL buttons above it. The picture needs a terminal with the kitty graphics protocol, such as kitty or Ghostty.++If you can't use plugins, add only the MCP server with the Claude Code CLI:```bashclaude mcp add mobile-mcp -- npx -y @mobilenext/mobile-mcp@latestdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 053ddc2..1d41133 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -58,6 +58,11 @@ https://github.com/user-attachments/assets/bb084777-beb3-4930-ae6f-8d3fe694ddde- 🧠 **无需平台专业知识**: 不需要 XCUITest,不需要 Espresso,也不需要各平台的胶水代码 —— 描述目标,智能体来完成。- 🧰 **完整的设备控制**: 点击、滑动与手势;应用安装/启动/终止;屏幕录制;硬件按键;深度链接;屏幕方向。- 📊 **结构化、确定性的输出**: 读取真实的 UI 元素并提取结构化数据,减少纯截图方案带来的歧义。+- 🪞 **在 Claude Code 中镜像设备**: 适用于在 Ghostty 或 kitty 中运行的 Claude Code。安装插件后运行 `/mobile-mirror`,即可在侧边窗格中查看设备的实时画面,并且无需离开终端就能点按、输入文字以及按 Home/Back。++<p align="center">+ <img alt="/mobile-mirror showing an iOS simulator beside a Claude Code session" src="docs/screenshots/mobile-mirror.png" width="800" />+</p>### 🎯 平台支持@@ -208,7 +213,16 @@ Antigravity 没有添加 MCP 服务器的 CLI 命令,因此需要手动添加<details><summary>Claude Code</summary>-使用 Claude Code CLI 添加 Mobile MCP 服务器:+在 Claude Code 中安装插件,它会添加 Mobile MCP 服务器和 `/mobile-mirror`:++```+/plugin marketplace add mobile-next/mobile-mcp+/plugin install mobile-mcp@mobile-mcp+```++`/mobile-mirror [device-id]` 会打开一个显示设备实时画面的窗格。点击画面即可点按设备,输入文字即可发送按键,上方还有 Home、Back、App Switch 和 URL 按钮。显示画面需要支持 kitty 图形协议的终端,例如 kitty 或 Ghostty。++如果无法使用插件,可以用 Claude Code CLI 只添加 MCP 服务器:```bashclaude mcp add mobile-mcp -- npx -y @mobilenext/mobile-mcp@latestdiff --git a/docs/screenshots/mobile-mirror.png b/docs/screenshots/mobile-mirror.pngnew file mode 100644index 0000000..0c44eb4Binary files /dev/null and b/docs/screenshots/mobile-mirror.png differdiff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.jsonnew file mode 100644index 0000000..b9d0254--- /dev/null+++ b/plugin/.claude-plugin/plugin.json@@ -0,0 +1,21 @@+{+ "name": "mobile-mcp",+ "version": "1.0.7",+ "description": "Mobile automation for Claude Code: the mobile-mcp server, and /mobile-mirror, a live, clickable device screen in a pane.",+ "author": {+ "name": "Mobile Next",+ "url": "https://mobilenext.ai"+ },+ "homepage": "https://mobilenext.ai/docs",+ "repository": "https://github.com/mobile-next/mobile-mcp",+ "license": "Apache-2.0",+ "keywords": ["mobile", "android", "ios", "automation", "testing", "mcp", "mirror"],+ "mcpServers": {+ "mobile-mcp": {+ "type": "stdio",+ "command": "npx",+ "args": ["-y", "@mobilenext/mobile-mcp@latest"]+ }+ },+ "types": "./types/index.d.ts"+}diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.jsonnew file mode 100644index 0000000..5a63f64--- /dev/null+++ b/plugin/hooks/hooks.json@@ -0,0 +1 @@+{ "modules": ["./register.tsx"] }diff --git a/plugin/hooks/keys.ts b/plugin/hooks/keys.tsnew file mode 100644index 0000000..67686d0--- /dev/null+++ b/plugin/hooks/keys.ts@@ -0,0 +1,69 @@+import type { Platform } from "../types";++export type KeyAction = { type: "text"; text: string } | { type: "button"; button: string };++// special key names the terminal reports, mapped to mobile_press_button buttons+const ANDROID_BUTTONS: Record<string, string> = {+ return: "ENTER",+ backspace: "BACKSPACE",+ delete: "BACKSPACE",+ up: "DPAD_UP",+ down: "DPAD_DOWN",+ left: "DPAD_LEFT",+ right: "DPAD_RIGHT",+};++const IOS_BUTTONS: Record<string, string> = {+ return: "ENTER",+};++// ponytail: iOS has no BACKSPACE button in mobilecli, so it is typed as \b; unverified on a device+const IOS_TEXT: Record<string, string> = {+ backspace: "\b",+ delete: "\b",+};++function actionFor(key: string, platform: Platform): KeyAction | undefined {+ const buttons = platform === "android" ? ANDROID_BUTTONS : IOS_BUTTONS;+ const button = buttons[key];+ if (button) {+ return { type: "button", button };+ }++ const text = platform === "ios" ? IOS_TEXT[key] : undefined;+ if (text) {+ return { type: "text", text };+ }++ if (key === "space") {+ return { type: "text", text: " " };+ }++ // a single character is typed as is; any other named key is dropped+ if ([...key].length === 1) {+ return { type: "text", text: key };+ }++ return undefined;+}++// turns pressed keys into device actions, joining consecutive text into one type call+export function keysToActions(keys: string[], platform: Platform): KeyAction[] {+ const actions: KeyAction[] = [];+ for (const key of keys) {+ const action = actionFor(key, platform);+ if (!action) {+ continue;+ }++ const last = actions[actions.length - 1];+ if (action.type === "text" && last?.type === "text") {+ actions[actions.length - 1] = { type: "text", text: last.text + action.text };+ } else {+ actions.push(action);+ }++ }++ return actions;+}diff --git a/plugin/hooks/png.ts b/plugin/hooks/png.tsnew file mode 100644index 0000000..c682413--- /dev/null+++ b/plugin/hooks/png.ts@@ -0,0 +1,33 @@+// width and height from a PNG's IHDR chunk, big-endian at bytes 16..23+export function pngSize(bytes: Uint8Array): { width: number; height: number } {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);++ return { width: view.getUint32(16), height: view.getUint32(20) };+}++const MAX_CELLS = 255;+// cell height / cell width of the terminal font, measured 17.3px / 8.1px; no API reports it, so tune per font+export const CELL_ASPECT = 2.14;++function clampCells(n: number): number {+ return Math.max(1, Math.min(MAX_CELLS, Math.floor(n)));+}++// the largest box of cells that keeps the picture's aspect and fits inside maxColumns x maxRows+export function fitInside(columnsLimit: number, rowsLimit: number, width: number, height: number): { columns: number; rows: number } {+ const maxColumns = clampCells(columnsLimit);+ const maxRows = clampCells(rowsLimit);+ // a broken PNG header can report zero; without an aspect to keep, fill the box instead of dividing by zero+ if (width <= 0 || height <= 0) {+ return { columns: maxColumns, rows: maxRows };+ }++ const rowsAtFullWidth = (maxColumns * height) / width / CELL_ASPECT;+ if (rowsAtFullWidth <= maxRows) {+ return { columns: clampCells(maxColumns), rows: clampCells(rowsAtFullWidth) };+ }++ const columnsAtFullHeight = (maxRows * width * CELL_ASPECT) / height;++ return { columns: clampCells(columnsAtFullHeight), rows: clampCells(maxRows) };+}diff --git a/plugin/hooks/register.tsx b/plugin/hooks/register.tsxnew file mode 100644index 0000000..fb95abd--- /dev/null+++ b/plugin/hooks/register.tsx@@ -0,0 +1,242 @@+import { atom, read, update } from "claude-code";+import type { EngineInterface, Register } from "claude-code";++import type { Shot, Target } from "../types";+import { keysToActions } from "./keys";+import { fitInside, pngSize } from "./png";++// the key of the MCP server in this plugin's manifest+const MCP_SERVER = "mobile-mcp";+const COMMAND = "mobile-mirror";+const PANE = "mobile-mirror";+const VIEW_KEY = "view";+const TAP_KEY = "tap";+// frames rotate through a few files, so the terminal never reads one being rewritten+const FRAME_FILES = 3;+// large enough that the terminal never upscales it on a Retina pane; smaller is faster+const SHOT_MAX_SIZE = 1600;+const RETRY_AFTER_ERROR_MS = 1000;+// the toolbar row, plus the URL field's row while it shows+const TOOLBAR_ROWS = 1;+const URL_FIELD_ROWS = 1;++// kept in session state, not module variables, so they survive a reload of the mod+const target = atom({ plugin: "mobile-mcp", key: "target" } as const, null as Target | null);+// bumped to stop the running frame loop: a loop runs only while it holds the current value+const streamId = atom({ plugin: "mobile-mcp", key: "streamId" } as const, 0);+const isAskingUrl = atom({ plugin: "mobile-mcp", key: "isAskingUrl" } as const, false);+const shot = atom({ plugin: "mobile-mcp", key: "shot" } as const, { file: "", generation: 0, width: 1, height: 1 } as Shot);++type Device = { id: string; platform: string; state: string };+type TapMessage = { x: number; y: number };+type KeysMessage = { keys: string[] };+// the runtime has Uint8Array.fromBase64; the TS lib does not declare it yet+type Base64Decoder = { fromBase64(base64: string): Uint8Array };+type McpResult = Awaited<ReturnType<EngineInterface["mcp"]["call"]>>;++function firstText(content: unknown): string {+ const block = (content as { type: string; text?: string }[]).find(b => b.type === "text");++ return block?.text ?? "";+}++function frameFile(generation: number): string {+ return `/tmp/mobile-mirror-${generation % FRAME_FILES}.png`;+}++// calls a mobile-mcp tool by the name this session runs the server under, connecting it on first use+async function callMobileMcp($: EngineInterface, tool: string, args: Record<string, unknown> = {}): Promise<McpResult> {+ const connection = await $.mcp.connect(MCP_SERVER);+ if (!connection.isConnected) {+ throw new Error(`mobile-mcp is not connected: ${connection.message}`);+ }++ return $.mcp.call(connection.server, tool, args);+}++// runs a toolbar action, and toasts only when it fails+async function runAction($: EngineInterface, what: string, tool: string, args: Record<string, unknown>): Promise<void> {+ try {+ const result = await callMobileMcp($, tool, args);+ if (result.isError) {+ $.ui.toast(`${what} failed: ${firstText(result.content)}`);+ }++ } catch (error) {+ $.ui.toast(`${what} failed: ${String(error)}`);+ }+}++function pickDevice(devices: Device[], wanted: string | undefined): Device | undefined {+ const online = devices.filter(d => d.state === "online");+ if (wanted) {+ return online.find(d => d.id === wanted);+ }++ return online.find(d => d.platform === "android") ?? online[0];+}++export const register: Register = on => {+ // key batches are sent one after another, so typed text keeps its order+ let typing: Promise<void> = Promise.resolve();++ on("session.start", async ($, e, next) => {+ await $.command.register({ name: COMMAND, description: "Mirror a device screen: live picture, taps, keys and buttons", argumentHint: "[device-id]" });++ return next(e);+ });++ on("command.run", { command: COMMAND }, async ($, e) => {+ const wanted = e.args.trim() || undefined;+ const listed = await callMobileMcp($, "mobile_list_available_devices");+ const { devices } = JSON.parse(firstText(listed.content)) as { devices: Device[] };+ const device = pickDevice(devices, wanted);+ if (!device) {+ const online = devices.filter(d => d.state === "online").map(d => d.id);+ return { text: `No online device${wanted ? ` "${wanted}"` : ""}. Online: ${online.join(", ") || "none"}` };+ }++ const sized = await callMobileMcp($, "mobile_get_screen_size", { device: device.id });+ const match = /(\d+)x(\d+)/.exec(firstText(sized.content));+ if (!match) {+ return { text: `Could not read the screen size of ${device.id}.` };+ }++ await update($, target, () => ({+ id: device.id,+ platform: device.platform === "android" ? "android" : "ios",+ screenWidth: Number(match[1]),+ screenHeight: Number(match[2]),+ }));+ await update($, isAskingUrl, () => false);+ const id = await update($, streamId, n => n + 1);++ const captureFrame = async (generation: number): Promise<boolean> => {+ const file = frameFile(generation);+ const saved = await callMobileMcp($, "mobile_save_screenshot", { device: device.id, saveTo: file, maxSize: SHOT_MAX_SIZE });+ if (saved.isError) {+ return false;+ }++ const { base64 } = await $.fs.read(file, { as: "bytes" });+ const size = pngSize((Uint8Array as unknown as Base64Decoder).fromBase64(base64));+ const current = await read($, shot);+ // a new shape (first frame, rotation) needs a full redraw; otherwise swap the pixels in place+ if (current.generation === 0 || current.width !== size.width || current.height !== size.height) {+ await update($, shot, () => ({ file, generation, ...size }));+ } else {+ await $.ui.blit({ requestId: PANE, key: VIEW_KEY, source: { file, format: "png", generation } }).catch(() => {});+ }++ return true;+ };++ const stream = async () => {+ // the next frame is asked for as soon as the previous one is shown+ for (let generation = 1; id === (await read($, streamId)); generation++) {+ const isShown = await captureFrame(generation).catch(() => false);+ if (!isShown) {+ await $.clock.sleep(RETRY_AFTER_ERROR_MS);+ }++ }+ };++ await update($, shot, () => ({ file: "", generation: 0, width: 1, height: 1 }));+ void stream();+ await $.ui.open({ id: PANE, title: `mobile-mirror · ${device.id}` });++ return { text: `Mirroring ${device.id}. Click the picture to tap, then type to send keys.` };+ });++ on("ui.message", async ($, e) => {+ const device = await read($, target);+ if (e.element !== TAP_KEY || !device) {+ return {};+ }++ if ("keys" in (e.data as object)) {+ const actions = keysToActions((e.data as KeysMessage).keys, device.platform);+ typing = typing.then(async () => {+ for (const action of actions) {+ if (action.type === "text") {+ await runAction($, "Typing", "mobile_type_keys", { device: device.id, text: action.text, submit: false });+ } else {+ await runAction($, `Press ${action.button}`, "mobile_press_button", { device: device.id, button: action.button });+ }++ }+ });++ return {};+ }++ const tap = e.data as TapMessage;+ const x = Math.round(tap.x * device.screenWidth);+ const y = Math.round(tap.y * device.screenHeight);+ await runAction($, "Tap", "mobile_click_on_screen_at_coordinates", { device: device.id, x, y });++ return {};+ });++ on("ui.close", async ($, e, next) => {+ if (e.id === PANE) {+ await update($, streamId, n => n + 1);+ }++ return next(e);+ });++ on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {+ const ui = $.ui.resolve(e);+ const { Box, Text } = ui;+ if (e.surface !== "terminal" || !("Image" in ui)) {+ return <Text>mobile-mirror needs the terminal, in kitty or Ghostty.</Text>;+ }++ const { file, generation, width, height } = await read($, shot);+ if (generation === 0) {+ return <Text dimColor>Waiting for the first frame…</Text>;+ }++ const device = await read($, target);+ if (!device) {+ return <Text dimColor>Run /mobile-mirror to pick a device.</Text>;+ }++ const isAndroid = device.platform === "android";+ const isAsking = await read($, isAskingUrl);+ const roomForImage = e.props.scroll.bodyRows - TOOLBAR_ROWS - (isAsking ? URL_FIELD_ROWS : 0);+ const size = fitInside(e.props.bodyColumns, roomForImage, width, height);+ const { Button, Input } = ui;++ const press = (button: string) => () => runAction($, `Press ${button}`, "mobile_press_button", { device: device.id, button });++ const openUrl = async (url: string) => {+ await update($, isAskingUrl, () => false);+ if (!url.trim()) {+ return;+ }++ await runAction($, `Open ${url.trim()}`, "mobile_open_url", { device: device.id, url: url.trim() });+ };++ return (+ <Box flexDirection='column'>+ <Box flexDirection='row' gap={1}>+ <Button key='home' label='Home' onPress={press("HOME")} />+ {isAndroid && <Button key='back' label='Back' onPress={press("BACK")} />}+ {isAndroid && <Button key='app-switch' label='App Switch' onPress={press("APP_SWITCH")} />}+ <Button key='url' label='URL' onPress={() => update($, isAskingUrl, asking => !asking)} />+ </Box>+ {isAsking && <Input key='url-field' label='URL ' placeholder='https://example.com' submitLabel='open' autoFocus onSubmit={openUrl} />}+ <Box>+ <ui.Image key={VIEW_KEY} source={{ file, format: "png", generation }} columns={size.columns} rows={size.rows} alt='device screen' />+ <Box position='absolute' top={0} left={0}>+ <ui.Client key={TAP_KEY} module='./tap.tsx' width={size.columns} height={size.rows} />+ </Box>+ </Box>+ </Box>+ );+ });+};diff --git a/plugin/hooks/tap.tsx b/plugin/hooks/tap.tsxnew file mode 100644index 0000000..3ec0e13--- /dev/null+++ b/plugin/hooks/tap.tsx@@ -0,0 +1,42 @@+import type { ClientKeyEvent, ClientPointerEvent, ClientSurface } from "claude-code";++type Pending = { keys: string[] };++// a post per frame at most, and a later one replaces an undelivered one, so keys are sent in batches+const FLUSH_MS = 50;++// Laid over the screenshot: posts each left click as a fraction of the picture (0..1 on both axes),+// and, once clicked, the keys typed while it holds the focus+export default function TapInput(_props: unknown, surface: ClientSurface<Pending>) {+ if (surface.state === undefined) {+ const pending: Pending = { keys: [] };++ surface.onPointer((e: ClientPointerEvent) => {+ if (e.type !== "down" || e.button !== "left" || surface.columns === 0 || surface.rows === 0) {+ return;+ }++ const x = e.fine?.x ?? e.x + 0.5;+ const y = e.fine?.y ?? e.y + 0.5;+ surface.post({ x: x / surface.columns, y: y / surface.rows });+ });++ surface.onKey((e: ClientKeyEvent) => {+ pending.keys.push(e.key);+ });++ surface.every(FLUSH_MS, () => {+ if (pending.keys.length === 0) {+ return;+ }++ surface.post({ keys: pending.keys.splice(0) });+ });++ surface.setState(pending);+ }++ const { Box } = surface.elements;++ return <Box width='100%' height='100%' />;+}diff --git a/plugin/types/index.d.ts b/plugin/types/index.d.tsnew file mode 100644index 0000000..b43a208--- /dev/null+++ b/plugin/types/index.d.ts@@ -0,0 +1,9 @@+export type Shot = { file: string; generation: number; width: number; height: number };+export type Platform = "android" | "ios";+export type Target = { id: string; platform: Platform; screenWidth: number; screenHeight: number };++declare module "claude-code" {+ interface PluginState {+ "mobile-mcp": { shot: Shot; target: Target | null; streamId: number; isAskingUrl: boolean }+ }+}diff --git a/test/mobile-mirror.test.ts b/test/mobile-mirror.test.tsnew file mode 100644index 0000000..bc5090f--- /dev/null+++ b/test/mobile-mirror.test.ts@@ -0,0 +1,62 @@+import { expect, test } from "@playwright/test";++import { CELL_ASPECT, fitInside, pngSize } from "../plugin/hooks/png";+import { keysToActions } from "../plugin/hooks/keys";++function pngHeaderOfSize(width: number, height: number): Uint8Array {+ const bytes = new Uint8Array(24);+ const view = new DataView(bytes.buffer);+ view.setUint32(16, width);+ view.setUint32(20, height);+ return bytes;+}++test.describe("mobile-mirror picture sizing", () => {+ test("reads width and height from the PNG header", () => {+ expect(pngSize(pngHeaderOfSize(356, 800))).toEqual({ width: 356, height: 800 });+ });++ test("a portrait screenshot in a short pane is limited by height", () => {+ const columns = Math.floor((20 * 400 * CELL_ASPECT) / 800);+ expect(fitInside(80, 20, 400, 800)).toEqual({ columns, rows: 20 });+ });++ test("a landscape screenshot in a tall pane is limited by width", () => {+ const rows = Math.floor((40 * 400) / 800 / CELL_ASPECT);+ expect(fitInside(40, 100, 800, 400)).toEqual({ columns: 40, rows });+ });++ test("never exceeds 255 cells and keeps the aspect while capped", () => {+ const columns = Math.floor((255 * 100 * CELL_ASPECT) / 1000);+ expect(fitInside(300, 1000, 100, 1000)).toEqual({ columns, rows: 255 });+ });++ test("a picture with no width or height fills the box instead of dividing by zero", () => {+ expect(fitInside(40, 20, 0, 800)).toEqual({ columns: 40, rows: 20 });+ expect(fitInside(40, 20, 400, 0)).toEqual({ columns: 40, rows: 20 });+ });+});++test.describe("mobile-mirror keys", () => {+ test("consecutive characters become one text action", () => {+ expect(keysToActions(["h", "i", "space", "!"], "android")).toEqual([{ type: "text", text: "hi !" }]);+ });++ test("return splits text and presses ENTER", () => {+ expect(keysToActions(["a", "return", "b"], "ios")).toEqual([+ { type: "text", text: "a" },+ { type: "button", button: "ENTER" },+ { type: "text", text: "b" },+ ]);+ });++ test("backspace is a button on android and typed text on ios", () => {+ expect(keysToActions(["backspace"], "android")).toEqual([{ type: "button", button: "BACKSPACE" }]);+ expect(keysToActions(["backspace"], "ios")).toEqual([{ type: "text", text: "\b" }]);+ });++ test("arrows press the dpad on android and are dropped on ios", () => {+ expect(keysToActions(["up"], "android")).toEqual([{ type: "button", button: "DPAD_UP" }]);+ expect(keysToActions(["up", "pageup"], "ios")).toEqual([]);+ });+});