Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/claude/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ calls when prompted. Run `claude plugin marketplace update mobile-dev` to update
[nodejs.org](https://nodejs.org), then restart Claude.
- **iOS:** Xcode 26 or later with an installed simulator runtime. Physical iPhone
logs need Xcode 27 or later.
- **Android:** Android SDK platform-tools and emulator, and an AVD or a device with
USB or wireless debugging authorized.
- **Android:** Android SDK Platform-Tools for an authorized USB or wireless device.
For a virtual device, also install Android Emulator and create an AVD with a system image.

## What it runs on your Mac

Expand Down
8 changes: 6 additions & 2 deletions docs/devices.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Discovery preserves remembered disconnected and unavailable devices. Their `tran

The native panel targets Codex desktop, iOS simulators, and Android emulators or attached devices. The active Mobile Dev MCP server also works through stdio in a local MCP client. Use the selected UDID for iOS tools and the selected running serial for Android tools. This plugin does not build the user's app. Codex's permission and confirmation rules still apply to tool calls.

Android logs need `adb` from an installed Android SDK. The reader checks `ANDROID_HOME`, `ANDROID_SDK_ROOT`, `~/Library/Android/sdk`, then PATH. Metro logs need an existing local Metro server and an app with an inspector target. The log tools connect to that server without starting it.
Android tools look for the SDK in `ANDROID_HOME`, `ANDROID_SDK_ROOT`, and the default SDK location, then check `PATH` for executables. Metro logs need an existing local Metro server and an app with an inspector target. The log tools connect to that server without starting it.

## Device panel

Expand All @@ -38,7 +38,11 @@ You can request fullscreen or a tool-only workflow. Planning, docs, code review,

## Android

Install Android SDK platform-tools and emulator. Create an AVD in Android Studio or connect an Android device and authorize adb access. The Android panel lists devices without booting one. Selecting an AVD boots it if needed, then starts the bundled Node.js serve-emu CLI on a private loopback port. Home, Back, Recents, Lock, pointer gestures, and typing use scrcpy's control socket. Closing the panel leaves the emulator running. AVDs start without a separate emulator window. A failed emulator process reports its exit right away instead of waiting for the boot timeout.
Install **Android SDK Platform-Tools** in Android Studio's **SDK Manager → SDK Tools**. For a virtual device, also install **Android Emulator**, then create an AVD with a system image in **Device Manager**. For a physical phone, enable USB or wireless debugging and authorize your computer. [Virtual device setup](https://developer.android.com/studio/run/managing-avds) · [Physical device setup](https://developer.android.com/studio/run/device)

For a custom SDK, set `ANDROID_HOME` to the **Android SDK Location** shown in SDK Manager. The default SDK paths checked on macOS and Linux are `~/Library/Android/sdk` and `~/Android/Sdk`, respectively. On either system, verify a phone with `"$ANDROID_HOME/platform-tools/adb" devices -l` or list configured AVDs with `"$ANDROID_HOME/emulator/emulator" -list-avds` after setting that variable. [Android SDK environment variables](https://developer.android.com/tools/variables)

The Android panel lists devices without booting one. Selecting an AVD boots it if needed, then starts the bundled Node.js serve-emu CLI on a private loopback port. Home, Back, Recents, Lock, pointer gestures, and typing use scrcpy's control socket. Closing the panel leaves the emulator running. AVDs start without a separate emulator window. A failed emulator process reports its exit right away instead of waiting for the boot timeout.

The Android dropdown shows **Connected devices** first, with USB or Wi-Fi labels, then **Emulators**. It refreshes every three seconds while the Android panel is visible, and when opening the dropdown. Physical devices use ADB discovery: enable USB debugging and authorize the computer, or pair the device for wireless debugging. Offline and unauthorized devices remain visible with their state. Emulators keep their AVD name while unauthorized. An emulator restored from a quick-boot snapshot can stay unauthorized because adb does not repeat the key exchange; the panel reconnects adb at most every 5 seconds while an AVD boots, and for up to 15 seconds after you select an already running emulator. Selecting an authorized phone connects its screen and shares its serial and transport with the chat. Bundled scrcpy mirrors and controls the phone without installing a companion app. Physical Android devices support the existing screen, input, screenshot, native log, and performance tools; emulator boot and stop controls do not apply to them.

Expand Down
30 changes: 28 additions & 2 deletions packages/core/src/android-sdk.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,33 @@
import { constants } from "node:fs";
import { access } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { delimiter, dirname, isAbsolute, join } from "node:path";

export const missingAdbMessage = "Android SDK Platform-Tools (adb) could not be found. Install Android SDK Platform-Tools in Android Studio’s SDK Manager. For a custom SDK location, set ANDROID_HOME to the SDK folder or add platform-tools to PATH, then restart the host app.";

// Android SDK locations, in the order the SDK's own tools check them.
export function androidSdkRoots(): string[] {
return [process.env.ANDROID_HOME, process.env.ANDROID_SDK_ROOT, join(homedir(), "Library/Android/sdk")].filter(root => !!root) as string[];
const defaultRoot = process.platform === "win32"
? join(process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local"), "Android", "Sdk")
: join(homedir(), process.platform === "darwin" ? "Library/Android/sdk" : "Android/Sdk");
return [...new Set([process.env.ANDROID_HOME, process.env.ANDROID_SDK_ROOT, defaultRoot].filter((root): root is string => !!root))];
}

export function sdkExecutable(name: string) {
return process.platform === "win32" ? `${name}.exe` : name;
}

export async function sdkToolPath(name: "adb" | "emulator" | "sqlite3") {
const executable = sdkExecutable(name);
for (const root of androidSdkRoots()) {
const path = join(root, name === "emulator" ? "emulator" : "platform-tools", executable);
try { await access(path, constants.X_OK); return path; } catch { /* Try the next SDK, then PATH. */ }
}
return executable;
}

/** serve-emu and agent-device start SDK tools by name. Preserve PATH when a tool was found there. */
export function androidToolPath(tools: string[], path = process.env.PATH ?? "") {
const inherited = path ? path.split(delimiter) : [];
return [...new Set([...tools.filter(isAbsolute).map(tool => dirname(tool)), ...inherited])].join(delimiter);
}
2 changes: 1 addition & 1 deletion packages/core/src/android-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function registerAndroidTools(server: McpServer, android: ServeEmu, appUr
title: "List Android devices", description: "Discover physical Android devices over USB or Wi-Fi, running emulators and installed AVDs through ADB. Returns device kind, ADB serial (udid), model when available, transport for physical devices, and state (authorized devices use Booted). Pass the serial as deviceId to select a running device in the Android panel. Listing does not boot, pair, authorize, or stream a device.", inputSchema: {}, annotations: read,
}, guarded(async () => {
const status = await android.list();
const text = status.connected ? JSON.stringify(status.devices) : status.error!;
const text = status.error ?? status.setupHint ?? JSON.stringify(status.devices);
return deviceListResult(status, text);
}));
for (const action of ["boot", "shutdown"] as const) server.registerTool(`mobile_${action}_android_emulator`, {
Expand Down
12 changes: 8 additions & 4 deletions packages/core/src/app-control/commands.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { execFile } from "node:child_process";
import { constants } from "node:fs";
import { access, mkdtemp, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ExpectedOperationError, expectedOutcome } from "@mobile-dev/shared/error-reporting.ts";
import { annotateDeviceCommand, classifyCommandFailure } from "@mobile-dev/shared/device-command-diagnostics.ts";
import { adbPath } from "../native-logs.ts";
import { androidSdkRoots } from "../android-sdk.ts";
import { androidSdkRoots, sdkExecutable } from "../android-sdk.ts";

export type CommandOptions = { timeout: number; input?: string; maxBuffer?: number };
export type CommandRunner = (file: string, args: string[], options: CommandOptions) => Promise<string>;
Expand Down Expand Up @@ -40,8 +41,8 @@ async function findAapt2(): Promise<string | null> {
const versions = await readdir(join(root, "build-tools")).catch(() => []);
versions.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
for (const version of versions) {
const path = join(root, "build-tools", version, "aapt2");
if (await access(path).then(() => true, () => false)) return aapt2 = path;
const path = join(root, "build-tools", version, sdkExecutable("aapt2"));
if (await access(path, constants.X_OK).then(() => true, () => false)) return aapt2 = path;
}
}
return null;
Expand Down Expand Up @@ -69,7 +70,10 @@ export function commandError(error: unknown, action: string, command?: string):
const message = output.split("\n").map(line => line.trim()).filter(line => line && !/^Underlying error|^An error was encountered/.test(line)).slice(0, 3).join(" ");
const text = `${action} failed${message ? `: ${message}` : "."}`;
if (unavailable.test(output)) return new ExpectedOperationError("device_unavailable", text);
if (error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT") return new ExpectedOperationError("unsupported_platform", `${action} needs ${process.platform === "darwin" ? "Xcode or the Android SDK" : "macOS and Xcode"}.`);
if (error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT") {
const requirement = command?.startsWith("adb_") ? "Android SDK Platform-Tools" : "macOS and Xcode";
return new ExpectedOperationError("unsupported_platform", `${action} needs ${requirement}.`);
}
const failure = new Error(text, { cause: error });
// Reports name the command and how it ended instead of repeating its output.
return command === undefined ? failure : annotateDeviceCommand(failure, command, classifyCommandFailure(error));
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/app-storage/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export class AndroidContainer implements AppContainer {
async reset() {
let output: string;
try { output = await this.commands.run(await this.commands.adb(), ["-s", this.serial, "shell", `pm clear ${this.bundleId}`], { timeout: 30000 }); }
catch (error) { throw commandError(error, "Clearing app data"); }
catch (error) { throw commandError(error, "Clearing app data", "adb_shell"); }
if (!/Success/.test(output)) throw new ExpectedOperationError("invalid_input", `Clearing app data failed: ${output.trim().split("\n")[0] || "pm clear did not succeed."}`);
}
}
Expand All @@ -183,5 +183,5 @@ export function runAsError(error: unknown, action: string, bundleId: string): Er
const output = commandOutput(error);
if (/not debuggable/.test(output)) return new ExpectedOperationError("unsupported_platform", `${bundleId} is a release build. Android only allows reading app data of debuggable builds; Reset app data still works.`);
if (/unknown package|Unknown package|is unknown/.test(output)) return new ExpectedOperationError("invalid_input", `${bundleId} is not installed on this device.`);
return commandError(error, action);
return commandError(error, action, "adb_shell");
}
19 changes: 8 additions & 11 deletions packages/core/src/native-logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { execFile, spawn } from "node:child_process";
import { promisify } from "node:util";
import { StringDecoder } from "node:string_decoder";
import { setTimeout as delay } from "node:timers/promises";
import { access } from "node:fs/promises";
import { join } from "node:path";
import type { LogRecord, LogSourceStatus, NativeLogTarget } from "@mobile-dev/shared/logs.ts";
import { errorMessage } from "@mobile-dev/shared/protocol.ts";
import { androidSdkRoots } from "./android-sdk.ts";
import { missingAdbMessage, sdkToolPath } from "./android-sdk.ts";
import { isMissingFile } from "./install-integrity.ts";
import { ExpectedOperationError } from "@mobile-dev/shared/error-reporting.ts";
import { parseIOSLog, parseLogcat } from "./log-parsers.ts";
import { physicalIosLogCommand } from "./physical-ios-logs.ts";
import { IOSLogProcessingTelemetry } from "./telemetry.ts";
Expand All @@ -15,16 +15,13 @@ const execute = promisify(execFile);
export type LogSink = { log: (log: LogRecord) => void; status: (status: LogSourceStatus) => void };
export type StopLogSource = () => Promise<void>;

export async function adbPath(): Promise<string> {
for (const root of androidSdkRoots()) {
const path = join(root, "platform-tools/adb");
try { await access(path); return path; } catch { /* Try the next SDK, then PATH. */ }
}
return "adb";
}
export const adbPath = () => sdkToolPath("adb");

export async function listAndroidLogDevices(): Promise<{ id: string; name: string }[]> {
const { stdout } = await execute(await adbPath(), ["devices", "-l"], { timeout: 5000, maxBuffer: 1024 * 1024 });
const { stdout } = await execute(await adbPath(), ["devices", "-l"], { timeout: 5000, maxBuffer: 1024 * 1024 }).catch(error => {
if (isMissingFile(error)) throw new ExpectedOperationError("unsupported_platform", missingAdbMessage);
throw error;
});
return stdout.split("\n").flatMap(line => {
const match = line.match(/^(\S+)\s+device(?:\s|$)(.*)/);
return match ? [{ id: match[1], name: match[2].match(/model:(\S+)/)?.[1].replace(/_/g, " ") ?? match[1] }] : [];
Expand Down
Loading
Loading