From f254befcd2617021955de0579b3db987953b530c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Sat, 21 Nov 2026 14:39:11 +0100 Subject: [PATCH] fix(android): discover SDK tools and explain device setup --- apps/claude/README.md | 4 +- docs/devices.md | 8 +- packages/core/src/android-sdk.ts | 30 ++++- packages/core/src/android-tools.ts | 2 +- packages/core/src/app-control/commands.ts | 12 +- packages/core/src/app-storage/container.ts | 4 +- packages/core/src/native-logs.ts | 19 ++-- packages/core/src/serve-emu.ts | 49 +++++---- packages/core/test/android-sdk.test.ts | 104 ++++++++++++++++++ packages/core/test/android.test.ts | 30 +++++ packages/shared/src/protocol.ts | 1 + packages/skills/mobile-dev-setup/SKILL.md | 4 +- packages/ui/src/simulator-panel.ts | 4 +- packages/ui/test/simulator-panel.test.ts | 11 ++ .../src/content/docs/docs/getting-started.md | 8 +- 15 files changed, 239 insertions(+), 51 deletions(-) create mode 100644 packages/core/test/android-sdk.test.ts diff --git a/apps/claude/README.md b/apps/claude/README.md index a61c6d7e..1f737b80 100644 --- a/apps/claude/README.md +++ b/apps/claude/README.md @@ -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 diff --git a/docs/devices.md b/docs/devices.md index 4389e982..1cde9cab 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -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 @@ -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. diff --git a/packages/core/src/android-sdk.ts b/packages/core/src/android-sdk.ts index 12c97961..88e93417 100644 --- a/packages/core/src/android-sdk.ts +++ b/packages/core/src/android-sdk.ts @@ -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); } diff --git a/packages/core/src/android-tools.ts b/packages/core/src/android-tools.ts index 6b60468a..a18ccb54 100644 --- a/packages/core/src/android-tools.ts +++ b/packages/core/src/android-tools.ts @@ -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`, { diff --git a/packages/core/src/app-control/commands.ts b/packages/core/src/app-control/commands.ts index 75e0b73e..5ff9ebab 100644 --- a/packages/core/src/app-control/commands.ts +++ b/packages/core/src/app-control/commands.ts @@ -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; @@ -40,8 +41,8 @@ async function findAapt2(): Promise { 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; @@ -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)); diff --git a/packages/core/src/app-storage/container.ts b/packages/core/src/app-storage/container.ts index cc584b8f..0030671e 100644 --- a/packages/core/src/app-storage/container.ts +++ b/packages/core/src/app-storage/container.ts @@ -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."}`); } } @@ -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"); } diff --git a/packages/core/src/native-logs.ts b/packages/core/src/native-logs.ts index 6cde5e9c..e026f0bf 100644 --- a/packages/core/src/native-logs.ts +++ b/packages/core/src/native-logs.ts @@ -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"; @@ -15,16 +15,13 @@ const execute = promisify(execFile); export type LogSink = { log: (log: LogRecord) => void; status: (status: LogSourceStatus) => void }; export type StopLogSource = () => Promise; -export async function adbPath(): Promise { - 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] }] : []; diff --git a/packages/core/src/serve-emu.ts b/packages/core/src/serve-emu.ts index b82899a9..15a5a777 100644 --- a/packages/core/src/serve-emu.ts +++ b/packages/core/src/serve-emu.ts @@ -2,8 +2,6 @@ import { execFile, spawn } from "node:child_process"; import type { ChildProcess } from "node:child_process"; import { promisify } from "node:util"; import { access } from "node:fs/promises"; -import { constants } from "node:fs"; -import { dirname, join } from "node:path"; import { createServer } from "node:net"; import { setTimeout as delay } from "node:timers/promises"; import { z } from "zod"; @@ -17,7 +15,7 @@ import { isMissingFile, MissingRuntimeError } from "./install-integrity.ts"; import { recordAndroidEmulatorReconnect, recordAndroidBootWait, recordAndroidBackendStartup, recordAndroidStartupStages, recordAndroidStartupContext, recordAndroidStartupDeviceState, recordAndroidBackendStop } from "./telemetry.ts"; import { androidStartupMessageSchema, androidDeviceState, setAndroidStartupDiagnostic } from "@mobile-dev/shared/android-startup-diagnostics.ts"; import type { AndroidStartupContext, AndroidStartupFailure, AndroidStartupSummary } from "@mobile-dev/shared/android-startup-diagnostics.ts"; -import { androidSdkRoots } from "./android-sdk.ts"; +import { androidToolPath, missingAdbMessage, sdkToolPath } from "./android-sdk.ts"; import { panelRuntimePath } from "./panel-runtime.ts"; import type { ResourceSaving } from "./resource-saving.ts"; @@ -56,24 +54,20 @@ export class ServeEmu { if (baseUrl) this.external = parseBaseUrl(baseUrl, "SERVE_EMU_URL"); } - private async emulatorPath() { - for (const root of androidSdkRoots()) { - const path = join(root, "emulator/emulator"); - try { await access(path, constants.X_OK); return path; } catch { /* Try PATH next. */ } - } - return "emulator"; - } - - async list(): Promise { + async list(run: (file: string, args: string[], options: { timeout: number; maxBuffer?: number; windowsHide?: boolean }) => Promise<{ stdout: string }> = execute): Promise { try { const adb = await adbPath(); - const emulator = await this.emulatorPath(); + const emulator = await sdkToolPath("emulator"); const [devices, avds] = await Promise.all([ - execute(adb, ["devices", "-l"], { timeout: 5000, maxBuffer: 1024 * 1024 }), - execute(emulator, ["-list-avds"], { timeout: 5000, maxBuffer: 1024 * 1024 }).catch(error => { - if (error.code === "ENOENT") return { stdout: "" }; - throw error; - }), + run(adb, ["devices", "-l"], { timeout: 5000, maxBuffer: 1024 * 1024, windowsHide: true }), + run(emulator, ["-list-avds"], { timeout: 5000, maxBuffer: 1024 * 1024, windowsHide: true }) + .then(({ stdout }): { stdout: string; hint?: string } => ({ stdout })) + .catch(error => ({ + stdout: "", + hint: isMissingFile(error) + ? "To use a virtual device, install Android Emulator in Android Studio’s SDK Manager, then create an AVD in Device Manager." + : `Android Emulator could not list AVDs. Run emulator -list-avds to check the installation. ${errorMessage(error)}`, + })), ]); const deviceLines = devices.stdout.split(/\r?\n/); const runningReads = deviceLines.flatMap(line => { @@ -88,7 +82,7 @@ export class ServeEmu { const emulatorDevice = /^emulator-\d+$/.test(match[1]); // The emulator console names the AVD before adb authorizes the device. if (emulatorDevice) { - const response = await execute(adb, ["-s", match[1], "emu", "avd", "name"], { timeout: 3000 }).catch(() => undefined); + const response = await run(adb, ["-s", match[1], "emu", "avd", "name"], { timeout: 3000, windowsHide: true }).catch(() => undefined); const avdName = parseAvdName(response?.stdout); if (avdName) this.avdNames.set(match[1], avdName); name = avdName ?? this.avdNames.get(match[1]) ?? name; @@ -111,9 +105,16 @@ export class ServeEmu { return parsedId.success && !runningAvd; }); const stopped = stoppedNames.map(name => ({ udid: `avd:${name}`, name, state: "Shutdown", runtime: "Android", platform: "android" as const, kind: "emulator" as const })); - return { connected: true, managed: [...this.backends.values()].some(backend => !!backend.child), baseUrl: this.external?.origin ?? "", devices: [...running, ...stopped] }; + const discovered = [...running, ...stopped]; + const setupHint = discovered.length === 0 + ? `${avds.hint ?? "No Android virtual devices found. Create an AVD in Android Studio’s Device Manager."} Or connect an Android device with USB debugging enabled and authorize this computer.` + : undefined; + return { connected: true, managed: [...this.backends.values()].some(backend => !!backend.child), baseUrl: this.external?.origin ?? "", devices: discovered, ...(setupHint && { setupHint }) }; } catch (error) { - return { connected: false, managed: false, baseUrl: "", devices: [], error: `Cannot list Android devices. Install Android SDK platform-tools and emulator. ${errorMessage(error)}` }; + const message = isMissingFile(error) + ? missingAdbMessage + : `Cannot list Android devices. Run adb devices -l to check the connection. ${errorMessage(error)}`; + return { connected: false, managed: false, baseUrl: "", devices: [], error: message }; } } @@ -147,7 +148,7 @@ export class ServeEmu { const target = { platform: "android" as const, id, key: device.name, state: device.state }; const resourceSaving = await this.resourceSaving?.enabled(target); const status = await bootAndroidEmulator({ - name: device.name, executable: await this.emulatorPath(), signal: this.lifetime.signal, + name: device.name, executable: await sdkToolPath("emulator"), signal: this.lifetime.signal, ready: () => this.emulatorReady(item => item.name === device.name, "boot"), resourceSaving, }); @@ -310,8 +311,8 @@ export class ServeEmu { recordAndroidStartupContext(context); const adb = await adbPath(); const child = spawn(process.execPath, [cli, "--host", "127.0.0.1", "--port", url.port, "--serial", id, "--max-fps", "30"], { - stdio: ["ignore", "pipe", "pipe", "ipc"], shell: false, - env: { ...process.env, PATH: `${dirname(adb)}:${process.env.PATH ?? ""}`, SERVE_EMU_UPDATE_CHECK: "0" }, + stdio: ["ignore", "pipe", "pipe", "ipc"], shell: false, windowsHide: true, + env: { ...process.env, PATH: androidToolPath([adb, await sdkToolPath("emulator")]), SERVE_EMU_UPDATE_CHECK: "0" }, }); this.backendContexts.set(child, context); let stage: AndroidStartupFailure["stage"] = "process-launch"; diff --git a/packages/core/test/android-sdk.test.ts b/packages/core/test/android-sdk.test.ts new file mode 100644 index 00000000..3664b3e3 --- /dev/null +++ b/packages/core/test/android-sdk.test.ts @@ -0,0 +1,104 @@ +import test from "node:test"; +import type { TestContext } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { delimiter, dirname, join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { androidSdkRoots, androidToolPath, sdkToolPath } from "../src/android-sdk.ts"; +import { registerAndroidTools } from "../src/android-tools.ts"; +import { systemCommands } from "../src/app-control/commands.ts"; +import { AndroidContainer } from "../src/app-storage/container.ts"; +import { ServeEmu } from "../src/serve-emu.ts"; + +async function isolatedProfile(t: TestContext) { + const profile = await mkdtemp(join(tmpdir(), "mobile sdk ")); + const variables = ["HOME", "USERPROFILE", "LOCALAPPDATA", "ANDROID_HOME", "ANDROID_SDK_ROOT", "PATH"]; + const previous = variables.map(key => [key, process.env[key]] as const); + t.after(async () => { + for (const [key, value] of previous) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + await rm(profile, { recursive: true, force: true }); + }); + process.env.HOME = process.env.USERPROFILE = profile; + process.env.LOCALAPPDATA = join(profile, "Local App Data"); + process.env.PATH = profile; + delete process.env.ANDROID_HOME; + delete process.env.ANDROID_SDK_ROOT; + return profile; +} + +const executable = (name: string) => process.platform === "win32" ? name + ".exe" : name; + +async function installTool(root: string, directory: string, name: string, mode = 0o755) { + const file = join(root, directory, executable(name)); + await mkdir(dirname(file), { recursive: true }); + await writeFile(file, "", { mode }); + return file; +} + +test("Android tools use the host's default SDK and preserve spaced directories on the child PATH", async t => { + const profile = await isolatedProfile(t); + const root = process.platform === "win32" ? join(profile, "Local App Data", "Android", "Sdk") + : process.platform === "darwin" ? join(profile, "Library", "Android", "sdk") : join(profile, "Android", "Sdk"); + assert.deepEqual(androidSdkRoots(), [root]); + assert.equal(await sdkToolPath("adb"), executable("adb")); + const adb = await installTool(root, "platform-tools", "adb"); + const emulator = await installTool(root, "emulator", "emulator"); + const aapt2 = await installTool(root, "build-tools/35", "aapt2"); + await installTool(root, "build-tools/9", "aapt2"); + if (process.platform !== "win32") await installTool(root, "build-tools/36", "aapt2", 0o644); + assert.equal(await sdkToolPath("adb"), adb); + assert.equal(await sdkToolPath("emulator"), emulator); + assert.equal(await systemCommands.aapt2(), aapt2); + const userPath = [join(profile, "Other Tools"), dirname(adb)].join(delimiter); + assert.equal(androidToolPath([adb, emulator], userPath), [dirname(adb), dirname(emulator), join(profile, "Other Tools")].join(delimiter)); + assert.equal(androidToolPath([executable("adb")], userPath), userPath); + assert.equal(androidToolPath([adb], ""), dirname(adb)); + if (process.platform === "win32") { + delete process.env.LOCALAPPDATA; + assert.deepEqual(androidSdkRoots(), [join(profile, "AppData", "Local", "Android", "Sdk")]); + } +}); + +test("Android tools search ANDROID_HOME before ANDROID_SDK_ROOT and fall back per executable", async t => { + const profile = await isolatedProfile(t); + const [defaultRoot] = androidSdkRoots(); + const customRoot = process.env.ANDROID_HOME = join(profile, "custom SDK"); + const legacyRoot = process.env.ANDROID_SDK_ROOT = join(profile, "legacy SDK"); + assert.deepEqual(androidSdkRoots(), [customRoot, legacyRoot, defaultRoot]); + const defaultAdb = await installTool(defaultRoot, "platform-tools", "adb"); + assert.equal(await sdkToolPath("adb"), defaultAdb); + const legacyAdb = await installTool(legacyRoot, "platform-tools", "adb"); + assert.equal(await sdkToolPath("adb"), legacyAdb); + const customAdb = await installTool(customRoot, "platform-tools", "adb"); + assert.equal(await sdkToolPath("adb"), customAdb); + const legacyEmulator = await installTool(legacyRoot, "emulator", "emulator"); + if (process.platform !== "win32") await installTool(customRoot, "emulator", "emulator", 0o644); + assert.equal(await sdkToolPath("emulator"), legacyEmulator); + process.env.ANDROID_SDK_ROOT = customRoot; + assert.deepEqual(androidSdkRoots(), [customRoot, defaultRoot]); +}); + +test("Android discovery returns SDK installation guidance to MCP clients with no SDK installed", async t => { + await isolatedProfile(t); + const backend = new ServeEmu(); + const server = new McpServer({ name: "android-setup-test", version: "1" }); + registerAndroidTools(server, backend, "ui://mobile-dev/test.html", async () => {}, async () => {}); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "android-setup-test", version: "1" }); + t.after(async () => { await client.close(); await server.close(); backend.dispose(); }); + await server.connect(serverTransport); + await client.connect(clientTransport); + const result = await client.callTool({ name: "mobile_list_android_devices", arguments: {} }); + assert.equal(result.isError, undefined); + assert.equal(result.structuredContent?.connected, false); + assert.deepEqual(result.structuredContent?.devices, []); + assert.match(String(result.structuredContent?.error), /Platform-Tools \(adb\).*SDK Manager.*ANDROID_HOME.*PATH/); + assert.deepEqual(result.content, [{ type: "text", text: result.structuredContent?.error }]); + const container = new AndroidContainer("setup-test-phone", "com.example", systemCommands); + await assert.rejects(() => container.list(), /Listing app data needs Android SDK Platform-Tools/); +}); diff --git a/packages/core/test/android.test.ts b/packages/core/test/android.test.ts index ea95c4e9..ee15a9d5 100644 --- a/packages/core/test/android.test.ts +++ b/packages/core/test/android.test.ts @@ -22,6 +22,36 @@ const ID = "emulator-5554"; const SCREEN = { width: 1080, height: 2400 }; const H264 = Buffer.from([0, 0, 0, 1, 0x67, 0x64, 0, 0x28, 0, 0, 0, 1, 0x65, 1]); +test("Android discovery distinguishes a missing SDK, missing emulator, and empty AVD list", async t => { + const backend = new ServeEmu(); + t.after(() => backend.dispose()); + const missing = Object.assign(new Error("not found"), { code: "ENOENT" }); + const unavailable = await backend.list(async () => { throw missing; }); + assert.equal(unavailable.connected, false); + assert.match(unavailable.error!, /Platform-Tools \(adb\).*SDK Manager.*ANDROID_HOME.*PATH/); + const physicalOnly = async (deviceList: string, emulatorError: Error = missing) => backend.list(async (_file, args) => { + if (args[0] === "-list-avds") throw emulatorError; + return { stdout: deviceList }; + }); + const noEmulator = await physicalOnly("List of devices attached\r\n"); + assert.equal(noEmulator.connected, true); + assert.match(noEmulator.setupHint!, /install Android Emulator.*Device Manager/i); + const phone = await physicalOnly("List of devices attached\r\nserial device model:Pixel\r\n"); + assert.equal(phone.connected, true); + assert.equal(phone.devices[0].udid, "serial"); + assert.equal(phone.setupHint, undefined); + const brokenEmulator = new Error("failed to read the AVD directory"); + const connected = await physicalOnly("serial device model:Pixel\r\n", brokenEmulator); + assert.deepEqual(connected.devices, phone.devices); + assert.equal(connected.setupHint, undefined); + const broken = await physicalOnly("", brokenEmulator); + assert.equal(broken.connected, true); + assert.match(broken.setupHint!, /emulator -list-avds.*failed to read the AVD directory/); + const noAvds = await backend.list(async () => ({ stdout: "" })); + assert.equal(noAvds.connected, true); + assert.match(noAvds.setupHint!, /Create an AVD.*Device Manager.*USB debugging/); +}); + test("Android booking names are app metadata for live ADC relays only", async t => { const directory = await mkdtemp(join(tmpdir(), "mobile-dev-adc-labels-")); const previousHome = process.env.HOME; diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index ba1ea872..133941f6 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -45,6 +45,7 @@ export type Status = { baseUrl: string; devices: SimulatorDevice[]; error?: string; + setupHint?: string; }; export function normalizeDevices(payload: unknown): SimulatorDevice[] { diff --git a/packages/skills/mobile-dev-setup/SKILL.md b/packages/skills/mobile-dev-setup/SKILL.md index 02633693..8241b8f0 100644 --- a/packages/skills/mobile-dev-setup/SKILL.md +++ b/packages/skills/mobile-dev-setup/SKILL.md @@ -30,7 +30,9 @@ For source development, `npm run vendor:baguette` downloads the pinned official ## Android setup -The package also contains a checked-in Node.js fork of serve-emu 0.0.6, its Node dependencies, and scrcpy 4.0. Android uses the same Node runtime as the server and needs Android SDK platform-tools and emulator, and an AVD or authorized attached device. Check connectivity with `mobile_list_android_devices`. The SDK lookup checks `ANDROID_HOME`, `ANDROID_SDK_ROOT`, `~/Library/Android/sdk`, then PATH. +The package contains serve-emu 0.0.6 and scrcpy 4.0. Call `mobile_list_android_devices` and use its setup guidance when the list is empty. If adb is missing, direct the user to **Android Studio → SDK Manager → SDK Tools → Android SDK Platform-Tools**. For an emulator, also install **Android Emulator**, then create an AVD with a system image in **Device Manager**. For a phone, enable USB debugging and accept the authorization prompt, or pair it for wireless debugging. + +The plugin checks `ANDROID_HOME`, then `ANDROID_SDK_ROOT`, then the default SDK folder, and finally executables on `PATH`. The default it checks is `%LOCALAPPDATA%\Android\Sdk` on Windows, `~/Library/Android/sdk` on macOS and `~/Android/Sdk` on Linux. For a custom location, set `ANDROID_HOME` to the SDK root shown by SDK Manager and restart the host. Open or reuse the panel for Android work. Call `mobile_list_android_devices` to discover devices; listing does not boot them. Follow the user's choice or reuse a compatible device shared by the panel. For app development, reuse a suitable running emulator or choose an installed AVD and call `mobile_boot_android_emulator` if needed. Pick among equivalent AVDs yourself; ask only when the choice changes what the task needs. The user can also enable Android in the panel toolbar and select an AVD to boot and stream it. Use the returned running serial with the Mobile Dev Android tools. The panel needs WebCodecs H.264 support. Do not install a global serve-emu package or start a second app dev server. diff --git a/packages/ui/src/simulator-panel.ts b/packages/ui/src/simulator-panel.ts index e4ed3e35..42dc7e92 100644 --- a/packages/ui/src/simulator-panel.ts +++ b/packages/ui/src/simulator-panel.ts @@ -585,7 +585,9 @@ export function createSimulatorPanel( placeholder: available.length ? "Select a device" : next.connected ? "No devices" : "Devices unavailable", }); selectDevice(); - if (!next.connected && physicalDevices.length === 0) { + if (platform === "android" && !available.length && (next.setupHint || !next.connected)) { + empty(next.connected ? "No Android devices." : "Android devices unavailable.", next.setupHint ?? next.error); + } else if (!next.connected && physicalDevices.length === 0) { empty("Could not start the simulator backend."); notice(next.error); } diff --git a/packages/ui/test/simulator-panel.test.ts b/packages/ui/test/simulator-panel.test.ts index 111cc23b..1620c2ce 100644 --- a/packages/ui/test/simulator-panel.test.ts +++ b/packages/ui/test/simulator-panel.test.ts @@ -566,6 +566,17 @@ test("Android refresh connects an arriving phone once and closes its stream when assert.equal(lifecycle.length, 0); }); +test("the Android panel shows the server's emulator setup hint when adb is available but the device list is empty", async t => { + const { android } = fixture(t); + android.panel.setOpeningTarget({ platform: "android" }); + const setupHint = "Install Android Emulator in SDK Manager, then create an AVD in Device Manager."; + android.panel.acceptStatus({ connected: true, managed: false, baseUrl: "", devices: [], setupHint }); + assert.equal(android.element("empty").textContent, "No Android devices."); + assert.equal(android.element("empty-description").textContent, setupHint); + assert.equal(android.element("empty-description").hidden, false); + assert.equal(android.element("start-device").disabled, true); +}); + test("Android discovery polls visible panels, shares refreshes, and removes disconnected phones", async t => { t.mock.timers.enable({ apis: ["setTimeout"] }); const f = fixture(t); diff --git a/website/src/content/docs/docs/getting-started.md b/website/src/content/docs/docs/getting-started.md index b5fe38f1..688cbd6e 100644 --- a/website/src/content/docs/docs/getting-started.md +++ b/website/src/content/docs/docs/getting-started.md @@ -13,7 +13,7 @@ Mobile Dev runs on an **Apple Silicon Mac**. Install the platform tools for the | --- | --- | | iOS simulator | Xcode 26 or later, with an installed simulator runtime | | Physical iPhone or iPad | Xcode 27 or later, a paired device, Developer Mode, and USB or Wi-Fi connectivity | -| Android | Android SDK platform-tools and emulator, plus an AVD or a physical device with authorized debugging | +| Android | Android SDK Platform-Tools for physical devices. For AVDs, also install Android Emulator and a system image | | Android screen streaming | A host with H.264 WebCodecs decoding | | Physical iOS screen mirroring | A host with HEVC WebCodecs decoding | | Metro logs and React Native inspection | An existing local Metro server with a compatible app inspector target | @@ -22,6 +22,12 @@ Mobile Dev runs on an **Apple Silicon Mac**. Install the platform tools for the Select the full Xcode installation in **Xcode Settings → Locations → Command Line Tools**. Command Line Tools alone do not provide the required simulator tools. +### Set up Android + +1. In [Android Studio](https://developer.android.com/studio), open **SDK Manager → SDK Tools** and install **Android SDK Platform-Tools**. Note the **Android SDK Location** shown in SDK Manager. +2. For an emulator, also install **Android Emulator**, then create an AVD in **Device Manager** and choose a system image. For a phone, enable **USB debugging** and accept the authorization prompt, or pair it for wireless debugging. [Virtual device setup](https://developer.android.com/studio/run/managing-avds) · [Physical device setup](https://developer.android.com/studio/run/device) +3. If you use a custom SDK location, set `ANDROID_HOME` to that folder and fully restart your host app. Mobile Dev checks `%LOCALAPPDATA%\Android\Sdk` on Windows, `~/Library/Android/sdk` on macOS and `~/Android/Sdk` on Linux by default. [Android SDK environment variables](https://developer.android.com/tools/variables) + ## ChatGPT and Codex [Open Mobile Dev in the ChatGPT plugin store](https://chatgpt.com/plugins/plugins_6ac4c117f76881918d3676e851fa4005). ChatGPT and Codex share the same listing. Install the plugin in the desktop app, then start a new chat and ask **“Open Mobile Dev.”**