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: move iphone-simulator calls to use mobilecli binary (#241)
Gil Megidishcb0c290b6029
diff --git a/package-lock.json b/package-lock.jsonindex 374de0b..ec99c1a 100644--- a/package-lock.json+++ b/package-lock.json@@ -44,7 +44,7 @@"node": ">=18"},"optionalDependencies": {- "@mobilenext/mobilecli": "0.0.38"+ "@mobilenext/mobilecli": "0.0.46"}},"node_modules/@babel/code-frame": {@@ -717,9 +717,9 @@}},"node_modules/@mobilenext/mobilecli": {- "version": "0.0.38",- "resolved": "https://registry.npmjs.org/@mobilenext/mobilecli/-/mobilecli-0.0.38.tgz",- "integrity": "sha512-qTBHAi+aOL73tYj79C704JfWeYRCyOU4O/5TcgDWl8PBDPmw9D9NxDIA0mFrfYCSW0O17K1WCXh8dwFZgxHjwQ==",+ "version": "0.0.46",+ "resolved": "https://registry.npmjs.org/@mobilenext/mobilecli/-/mobilecli-0.0.46.tgz",+ "integrity": "sha512-opdmd+kQTGwgl4y9d9Y78BQQNHM/3k6R3ZvvEOKTFb3iJbifRvfQZsGsSgGJqA+ZCbNaWnlt+M8pH+oILRpJXQ==","license": "MIT","optional": true,"bin": {diff --git a/package.json b/package.jsonindex 554db24..57aba73 100644--- a/package.json+++ b/package.json@@ -32,7 +32,7 @@"zod-to-json-schema": "3.25.0"},"optionalDependencies": {- "@mobilenext/mobilecli": "0.0.38"+ "@mobilenext/mobilecli": "0.0.46"},"devDependencies": {"@eslint/eslintrc": "^3.2.0",diff --git a/src/android.ts b/src/android.tsindex 94ba18b..0b6d73e 100644--- a/src/android.ts+++ b/src/android.ts@@ -514,6 +514,39 @@ export class AndroidDeviceManager {return "mobile";}+ private getDeviceVersion(deviceId: string): string {+ try {+ const output = execFileSync(getAdbPath(), ["-s", deviceId, "shell", "getprop", "ro.build.version.release"], {+ timeout: 5000,+ }).toString().trim();+ return output;+ } catch (error) {+ return "unknown";+ }+ }++ private getDeviceName(deviceId: string): string {+ try {+ // Try getting AVD name first (for emulators)+ const avdName = execFileSync(getAdbPath(), ["-s", deviceId, "shell", "getprop", "ro.boot.qemu.avd_name"], {+ timeout: 5000,+ }).toString().trim();++ if (avdName !== "") {+ // Replace underscores with spaces (e.g., "Pixel_9_Pro" -> "Pixel 9 Pro")+ return avdName.replace(/_/g, " ");+ }++ // Fall back to product model+ const output = execFileSync(getAdbPath(), ["-s", deviceId, "shell", "getprop", "ro.product.model"], {+ timeout: 5000,+ }).toString().trim();+ return output;+ } catch (error) {+ return deviceId;+ }+ }+public getConnectedDevices(): AndroidDevice[] {try {const names = execFileSync(getAdbPath(), ["devices"])@@ -533,4 +566,26 @@ export class AndroidDeviceManager {return [];}}++ public getConnectedDevicesWithDetails(): Array<AndroidDevice & { version: string, name: string }> {+ try {+ const names = execFileSync(getAdbPath(), ["devices"])+ .toString()+ .split("\n")+ .map(line => line.trim())+ .filter(line => line !== "")+ .filter(line => !line.startsWith("List of devices attached"))+ .map(line => line.split("\t")[0]);++ return names.map(deviceId => ({+ deviceId,+ deviceType: this.getDeviceType(deviceId),+ version: this.getDeviceVersion(deviceId),+ name: this.getDeviceName(deviceId),+ }));+ } catch (error) {+ console.error("Could not execute adb command, maybe ANDROID_HOME is not set?");+ return [];+ }+ }}diff --git a/src/ios.ts b/src/ios.tsindex 51a1dd4..4021367 100644--- a/src/ios.ts+++ b/src/ios.ts@@ -249,6 +249,12 @@ export class IosManager {return json.DeviceName;}+ public getDeviceInfo(deviceId: string): InfoCommandOutput {+ const output = execFileSync(getGoIosPath(), ["info", "--udid", deviceId]).toString();+ const json: InfoCommandOutput = JSON.parse(output);+ return json;+ }+public listDevices(): IosDevice[] {if (!this.isGoIosInstalled()) {console.error("go-ios is not installed, no physical iOS devices can be detected");@@ -264,4 +270,24 @@ export class IosManager {return devices;}++ public listDevicesWithDetails(): Array<IosDevice & { version: string }> {+ if (!this.isGoIosInstalled()) {+ console.error("go-ios is not installed, no physical iOS devices can be detected");+ return [];+ }++ const output = execFileSync(getGoIosPath(), ["list"]).toString();+ const json: ListCommandOutput = JSON.parse(output);+ const devices = json.deviceList.map(device => {+ const info = this.getDeviceInfo(device);+ return {+ deviceId: device,+ deviceName: info.DeviceName,+ version: info.ProductVersion,+ };+ });++ return devices;+ }}diff --git a/src/iphone-simulator.ts b/src/iphone-simulator.tsindex 8f6170a..bca830e 100644--- a/src/iphone-simulator.ts+++ b/src/iphone-simulator.ts@@ -13,17 +13,6 @@ export interface Simulator {state: string;}-interface ListDevicesResponse {- devices: {- [key: string]: Array<{- state: string;- name: string;- isAvailable: boolean;- udid: string;- }>,- },-}-interface AppInfo {ApplicationType: string;Bundle: string;@@ -281,40 +270,3 @@ export class Simctl implements Robot {return wda.getOrientation();}}--export class SimctlManager {-- public listSimulators(): Simulator[] {- // detect if this is a mac- if (process.platform !== "darwin") {- // don't even try to run xcrun- return [];- }-- try {- const text = execFileSync("xcrun", ["simctl", "list", "devices", "-j"]).toString();- const json: ListDevicesResponse = JSON.parse(text);- return Object.values(json.devices).flatMap(device => {- return device.map(d => {- return {- name: d.name,- uuid: d.udid,- state: d.state,- };- });- });- } catch (error) {- console.error("Error listing simulators", error);- return [];- }- }-- public listBootedSimulators(): Simulator[] {- return this.listSimulators()- .filter(simulator => simulator.state === "Booted");- }-- public getSimulator(uuid: string): Simctl {- return new Simctl(uuid);- }-}diff --git a/src/mobile-device.ts b/src/mobile-device.tsnew file mode 100644index 0000000..bd068ab--- /dev/null+++ b/src/mobile-device.ts@@ -0,0 +1,216 @@+import { Mobilecli } from "./mobilecli";+import { Button, InstalledApp, Orientation, Robot, ScreenElement, ScreenSize, SwipeDirection } from "./robot";++interface InstalledAppsResponse {+ status: "ok",+ data: Array<{+ packageName: string;+ appName?: string; // ios+ version?: string; // ios+ }>;+}++interface DeviceInfoResponse {+ status: "ok",+ data: {+ device: {+ id: string;+ name: string;+ platform: string;+ type: string;+ version: string;+ state: string;+ screenSize?: {+ width: number;+ height: number;+ scale: number;+ };+ };+ };+}++interface UIElementResponse {+ type: string;+ label?: string;+ text?: string;+ name?: string;+ value?: string;+ identifier?: string;+ rect: {+ x: number;+ y: number;+ width: number;+ height: number;+ };+ focused?: boolean;+}++interface DumpUIResponse {+ status: "ok",+ data: {+ elements: UIElementResponse[];+ };+}++interface OrientationResponse {+ status: "ok",+ data: {+ orientation: Orientation;+ };+}++export class MobileDevice implements Robot {++ private mobilecli: Mobilecli;++ public constructor(private deviceId: string) {+ this.mobilecli = new Mobilecli();+ }++ private runCommand(args: string[]): string {+ const fullArgs = [...args, "--device", this.deviceId];+ return this.mobilecli.executeCommand(fullArgs);+ }++ public async getScreenSize(): Promise<ScreenSize> {+ const response = JSON.parse(this.runCommand(["device", "info"])) as DeviceInfoResponse;+ if (response.data.device.screenSize) {+ return response.data.device.screenSize;+ }+ return { width: 0, height: 0, scale: 1.0 };+ }++ public async swipe(direction: SwipeDirection): Promise<void> {+ const screenSize = await this.getScreenSize();+ const centerX = Math.floor(screenSize.width / 2);+ const centerY = Math.floor(screenSize.height / 2);+ const distance = 400; // Default distance in pixels++ let startX = centerX;+ let startY = centerY;+ let endX = centerX;+ let endY = centerY;++ switch (direction) {+ case "up":+ startY = centerY + distance / 2;+ endY = centerY - distance / 2;+ break;+ case "down":+ startY = centerY - distance / 2;+ endY = centerY + distance / 2;+ break;+ case "left":+ startX = centerX + distance / 2;+ endX = centerX - distance / 2;+ break;+ case "right":+ startX = centerX - distance / 2;+ endX = centerX + distance / 2;+ break;+ }++ this.runCommand(["io", "swipe", `${startX},${startY},${endX},${endY}`]);+ }++ public async swipeFromCoordinate(x: number, y: number, direction: SwipeDirection, distance?: number): Promise<void> {+ const swipeDistance = distance || 400;+ let endX = x;+ let endY = y;++ switch (direction) {+ case "up":+ endY = y - swipeDistance;+ break;+ case "down":+ endY = y + swipeDistance;+ break;+ case "left":+ endX = x - swipeDistance;+ break;+ case "right":+ endX = x + swipeDistance;+ break;+ }++ this.runCommand(["io", "swipe", `${x},${y},${endX},${endY}`]);+ }++ public async getScreenshot(): Promise<Buffer> {+ const fullArgs = ["screenshot", "--device", this.deviceId, "--format", "png", "--output", "-"];+ return this.mobilecli.executeCommandBuffer(fullArgs);+ }++ public async listApps(): Promise<InstalledApp[]> {+ const response = JSON.parse(this.runCommand(["apps", "list"])) as InstalledAppsResponse;+ return response.data.map(app => ({+ appName: app.appName || app.packageName,+ packageName: app.packageName,+ })) as InstalledApp[];+ }++ public async launchApp(packageName: string): Promise<void> {+ this.runCommand(["apps", "launch", packageName]);+ }++ public async terminateApp(packageName: string): Promise<void> {+ this.runCommand(["apps", "terminate", packageName]);+ }++ public async installApp(path: string): Promise<void> {+ this.runCommand(["apps", "install", path]);+ }++ public async uninstallApp(bundleId: string): Promise<void> {+ this.runCommand(["apps", "uninstall", bundleId]);+ }++ public async openUrl(url: string): Promise<void> {+ this.runCommand(["url", url]);+ }++ public async sendKeys(text: string): Promise<void> {+ this.runCommand(["io", "text", text]);+ }++ public async pressButton(button: Button): Promise<void> {+ this.runCommand(["io", "button", button]);+ }++ public async tap(x: number, y: number): Promise<void> {+ this.runCommand(["io", "tap", `${x},${y}`]);+ }++ public async doubleTap(x: number, y: number): Promise<void> {+ // TODO: should move into mobilecli itself as "io doubletap"+ await this.tap(x, y);+ await this.tap(x, y);+ }++ public async longPress(x: number, y: number): Promise<void> {+ this.runCommand(["io", "longpress", `${x},${y}`]);+ }++ public async getElementsOnScreen(): Promise<ScreenElement[]> {+ const response = JSON.parse(this.runCommand(["dump", "ui"])) as DumpUIResponse;+ return response.data.elements.map(element => ({+ type: element.type,+ label: element.label,+ text: element.text,+ name: element.name,+ value: element.value,+ identifier: element.identifier,+ rect: element.rect,+ focused: element.focused,+ }));+ }++ public async setOrientation(orientation: Orientation): Promise<void> {+ this.runCommand(["device", "orientation", "set", orientation]);+ }++ public async getOrientation(): Promise<Orientation> {+ const response = JSON.parse(this.runCommand(["device", "orientation", "get"])) as OrientationResponse;+ return response.data.orientation;+ }+}diff --git a/src/mobilecli.ts b/src/mobilecli.tsindex 6478540..2bce8ba 100644--- a/src/mobilecli.ts+++ b/src/mobilecli.ts@@ -1,64 +1,135 @@import { existsSync } from "node:fs";import { dirname, join, sep } from "node:path";+import { execFileSync } from "node:child_process";-export const getMobilecliPath = (): string => {- if (process.env.MOBILECLI_PATH) {- return process.env.MOBILECLI_PATH;- }+export interface MobilecliDevicesOptions {+ includeOffline?: boolean;+ platform?: "ios" | "android";+ type?: "real" | "emulator" | "simulator";+}- const arch = process.arch;- const platform = process.platform;- let binaryName = "mobilecli";+export interface MobilecliDevicesResponse {+ status: "ok";+ data: {+ devices: Array<{+ id: string;+ name: string;+ platform: "android" | "ios";+ type: "real" | "emulator" | "simulator";+ version: string;+ }>;+ };+}- switch (platform) {- case "darwin":- if (arch === "arm64") {- binaryName += "-darwin-arm64";- } else {- binaryName += "-darwin-amd64";- }- break;+const TIMEOUT = 30000;+const MAX_BUFFER_SIZE = 1024 * 1024 * 4;- case "linux":- if (arch === "arm64") {- binaryName += "-linux-arm64";- } else {- binaryName += "-linux-amd64";- }- break;+export class Mobilecli {+ private path: string | null = null;++ constructor() { }- case "win32":- binaryName += "-windows-amd64.exe";- break;+ private getPath(): string {+ if (!this.path) {+ this.path = Mobilecli.getMobilecliPath();+ }+ return this.path;+ }++ public executeCommand(args: string[]): string {+ const path = this.getPath();+ return execFileSync(path, args, { encoding: "utf8" }).toString().trim();+ }- default:- throw new Error(`Unsupported platform: ${platform}`);+ public executeCommandBuffer(args: string[]): Buffer {+ const path = this.getPath();+ return execFileSync(path, args, {+ encoding: "buffer",+ maxBuffer: MAX_BUFFER_SIZE,+ timeout: TIMEOUT,+ }) as Buffer;}- // Check if mobile-mcp is installed as a package- const currentPath = __filename;- const pathParts = currentPath.split(sep);- const lastNodeModulesIndex = pathParts.lastIndexOf("node_modules");+ private static getMobilecliPath(): string {+ if (process.env.MOBILECLI_PATH) {+ return process.env.MOBILECLI_PATH;+ }++ const platform = process.platform;+ const arch = process.arch;++ const normalizedPlatform = platform === "win32" ? "windows" : platform;+ const normalizedArch = arch === "arm64" ? "arm64" : "amd64";+ const ext = platform === "win32" ? ".exe" : "";+ const binaryName = `mobilecli-${normalizedPlatform}-${normalizedArch}${ext}`;++ // Check if mobile-mcp is installed as a package+ const currentPath = __filename;+ const pathParts = currentPath.split(sep);+ const lastNodeModulesIndex = pathParts.lastIndexOf("node_modules");++ if (lastNodeModulesIndex !== -1) {+ // We're inside node_modules, go to the last node_modules in the path+ const nodeModulesParts = pathParts.slice(0, lastNodeModulesIndex + 1);+ const lastNodeModulesPath = nodeModulesParts.join(sep);+ const mobilecliPath = join(lastNodeModulesPath, "@mobilenext", "mobilecli", "bin", binaryName);++ if (existsSync(mobilecliPath)) {+ return mobilecliPath;+ }+ }- if (lastNodeModulesIndex !== -1) {- // We're inside node_modules, go to the last node_modules in the path- const nodeModulesParts = pathParts.slice(0, lastNodeModulesIndex + 1);- const lastNodeModulesPath = nodeModulesParts.join(sep);- const mobilecliPath = join(lastNodeModulesPath, "@mobilenext", "mobilecli", "bin", binaryName);+ // Not in node_modules, look one directory up from current script+ const scriptDir = dirname(__filename);+ const parentDir = dirname(scriptDir);+ const mobilecliPath = join(parentDir, "node_modules", "@mobilenext", "mobilecli", "bin", binaryName);if (existsSync(mobilecliPath)) {return mobilecliPath;}++ throw new Error(`Could not find mobilecli binary for platform: ${platform}`);}- // Not in node_modules, look one directory up from current script- const scriptDir = dirname(__filename);- const parentDir = dirname(scriptDir);- const mobilecliPath = join(parentDir, "node_modules", "@mobilenext", "mobilecli", "bin", binaryName);+ getVersion(): string {+ try {+ const output = this.executeCommand(["--version"]);+ if (output.startsWith("mobilecli version ")) {+ return output.substring("mobilecli version ".length);+ }- if (existsSync(mobilecliPath)) {- return mobilecliPath;+ return "failed";+ } catch (error: any) {+ return "failed " + error.message;+ }}- throw new Error(`Could not find mobilecli binary for platform: ${platform}`);-};+ getDevices(options?: MobilecliDevicesOptions): MobilecliDevicesResponse {+ const args = ["devices"];++ if (options) {+ if (options.includeOffline) {+ args.push("--include-offline");+ }++ if (options.platform) {+ if (options.platform !== "ios" && options.platform !== "android") {+ throw new Error(`Invalid platform: ${options.platform}. Must be "ios" or "android"`);+ }++ args.push("--platform", options.platform);+ }++ if (options.type) {+ if (options.type !== "real" && options.type !== "emulator" && options.type !== "simulator") {+ throw new Error(`Invalid type: ${options.type}. Must be "real", "emulator", or "simulator"`);+ }++ args.push("--type", options.type);+ }+ }++ const mobilecliOutput = this.executeCommand(args);+ return JSON.parse(mobilecliOutput) as MobilecliDevicesResponse;+ }+}diff --git a/src/server.ts b/src/server.tsindex 84cba9d..cab8067 100644--- a/src/server.ts+++ b/src/server.ts@@ -3,28 +3,27 @@ import { z } from "zod";import fs from "node:fs";import os from "node:os";import crypto from "node:crypto";-import { execFileSync } from "node:child_process";import { error, trace } from "./logger";import { AndroidRobot, AndroidDeviceManager } from "./android";import { ActionableError, Robot } from "./robot";-import { SimctlManager } from "./iphone-simulator";import { IosManager, IosRobot } from "./ios";import { PNG } from "./png";import { isScalingAvailable, Image } from "./image-utils";-import { getMobilecliPath } from "./mobilecli";+import { Mobilecli } from "./mobilecli";+import { MobileDevice } from "./mobile-device";++interface MobilecliDevice {+ id: string;+ name: string;+ platform: "android" | "ios";+ type: "real" | "emulator" | "simulator";+ version: string;+ state: "online" | "offline";+}interface MobilecliDevicesResponse {- status: "ok";- data: {- devices: Array<{- id: string;- name: string;- platform: "android" | "ios";- type: "real" | "emulator" | "simulator";- version: string;- }>;- };+ devices: MobilecliDevice[];}export const getAgentVersion = (): string => {@@ -62,9 +61,11 @@ export const createMcpServer = (): McpServer => {}, (async (args: any, _extra: any) => {try {trace(`Invoking ${name} with args: ${JSON.stringify(args)}`);+ const start = +new Date();const response = await cb(args);+ const duration = +new Date() - start;trace(`=> ${response}`);- posthog("tool_invoked", { "ToolName": name }).then();+ posthog("tool_invoked", { "ToolName": name, "Duration": duration }).then();return {content: [{ type: "text", text: response }],};@@ -124,57 +125,57 @@ export const createMcpServer = (): McpServer => {}};- const getMobilecliVersion = (): string => {+ const mobilecli = new Mobilecli();+ posthog("launch", {}).then();++ const ensureMobilecliAvailable = (): void => {try {- const path = getMobilecliPath();- const output = execFileSync(path, ["--version"], { encoding: "utf8" }).toString().trim();- if (output.startsWith("mobilecli version ")) {- return output.substring("mobilecli version ".length);+ const version = mobilecli.getVersion();+ if (version.startsWith("failed")) {+ throw new Error("mobilecli version check failed");}-- return "failed";} catch (error: any) {- return "failed " + error.message;+ throw new ActionableError(`mobilecli is not available or not working properly. Please review the documentation at https://github.com/mobile-next/mobile-mcp/wiki for installation instructions`);}};- const getMobilecliDevices = (): MobilecliDevicesResponse => {- const mobilecliPath = getMobilecliPath();- const mobilecliOutput = execFileSync(mobilecliPath, ["devices"], { encoding: "utf8" }).toString().trim();- return JSON.parse(mobilecliOutput) as MobilecliDevicesResponse;- };-- const mobilecliVersion = getMobilecliVersion();- posthog("launch", { "MobilecliVersion": mobilecliVersion }).then();+ const getRobotFromDevice = (deviceId: string): Robot => {- const simulatorManager = new SimctlManager();+ // from now on, we must have mobilecli working+ ensureMobilecliAvailable();- const getRobotFromDevice = (device: string): Robot => {+ // Check if it's an iOS deviceconst iosManager = new IosManager();- const androidManager = new AndroidDeviceManager();- const simulators = simulatorManager.listBootedSimulators();- const androidDevices = androidManager.getConnectedDevices();const iosDevices = iosManager.listDevices();-- // Check if it's a simulator- const simulator = simulators.find(s => s.name === device);- if (simulator) {- return simulatorManager.getSimulator(device);+ const iosDevice = iosDevices.find(d => d.deviceId === deviceId);+ if (iosDevice) {+ return new IosRobot(deviceId);}// Check if it's an Android device- const androidDevice = androidDevices.find(d => d.deviceId === device);+ const androidManager = new AndroidDeviceManager();+ const androidDevices = androidManager.getConnectedDevices();+ const androidDevice = androidDevices.find(d => d.deviceId === deviceId);if (androidDevice) {- return new AndroidRobot(device);+ return new AndroidRobot(deviceId);}- // Check if it's an iOS device- const iosDevice = iosDevices.find(d => d.deviceId === device);- if (iosDevice) {- return new IosRobot(device);+ // Check if it's a simulator (will later replace all other device types as well)+ const response = mobilecli.getDevices({+ platform: "ios",+ type: "simulator",+ includeOffline: false,+ });++ if (response.status === "ok" && response.data && response.data.devices) {+ for (const device of response.data.devices) {+ if (device.id === deviceId) {+ return new MobileDevice(deviceId);+ }+ }}- throw new ActionableError(`Device "${device}" not found. Use the mobile_list_available_devices tool to see available devices.`);+ throw new ActionableError(`Device "${deviceId}" not found. Use the mobile_list_available_devices tool to see available devices.`);};tool(@@ -185,64 +186,65 @@ export const createMcpServer = (): McpServer => {noParams},async ({}) => {- const iosManager = new IosManager();- const androidManager = new AndroidDeviceManager();- const simulators = simulatorManager.listBootedSimulators();- const simulatorNames = simulators.map(d => d.name);- const androidDevices = androidManager.getConnectedDevices();- const iosDevices = await iosManager.listDevices();- const iosDeviceNames = iosDevices.map(d => d.deviceId);- const androidTvDevices = androidDevices.filter(d => d.deviceType === "tv").map(d => d.deviceId);- const androidMobileDevices = androidDevices.filter(d => d.deviceType === "mobile").map(d => d.deviceId);-- if (true) {- // gilm: this is new code to verify first that mobilecli detects more or equal number of devices.- // in an attempt to make the smoothest transition from go-ios+xcrun+adb+iproxy+sips+imagemagick+wda to- // a single cli tool.- const deviceCount = simulators.length + iosDevices.length + androidDevices.length;-- let mobilecliDeviceCount = 0;- try {- const response = getMobilecliDevices();- if (response.status === "ok" && response.data && response.data.devices) {- mobilecliDeviceCount = response.data.devices.length;- }- } catch (error: any) {- // if mobilecli fails, we'll just set count to 0- }-- if (deviceCount === mobilecliDeviceCount) {- posthog("debug_mobilecli_same_number_of_devices", {- "DeviceCount": deviceCount,- "MobilecliDeviceCount": mobilecliDeviceCount,- }).then();- } else {- posthog("debug_mobilecli_different_number_of_devices", {- "DeviceCount": deviceCount,- "MobilecliDeviceCount": mobilecliDeviceCount,- "DeviceCountDifference": deviceCount - mobilecliDeviceCount,- }).then();- }- }- const resp = ["Found these devices:"];- if (simulatorNames.length > 0) {- resp.push(`iOS simulators: [${simulatorNames.join(",")}]`);- }+ // from today onward, we must have mobilecli working+ ensureMobilecliAvailable();- if (iosDevices.length > 0) {- resp.push(`iOS devices: [${iosDeviceNames.join(",")}]`);+ const iosManager = new IosManager();+ const androidManager = new AndroidDeviceManager();+ const devices: MobilecliDevice[] = [];++ // Get Android devices with details+ const androidDevices = androidManager.getConnectedDevicesWithDetails();+ for (const device of androidDevices) {+ devices.push({+ id: device.deviceId,+ name: device.name,+ platform: "android",+ type: "emulator",+ version: device.version,+ state: "online",+ });}- if (androidMobileDevices.length > 0) {- resp.push(`Android devices: [${androidMobileDevices.join(",")}]`);+ // Get iOS physical devices with details+ try {+ const iosDevices = iosManager.listDevicesWithDetails();+ for (const device of iosDevices) {+ devices.push({+ id: device.deviceId,+ name: device.deviceName,+ platform: "ios",+ type: "real",+ version: device.version,+ state: "online",+ });+ }+ } catch (error: any) {+ // If go-ios is not available, silently skip}- if (androidTvDevices.length > 0) {- resp.push(`Android TV devices: [${androidTvDevices.join(",")}]`);+ // Get iOS simulators from mobilecli (excluding offline devices)+ const response = mobilecli.getDevices({+ platform: "ios",+ type: "simulator",+ includeOffline: false,+ });+ if (response.status === "ok" && response.data && response.data.devices) {+ for (const device of response.data.devices) {+ devices.push({+ id: device.id,+ name: device.name,+ platform: device.platform,+ type: device.type,+ version: device.version,+ state: "online",+ });+ }}- return resp.join("\n");+ const out: MobilecliDevicesResponse = { devices };+ return JSON.stringify(out);});diff --git a/test/iphone-simulator.ts b/test/iphone-simulator.tsindex 10f25c8..0065d4a 100644--- a/test/iphone-simulator.ts+++ b/test/iphone-simulator.ts@@ -2,19 +2,26 @@ import assert from "node:assert";import { randomBytes } from "node:crypto";import { PNG } from "../src/png";-import { SimctlManager } from "../src/iphone-simulator";+import { MobileDevice } from "../src/mobile-device";+import { Mobilecli } from "../src/mobilecli";describe("iphone-simulator", () => {- const manager = new SimctlManager();- const bootedSimulators = manager.listBootedSimulators();- const hasOneSimulator = bootedSimulators.length === 1;- const simctl = manager.getSimulator(bootedSimulators?.[0]?.uuid || "");+ const mobilecli = new Mobilecli();+ const devicesResponse = mobilecli.getDevices({+ platform: "ios",+ type: "simulator",+ includeOffline: false,+ });++ const bootedSimulators = devicesResponse.data.devices;+ const hasOneSimulator = bootedSimulators.length >= 1;+ const device = new MobileDevice(bootedSimulators?.[0]?.id || "");const restartApp = async (app: string) => {- await simctl.launchApp(app);- await simctl.terminateApp(app);- await simctl.launchApp(app);+ await device.launchApp(app);+ await device.terminateApp(app);+ await device.launchApp(app);};const restartPreferencesApp = async () => {@@ -30,21 +37,21 @@ describe("iphone-simulator", () => {await restartPreferencesApp();// make sure "General" is present (since it's at the top of the list)- const elements1 = await simctl.getElementsOnScreen();+ const elements1 = await device.getElementsOnScreen();assert.ok(elements1.findIndex(e => e.name === "com.apple.settings.general") !== -1);// swipe up (bottom of screen to top of screen)- await simctl.swipe("up");+ await device.swipe("up");// make sure "General" is not visible now- const elements2 = await simctl.getElementsOnScreen();+ const elements2 = await device.getElementsOnScreen();assert.ok(elements2.findIndex(e => e.name === "com.apple.settings.general") === -1);// swipe down- await simctl.swipe("down");+ await device.swipe("down");// make sure "General" is visible again- const elements3 = await simctl.getElementsOnScreen();+ const elements3 = await device.getElementsOnScreen();assert.ok(elements3.findIndex(e => e.name === "com.apple.settings.general") !== -1);});@@ -54,33 +61,33 @@ describe("iphone-simulator", () => {// find new reminder elementawait new Promise(resolve => setTimeout(resolve, 3000));- const elements = await simctl.getElementsOnScreen();+ const elements = await device.getElementsOnScreen();const newElement = elements.find(e => e.label === "New Reminder");assert.ok(newElement !== undefined, "should have found New Reminder element");// click on new reminder- await simctl.tap(newElement.rect.x, newElement.rect.y);+ await device.tap(newElement.rect.x, newElement.rect.y);// wait for keyboard to appearawait new Promise(resolve => setTimeout(resolve, 1000));// send keys with press button "Enter"const random1 = randomBytes(8).toString("hex");- await simctl.sendKeys(random1);- await simctl.pressButton("ENTER");+ await device.sendKeys(random1);+ await device.pressButton("ENTER");// send keys with "\n"const random2 = randomBytes(8).toString("hex");- await simctl.sendKeys(random2 + "\n");+ await device.sendKeys(random2 + "\n");- const elements2 = await simctl.getElementsOnScreen();+ const elements2 = await device.getElementsOnScreen();assert.ok(elements2.findIndex(e => e.value === random1) !== -1);assert.ok(elements2.findIndex(e => e.value === random2) !== -1);});it("should be able to get the screen size", async function() {hasOneSimulator || this.skip();- const screenSize = await simctl.getScreenSize();+ const screenSize = await device.getScreenSize();assert.ok(screenSize.width > 256);assert.ok(screenSize.height > 256);assert.ok(screenSize.scale >= 1);@@ -89,13 +96,13 @@ describe("iphone-simulator", () => {it("should be able to get screenshot", async function() {hasOneSimulator || this.skip();- const screenshot = await simctl.getScreenshot();+ const screenshot = await device.getScreenshot();assert.ok(screenshot.length > 64 * 1024);// must be a valid png image that matches the screen sizeconst image = new PNG(screenshot);const pngSize = image.getDimensions();- const screenSize = await simctl.getScreenSize();+ const screenSize = await device.getScreenSize();// wda returns screen size as points, round upassert.equal(Math.ceil(pngSize.width / screenSize.scale), screenSize.width);@@ -105,10 +112,10 @@ describe("iphone-simulator", () => {it("should be able to open url", async function() {hasOneSimulator || this.skip();// simply checking thato openurl with https:// launches safari- await simctl.openUrl("https://www.example.com");+ await device.openUrl("https://www.example.com");await new Promise(resolve => setTimeout(resolve, 1000));- const elements = await simctl.getElementsOnScreen();+ const elements = await device.getElementsOnScreen();assert.ok(elements.length > 0);const addressBar = elements.find(element => element.type === "TextField" && element.name === "TabBarItemTitle" && element.label === "Address");@@ -117,7 +124,7 @@ describe("iphone-simulator", () => {it("should be able to list apps", async function() {hasOneSimulator || this.skip();- const apps = await simctl.listApps();+ const apps = await device.listApps();const packages = apps.map(app => app.packageName);assert.ok(packages.includes("com.apple.mobilesafari"));assert.ok(packages.includes("com.apple.reminders"));@@ -126,10 +133,10 @@ describe("iphone-simulator", () => {it("should be able to get elements on screen", async function() {hasOneSimulator || this.skip();- await simctl.pressButton("HOME");+ await device.pressButton("HOME");await new Promise(resolve => setTimeout(resolve, 2000));- const elements = await simctl.getElementsOnScreen();+ const elements = await device.getElementsOnScreen();assert.ok(elements.length > 0);// must have News app in home screen@@ -141,27 +148,48 @@ describe("iphone-simulator", () => {hasOneSimulator || this.skip();await restartPreferencesApp();await new Promise(resolve => setTimeout(resolve, 2000));- const elements = await simctl.getElementsOnScreen();+ const elements = await device.getElementsOnScreen();const buttons = elements.filter(e => e.type === "Button").map(e => e.label);assert.ok(buttons.includes("General"));assert.ok(buttons.includes("Accessibility"));// make sure app is terminated- await simctl.terminateApp("com.apple.Preferences");- const elements2 = await simctl.getElementsOnScreen();+ await device.terminateApp("com.apple.Preferences");+ const elements2 = await device.getElementsOnScreen();const buttons2 = elements2.filter(e => e.type === "Button").map(e => e.label);assert.ok(!buttons2.includes("General"));});+ /*+ it("should be able to get and set orientation", async function() {+ hasOneSimulator || this.skip();++ // Set to portrait and verify+ await device.setOrientation("portrait");+ const portrait = await device.getOrientation();+ assert.equal(portrait, "portrait");++ // Set to landscape and verify+ await device.setOrientation("landscape");+ const landscape = await device.getOrientation();+ assert.equal(landscape, "landscape");++ // Return to portrait+ await device.setOrientation("portrait");+ const portraitAgain = await device.getOrientation();+ assert.equal(portraitAgain, "portrait");+ });+ */+it("should throw an error if button is not supported", async function() {hasOneSimulator || this.skip();try {- await simctl.pressButton("NOT_A_BUTTON" as any);+ await device.pressButton("NOT_A_BUTTON" as any);assert.fail("should have thrown an error");} catch (error) {assert.ok(error instanceof Error);- assert.ok(error.message.includes("Button \"NOT_A_BUTTON\" is not supported"));+ assert.ok(error.message.includes("unsupported button: NOT_A_BUTTON"));}});});diff --git a/test/mobilecli.test.ts b/test/mobilecli.test.tsnew file mode 100644index 0000000..e707407--- /dev/null+++ b/test/mobilecli.test.ts@@ -0,0 +1,119 @@+import assert from "node:assert";+import { Mobilecli } from "../src/mobilecli";++type ExecuteCommandCall = {+ args: string[];+};++function createMockMobilecli(mockResponse: string): { mobilecli: Mobilecli; calls: ExecuteCommandCall[] } {+ const mobilecli = new Mobilecli();+ const calls: ExecuteCommandCall[] = [];++ mobilecli.executeCommand = function(args: string[]): string {+ calls.push({ args });+ return mockResponse;+ };++ return { mobilecli, calls };+}++describe("mobilecli", () => {++ const mobilecli = new Mobilecli();++ describe("getVersion", () => {+ it("should return a version string", () => {+ const version = mobilecli.getVersion();+ assert.ok(version.length > 0);+ assert.ok(!version.includes("failed"));+ });++ it("should return version in correct format", () => {+ const version = mobilecli.getVersion();+ // Version should be in format like "0.0.45" or similar+ const versionPattern = /^\d+\.\d+\.\d+/;+ assert.ok(versionPattern.test(version), `Version "${version}" should match pattern X.Y.Z`);+ });++ it("should return failed when MOBILECLI_PATH points to invalid location", () => {+ try {+ process.env.MOBILECLI_PATH = "/tmp";+ const mobilecli = new Mobilecli();+ const version = mobilecli.getVersion();+ assert.ok(version.includes("failed"), `Expected version to include "failed" but got: ${version}`);+ } finally {+ delete process.env.MOBILECLI_PATH;+ }+ });++ it("should call executeCommand with --version argument", () => {+ const { mobilecli, calls } = createMockMobilecli("mobilecli version 1.0.0");+ const version = mobilecli.getVersion();++ assert.equal(calls.length, 1);+ assert.deepEqual(calls[0].args, ["--version"]);+ assert.equal(version, "1.0.0");+ });+ });++ describe("getDevices", () => {+ const mockDevicesResponse = JSON.stringify({+ status: "ok",+ data: {+ devices: [+ {+ id: "device1",+ name: "Test Device",+ platform: "ios",+ type: "simulator",+ version: "17.0"+ }+ ]+ }+ });++ it("should call executeCommand with devices argument when no options", () => {+ const { mobilecli, calls } = createMockMobilecli(mockDevicesResponse);+ mobilecli.getDevices();++ assert.equal(calls.length, 1);+ assert.deepEqual(calls[0].args, ["devices"]);+ });++ it("should call executeCommand with platform filter", () => {+ const { mobilecli, calls } = createMockMobilecli(mockDevicesResponse);+ mobilecli.getDevices({ platform: "ios" });++ assert.equal(calls.length, 1);+ assert.deepEqual(calls[0].args, ["devices", "--platform", "ios"]);+ });++ it("should call executeCommand with type filter", () => {+ const { mobilecli, calls } = createMockMobilecli(mockDevicesResponse);+ mobilecli.getDevices({ type: "simulator" });++ assert.equal(calls.length, 1);+ assert.deepEqual(calls[0].args, ["devices", "--type", "simulator"]);+ });++ it("should call executeCommand with includeOffline flag", () => {+ const { mobilecli, calls } = createMockMobilecli(mockDevicesResponse);+ mobilecli.getDevices({ includeOffline: true });++ assert.equal(calls.length, 1);+ assert.deepEqual(calls[0].args, ["devices", "--include-offline"]);+ });++ it("should call executeCommand with combined options", () => {+ const { mobilecli, calls } = createMockMobilecli(mockDevicesResponse);+ mobilecli.getDevices({+ platform: "android",+ type: "emulator",+ includeOffline: true+ });++ assert.equal(calls.length, 1);+ assert.deepEqual(calls[0].args, ["devices", "--include-offline", "--platform", "android", "--type", "emulator"]);+ });+ });+});