diff --git a/src/platforms/android/adb.ts b/src/platforms/android/adb.ts new file mode 100644 index 0000000000..014e4f04ea --- /dev/null +++ b/src/platforms/android/adb.ts @@ -0,0 +1,21 @@ +import { whichCmd } from '../../utils/exec.ts'; +import { AppError } from '../../utils/errors.ts'; +import type { DeviceInfo } from '../../utils/device.ts'; + +export function adbArgs(device: DeviceInfo, args: string[]): string[] { + return ['-s', device.id, ...args]; +} + +export async function ensureAdb(): Promise { + const adbAvailable = await whichCmd('adb'); + if (!adbAvailable) throw new AppError('TOOL_MISSING', 'adb not found in PATH'); +} + +export function isClipboardShellUnsupported(stdout: string, stderr: string): boolean { + const haystack = `${stdout}\n${stderr}`.toLowerCase(); + return haystack.includes('no shell command implementation') || haystack.includes('unknown command'); +} + +export async function sleep(ms: number): Promise { + await new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/src/platforms/android/app-lifecycle.ts b/src/platforms/android/app-lifecycle.ts new file mode 100644 index 0000000000..cb15805272 --- /dev/null +++ b/src/platforms/android/app-lifecycle.ts @@ -0,0 +1,507 @@ +import { promises as fs } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { runCmd, whichCmd } from '../../utils/exec.ts'; +import { AppError } from '../../utils/errors.ts'; +import type { DeviceInfo } from '../../utils/device.ts'; +import { isDeepLinkTarget } from '../../core/open-target.ts'; +import { waitForAndroidBoot } from './devices.ts'; +import { adbArgs } from './adb.ts'; + +const ALIASES: Record = { + settings: { type: 'intent', value: 'android.settings.SETTINGS' }, +}; +const ANDROID_LAUNCHER_CATEGORY = 'android.intent.category.LAUNCHER'; +const ANDROID_LEANBACK_CATEGORY = 'android.intent.category.LEANBACK_LAUNCHER'; +const ANDROID_DEFAULT_CATEGORY = 'android.intent.category.DEFAULT'; + +export async function resolveAndroidApp( + device: DeviceInfo, + app: string, +): Promise<{ type: 'intent' | 'package'; value: string }> { + const trimmed = app.trim(); + if (trimmed.includes('.')) return { type: 'package', value: trimmed }; + + const alias = ALIASES[trimmed.toLowerCase()]; + if (alias) return alias; + + const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'list', 'packages'])); + const packages = result.stdout + .split('\n') + .map((line: string) => line.replace('package:', '').trim()) + .filter(Boolean); + + const matches = packages.filter((pkg: string) => + pkg.toLowerCase().includes(trimmed.toLowerCase()), + ); + if (matches.length === 1) { + return { type: 'package', value: matches[0] }; + } + + if (matches.length > 1) { + throw new AppError('INVALID_ARGS', `Multiple packages matched "${app}"`, { matches }); + } + + throw new AppError('APP_NOT_INSTALLED', `No package found matching "${app}"`); +} + +export async function listAndroidApps( + device: DeviceInfo, + filter: 'user-installed' | 'all' = 'all', +): Promise> { + const launchable = await listAndroidLaunchablePackages(device); + const packageIds = + filter === 'user-installed' + ? (await listAndroidUserInstalledPackages(device)).filter((pkg) => launchable.has(pkg)) + : Array.from(launchable); + return packageIds + .sort((a, b) => a.localeCompare(b)) + .map((pkg) => ({ package: pkg, name: inferAndroidAppName(pkg) })); +} + +async function listAndroidLaunchablePackages(device: DeviceInfo): Promise> { + const packages = new Set(); + for (const category of resolveAndroidLaunchCategories(device, { includeFallbackWhenUnknown: true })) { + const result = await runCmd( + 'adb', + adbArgs(device, [ + 'shell', + 'cmd', + 'package', + 'query-activities', + '--brief', + '-a', + 'android.intent.action.MAIN', + '-c', + category, + ]), + { allowFailure: true }, + ); + if (result.exitCode !== 0 || result.stdout.trim().length === 0) { + continue; + } + for (const line of result.stdout.split('\n')) { + const trimmed = line.trim(); + if (!trimmed) continue; + const firstToken = trimmed.split(/\s+/)[0]; + const pkg = firstToken.includes('/') ? firstToken.split('/')[0] : firstToken; + if (pkg) packages.add(pkg); + } + } + return packages; +} + +function resolveAndroidLauncherCategory(device: DeviceInfo): string { + return resolveAndroidLaunchCategories(device)[0] ?? ANDROID_LAUNCHER_CATEGORY; +} + +function resolveAndroidLaunchCategories( + device: DeviceInfo, + options: { includeFallbackWhenUnknown?: boolean } = {}, +): string[] { + if (device.target === 'tv') { + return [ANDROID_LEANBACK_CATEGORY]; + } + if (device.target === 'mobile') { + return [ANDROID_LAUNCHER_CATEGORY]; + } + if (options.includeFallbackWhenUnknown) { + return [ANDROID_LAUNCHER_CATEGORY, ANDROID_LEANBACK_CATEGORY]; + } + return [ANDROID_LAUNCHER_CATEGORY]; +} + +async function listAndroidUserInstalledPackages(device: DeviceInfo): Promise { + const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'list', 'packages', '-3'])); + return result.stdout + .split('\n') + .map((line: string) => line.replace('package:', '').trim()) + .filter(Boolean); +} + +export function inferAndroidAppName(packageName: string): string { + const ignoredTokens = new Set([ + 'com', + 'android', + 'google', + 'app', + 'apps', + 'service', + 'services', + 'mobile', + 'client', + ]); + const tokens = packageName + .split('.') + .flatMap((segment) => segment.split(/[_-]+/)) + .map((token) => token.trim().toLowerCase()) + .filter((token) => token.length > 0); + // Fallback to last token if every token is ignored (e.g. "com.android.app.services" → "Services"). + let chosen = tokens[tokens.length - 1] ?? packageName; + for (let index = tokens.length - 1; index >= 0; index -= 1) { + const token = tokens[index]; + if (!ignoredTokens.has(token)) { + chosen = token; + break; + } + } + return chosen + .split(/[^a-z0-9]+/i) + .filter(Boolean) + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(' '); +} + +export async function getAndroidAppState( + device: DeviceInfo, +): Promise<{ package?: string; activity?: string }> { + const windowFocus = await readAndroidFocus(device, [ + ['shell', 'dumpsys', 'window', 'windows'], + ['shell', 'dumpsys', 'window'], + ]); + if (windowFocus) return windowFocus; + + const activityFocus = await readAndroidFocus(device, [ + ['shell', 'dumpsys', 'activity', 'activities'], + ['shell', 'dumpsys', 'activity'], + ]); + if (activityFocus) return activityFocus; + return {}; +} + +async function readAndroidFocus( + device: DeviceInfo, + commands: string[][], +): Promise<{ package?: string; activity?: string } | null> { + for (const args of commands) { + const result = await runCmd('adb', adbArgs(device, args), { allowFailure: true }); + const text = result.stdout ?? ''; + const parsed = parseAndroidFocus(text); + if (parsed) return parsed; + } + return null; +} + +function parseAndroidFocus(text: string): { package?: string; activity?: string } | null { + const patterns = [ + /mCurrentFocus=Window\{[^}]*\s([\w.]+)\/([\w.$]+)/, + /mFocusedApp=AppWindowToken\{[^}]*\s([\w.]+)\/([\w.$]+)/, + /mResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/, + /ResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/, + ]; + for (const pattern of patterns) { + const match = pattern.exec(text); + if (match) { + return { package: match[1], activity: match[2] }; + } + } + return null; +} + +export async function openAndroidApp( + device: DeviceInfo, + app: string, + activity?: string, +): Promise { + if (!device.booted) { + await waitForAndroidBoot(device.id); + } + const deepLinkTarget = app.trim(); + if (isDeepLinkTarget(deepLinkTarget)) { + if (activity) { + throw new AppError('INVALID_ARGS', 'Activity override is not supported when opening a deep link URL'); + } + await runCmd('adb', adbArgs(device, [ + 'shell', + 'am', + 'start', + '-W', + '-a', + 'android.intent.action.VIEW', + '-d', + deepLinkTarget, + ])); + return; + } + const resolved = await resolveAndroidApp(device, app); + const launchCategory = resolveAndroidLauncherCategory(device); + if (resolved.type === 'intent') { + if (activity) { + throw new AppError('INVALID_ARGS', 'Activity override requires a package name, not an intent'); + } + await runCmd('adb', adbArgs(device, ['shell', 'am', 'start', '-W', '-a', resolved.value])); + return; + } + if (activity) { + const component = activity.includes('/') + ? activity + : `${resolved.value}/${activity.startsWith('.') ? activity : `.${activity}`}`; + await runCmd( + 'adb', + adbArgs(device, [ + 'shell', + 'am', + 'start', + '-W', + '-a', + 'android.intent.action.MAIN', + '-c', + ANDROID_DEFAULT_CATEGORY, + '-c', + launchCategory, + '-n', + component, + ]), + ); + return; + } + const primaryResult = await runCmd( + 'adb', + adbArgs(device, [ + 'shell', + 'am', + 'start', + '-W', + '-a', + 'android.intent.action.MAIN', + '-c', + ANDROID_DEFAULT_CATEGORY, + '-c', + launchCategory, + '-p', + resolved.value, + ]), + { allowFailure: true }, + ); + if (primaryResult.exitCode === 0 && !isAmStartError(primaryResult.stdout, primaryResult.stderr)) { + return; + } + const component = await resolveAndroidLaunchComponent(device, resolved.value); + if (!component) { + throw new AppError('COMMAND_FAILED', `Failed to launch ${resolved.value}`, { + stdout: primaryResult.stdout, + stderr: primaryResult.stderr, + }); + } + await runCmd( + 'adb', + adbArgs(device, [ + 'shell', + 'am', + 'start', + '-W', + '-a', + 'android.intent.action.MAIN', + '-c', + ANDROID_DEFAULT_CATEGORY, + '-c', + launchCategory, + '-n', + component, + ]), + ); +} + +async function resolveAndroidLaunchComponent( + device: DeviceInfo, + packageName: string, +): Promise { + const categories = Array.from(new Set( + resolveAndroidLaunchCategories(device, { includeFallbackWhenUnknown: true }), + )); + for (const category of categories) { + const result = await runCmd( + 'adb', + adbArgs(device, [ + 'shell', + 'cmd', + 'package', + 'resolve-activity', + '--brief', + '-a', + 'android.intent.action.MAIN', + '-c', + category, + packageName, + ]), + { allowFailure: true }, + ); + if (result.exitCode !== 0) { + continue; + } + const component = parseAndroidLaunchComponent(result.stdout); + if (component) return component; + } + return null; +} + +export function isAmStartError(stdout: string, stderr: string): boolean { + const output = `${stdout}\n${stderr}`; + return /Error:.*(?:Activity not started|unable to resolve Intent)/i.test(output); +} + +export function parseAndroidLaunchComponent(stdout: string): string | null { + const lines = stdout + .split('\n') + .map((line: string) => line.trim()) + .filter(Boolean); + for (let index = lines.length - 1; index >= 0; index -= 1) { + const line = lines[index]; + if (!line.includes('/')) continue; + return line.split(/\s+/)[0]; + } + return null; +} + +export async function openAndroidDevice(device: DeviceInfo): Promise { + if (!device.booted) { + await waitForAndroidBoot(device.id); + } +} + +export async function closeAndroidApp(device: DeviceInfo, app: string): Promise { + const trimmed = app.trim(); + if (trimmed.toLowerCase() === 'settings') { + await runCmd('adb', adbArgs(device, ['shell', 'am', 'force-stop', 'com.android.settings'])); + return; + } + const resolved = await resolveAndroidApp(device, app); + if (resolved.type === 'intent') { + throw new AppError('INVALID_ARGS', 'Close requires a package name, not an intent'); + } + await runCmd('adb', adbArgs(device, ['shell', 'am', 'force-stop', resolved.value])); +} + +async function uninstallAndroidApp( + device: DeviceInfo, + app: string, +): Promise<{ package: string }> { + const resolved = await resolveAndroidApp(device, app); + if (resolved.type === 'intent') { + throw new AppError('INVALID_ARGS', 'App uninstall requires a package name, not an intent'); + } + const result = await runCmd('adb', adbArgs(device, ['uninstall', resolved.value]), { allowFailure: true }); + if (result.exitCode !== 0) { + const output = `${result.stdout}\n${result.stderr}`.toLowerCase(); + if (!output.includes('unknown package') && !output.includes('not installed')) { + throw new AppError('COMMAND_FAILED', `adb uninstall failed for ${resolved.value}`, { + stdout: result.stdout, + stderr: result.stderr, + exitCode: result.exitCode, + }); + } + } + return { package: resolved.value }; +} + +type BundletoolInvocation = + | { cmd: 'bundletool'; prefixArgs: readonly string[] } + | { cmd: 'java'; prefixArgs: readonly string[] }; + +let cachedBundletoolInvocation: + | { key: string; invocation: BundletoolInvocation } + | null = null; + +function bundletoolInvocationCacheKey(): string { + return `${process.env.PATH ?? ''}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR ?? ''}`; +} + +async function resolveBundletoolInvocation(): Promise { + const cacheKey = bundletoolInvocationCacheKey(); + if (cachedBundletoolInvocation?.key === cacheKey) { + return cachedBundletoolInvocation.invocation; + } + + if (await whichCmd('bundletool')) { + const invocation = { cmd: 'bundletool', prefixArgs: [] } as const; + cachedBundletoolInvocation = { key: cacheKey, invocation }; + return invocation; + } + + const bundletoolJar = process.env.AGENT_DEVICE_BUNDLETOOL_JAR?.trim(); + if (!bundletoolJar) { + throw new AppError( + 'TOOL_MISSING', + 'bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.', + ); + } + try { + await fs.access(bundletoolJar); + } catch { + throw new AppError( + 'TOOL_MISSING', + `AGENT_DEVICE_BUNDLETOOL_JAR points to a missing file: ${bundletoolJar}`, + ); + } + const invocation = { cmd: 'java', prefixArgs: ['-jar', bundletoolJar] } as const; + cachedBundletoolInvocation = { key: cacheKey, invocation }; + return invocation; +} + +async function runBundletool(args: string[]): Promise { + const invocation = await resolveBundletoolInvocation(); + await runCmd(invocation.cmd, [...invocation.prefixArgs, ...args]); +} + +function isAndroidAppBundlePath(appPath: string): boolean { + return path.extname(appPath).toLowerCase() === '.aab'; +} + +function resolveBundletoolBuildMode(): string { + const mode = process.env.AGENT_DEVICE_ANDROID_BUNDLETOOL_MODE?.trim(); + return mode && mode.length > 0 ? mode : 'universal'; +} + +async function installAndroidAppBundle(device: DeviceInfo, appPath: string): Promise { + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'agent-device-aab-')); + const apksPath = path.join(tempDir, 'bundle.apks'); + const mode = resolveBundletoolBuildMode(); + try { + await runBundletool([ + 'build-apks', + '--bundle', + appPath, + '--output', + apksPath, + '--mode', + mode, + ]); + await runBundletool([ + 'install-apks', + '--apks', + apksPath, + '--device-id', + device.id, + ]); + } finally { + await fs.rm(tempDir, { recursive: true, force: true }); + } +} + +async function installAndroidAppFiles(device: DeviceInfo, appPath: string): Promise { + if (isAndroidAppBundlePath(appPath)) { + await installAndroidAppBundle(device, appPath); + return; + } + await runCmd('adb', adbArgs(device, ['install', '-r', appPath])); +} + +export async function installAndroidApp(device: DeviceInfo, appPath: string): Promise { + if (!device.booted) { + await waitForAndroidBoot(device.id); + } + await installAndroidAppFiles(device, appPath); +} + +export async function reinstallAndroidApp( + device: DeviceInfo, + app: string, + appPath: string, +): Promise<{ package: string }> { + if (!device.booted) { + await waitForAndroidBoot(device.id); + } + const { package: pkg } = await uninstallAndroidApp(device, app); + await installAndroidAppFiles(device, appPath); + return { package: pkg }; +} diff --git a/src/platforms/android/device-input-state.ts b/src/platforms/android/device-input-state.ts new file mode 100644 index 0000000000..e130b837cc --- /dev/null +++ b/src/platforms/android/device-input-state.ts @@ -0,0 +1,184 @@ +import { runCmd } from '../../utils/exec.ts'; +import { AppError } from '../../utils/errors.ts'; +import type { DeviceInfo } from '../../utils/device.ts'; +import { backAndroid } from './input-actions.ts'; +import { adbArgs, isClipboardShellUnsupported, sleep } from './adb.ts'; + +const ANDROID_INPUT_TYPE_CLASS_MASK = 0x0000000f; +const ANDROID_INPUT_TYPE_CLASS_TEXT = 0x00000001; +const ANDROID_INPUT_TYPE_CLASS_NUMBER = 0x00000002; +const ANDROID_INPUT_TYPE_CLASS_PHONE = 0x00000003; +const ANDROID_INPUT_TYPE_CLASS_DATETIME = 0x00000004; +const ANDROID_INPUT_TYPE_VARIATION_MASK = 0x00000ff0; +const ANDROID_TEXT_VARIATION_EMAIL_ADDRESS = 0x00000020; +const ANDROID_TEXT_VARIATION_WEB_EMAIL_ADDRESS = 0x000000d0; +const ANDROID_TEXT_VARIATION_PASSWORD = 0x00000080; +const ANDROID_TEXT_VARIATION_WEB_PASSWORD = 0x000000e0; +const ANDROID_TEXT_VARIATION_VISIBLE_PASSWORD = 0x00000090; +const ANDROID_KEYBOARD_DISMISS_MAX_ATTEMPTS = 2; +const ANDROID_KEYBOARD_DISMISS_RETRY_DELAY_MS = 120; + +type AndroidKeyboardType = 'text' | 'number' | 'email' | 'phone' | 'password' | 'datetime' | 'unknown'; + +export type AndroidKeyboardState = { + visible: boolean; + inputType?: string; + type?: AndroidKeyboardType; +}; + +export async function getAndroidKeyboardState( + device: DeviceInfo, +): Promise { + const result = await runCmd('adb', adbArgs(device, ['shell', 'dumpsys', 'input_method']), { + allowFailure: true, + }); + if (result.exitCode !== 0) { + throw new AppError('COMMAND_FAILED', 'Failed to query Android keyboard state', { + stdout: result.stdout, + stderr: result.stderr, + exitCode: result.exitCode, + }); + } + return parseAndroidKeyboardState(result.stdout); +} + +export async function dismissAndroidKeyboard(device: DeviceInfo): Promise<{ + attempts: number; + wasVisible: boolean; + dismissed: boolean; + visible: boolean; + inputType?: string; + type?: AndroidKeyboardType; +}> { + const initialState = await getAndroidKeyboardState(device); + let state = initialState; + let attempts = 0; + + while (state.visible && attempts < ANDROID_KEYBOARD_DISMISS_MAX_ATTEMPTS) { + await backAndroid(device); + attempts += 1; + await sleep(ANDROID_KEYBOARD_DISMISS_RETRY_DELAY_MS); + state = await getAndroidKeyboardState(device); + } + + return { + attempts, + wasVisible: initialState.visible, + dismissed: initialState.visible && !state.visible, + visible: state.visible, + inputType: state.inputType, + type: state.type, + }; +} + +function parseAndroidKeyboardState(stdout: string): AndroidKeyboardState { + const visibility = parseAndroidKeyboardVisibility(stdout); + let visible = visibility ?? false; + if (visibility === null) { + const imeWindowVisibility = stdout.match(/\bmImeWindowVis=0x([0-9a-fA-F]+)\b/); + if (imeWindowVisibility?.[1]) { + const flags = Number.parseInt(imeWindowVisibility[1], 16); + if (!Number.isNaN(flags)) { + visible = (flags & 0x1) !== 0; + } + } + } + + const inputTypeMatches = Array.from(stdout.matchAll(/\binputType=0x([0-9a-fA-F]+)\b/gi)); + const lastInputType = inputTypeMatches.length > 0 + ? inputTypeMatches[inputTypeMatches.length - 1]?.[1] + : undefined; + const inputType = lastInputType ? `0x${lastInputType.toLowerCase()}` : undefined; + + return { + visible, + inputType, + type: inputType ? classifyAndroidKeyboardType(inputType) : undefined, + }; +} + +function parseAndroidKeyboardVisibility(stdout: string): boolean | null { + const latestByKey = new Map(); + const pattern = /\b(mInputShown|mIsInputViewShown|isInputViewShown)=([a-zA-Z]+)\b/g; + for (const match of stdout.matchAll(pattern)) { + const key = match[1]; + const value = match[2]?.toLowerCase(); + if (!key || (value !== 'true' && value !== 'false')) continue; + latestByKey.set(key, value === 'true'); + } + if (latestByKey.size === 0) return null; + for (const visible of latestByKey.values()) { + if (visible) return true; + } + return false; +} + +function classifyAndroidKeyboardType(inputType: string): AndroidKeyboardType { + const parsed = Number.parseInt(inputType.replace(/^0x/i, ''), 16); + if (Number.isNaN(parsed)) return 'unknown'; + const inputClass = parsed & ANDROID_INPUT_TYPE_CLASS_MASK; + if (inputClass === ANDROID_INPUT_TYPE_CLASS_NUMBER) return 'number'; + if (inputClass === ANDROID_INPUT_TYPE_CLASS_PHONE) return 'phone'; + if (inputClass === ANDROID_INPUT_TYPE_CLASS_DATETIME) return 'datetime'; + if (inputClass !== ANDROID_INPUT_TYPE_CLASS_TEXT) return 'unknown'; + + const variation = parsed & ANDROID_INPUT_TYPE_VARIATION_MASK; + if (variation === ANDROID_TEXT_VARIATION_EMAIL_ADDRESS || variation === ANDROID_TEXT_VARIATION_WEB_EMAIL_ADDRESS) { + return 'email'; + } + if ( + variation === ANDROID_TEXT_VARIATION_PASSWORD || + variation === ANDROID_TEXT_VARIATION_WEB_PASSWORD || + variation === ANDROID_TEXT_VARIATION_VISIBLE_PASSWORD + ) { + return 'password'; + } + return 'text'; +} + +export async function readAndroidClipboardText(device: DeviceInfo): Promise { + const stdout = await runAndroidClipboardShellCommand( + device, + ['shell', 'cmd', 'clipboard', 'get', 'text'], + 'read', + ); + return normalizeAndroidClipboardText(stdout); +} + +export async function writeAndroidClipboardText(device: DeviceInfo, text: string): Promise { + await runAndroidClipboardShellCommand( + device, + ['shell', 'cmd', 'clipboard', 'set', 'text', text], + 'write', + ); +} + +async function runAndroidClipboardShellCommand( + device: DeviceInfo, + args: string[], + operation: 'read' | 'write', +): Promise { + const result = await runCmd('adb', adbArgs(device, args), { allowFailure: true }); + if (isClipboardShellUnsupported(result.stdout, result.stderr)) { + throw new AppError( + 'UNSUPPORTED_OPERATION', + `Android shell clipboard ${operation} is not supported on this device.`, + ); + } + if (result.exitCode !== 0) { + throw new AppError('COMMAND_FAILED', `Failed to ${operation} Android clipboard text`, { + stdout: result.stdout, + stderr: result.stderr, + exitCode: result.exitCode, + }); + } + return result.stdout; +} + +function normalizeAndroidClipboardText(stdout: string): string { + const normalized = stdout.replace(/\r\n/g, '\n').replace(/\n$/, ''); + const prefixed = normalized.match(/^clipboard text:\s*(.*)$/i); + if (prefixed) return prefixed[1] ?? ''; + if (normalized.trim().toLowerCase() === 'null') return ''; + return normalized; +} diff --git a/src/platforms/android/index.ts b/src/platforms/android/index.ts index 9335f4a287..1b5691a605 100644 --- a/src/platforms/android/index.ts +++ b/src/platforms/android/index.ts @@ -1,1532 +1,43 @@ -import { promises as fs } from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { runCmd, whichCmd } from '../../utils/exec.ts'; -import { withRetry } from '../../utils/retry.ts'; -import { AppError } from '../../utils/errors.ts'; -import type { DeviceInfo } from '../../utils/device.ts'; -import type { RawSnapshotNode, SnapshotOptions } from '../../utils/snapshot.ts'; -import { isDeepLinkTarget } from '../../core/open-target.ts'; -import { waitForAndroidBoot } from './devices.ts'; -import { findBounds, parseBounds, parseUiHierarchy, readNodeAttributes } from './ui-hierarchy.ts'; -import { - parsePermissionAction, - parsePermissionTarget, - type PermissionSettingOptions, -} from '../permission-utils.ts'; -import { parseAppearanceAction } from '../appearance.ts'; - -const ALIASES: Record = { - settings: { type: 'intent', value: 'android.settings.SETTINGS' }, -}; -const ANDROID_LAUNCHER_CATEGORY = 'android.intent.category.LAUNCHER'; -const ANDROID_LEANBACK_CATEGORY = 'android.intent.category.LEANBACK_LAUNCHER'; -const ANDROID_DEFAULT_CATEGORY = 'android.intent.category.DEFAULT'; -const ANDROID_INPUT_TYPE_CLASS_MASK = 0x0000000f; -const ANDROID_INPUT_TYPE_CLASS_TEXT = 0x00000001; -const ANDROID_INPUT_TYPE_CLASS_NUMBER = 0x00000002; -const ANDROID_INPUT_TYPE_CLASS_PHONE = 0x00000003; -const ANDROID_INPUT_TYPE_CLASS_DATETIME = 0x00000004; -const ANDROID_INPUT_TYPE_VARIATION_MASK = 0x00000ff0; -const ANDROID_TEXT_VARIATION_EMAIL_ADDRESS = 0x00000020; -const ANDROID_TEXT_VARIATION_WEB_EMAIL_ADDRESS = 0x000000d0; -const ANDROID_TEXT_VARIATION_PASSWORD = 0x00000080; -const ANDROID_TEXT_VARIATION_WEB_PASSWORD = 0x000000e0; -const ANDROID_TEXT_VARIATION_VISIBLE_PASSWORD = 0x00000090; -const ANDROID_KEYBOARD_DISMISS_MAX_ATTEMPTS = 2; -const ANDROID_KEYBOARD_DISMISS_RETRY_DELAY_MS = 120; - -type AndroidBroadcastPayload = { - action?: string; - receiver?: string; - extras?: Record; -}; - -type AndroidKeyboardType = 'text' | 'number' | 'email' | 'phone' | 'password' | 'datetime' | 'unknown'; - -export type AndroidKeyboardState = { - visible: boolean; - inputType?: string; - type?: AndroidKeyboardType; -}; - -function adbArgs(device: DeviceInfo, args: string[]): string[] { - return ['-s', device.id, ...args]; -} - -export async function resolveAndroidApp( - device: DeviceInfo, - app: string, -): Promise<{ type: 'intent' | 'package'; value: string }> { - const trimmed = app.trim(); - if (trimmed.includes('.')) return { type: 'package', value: trimmed }; - - const alias = ALIASES[trimmed.toLowerCase()]; - if (alias) return alias; - - const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'list', 'packages'])); - const packages = result.stdout - .split('\n') - .map((line: string) => line.replace('package:', '').trim()) - .filter(Boolean); - - const matches = packages.filter((pkg: string) => - pkg.toLowerCase().includes(trimmed.toLowerCase()), - ); - if (matches.length === 1) { - return { type: 'package', value: matches[0] }; - } - - if (matches.length > 1) { - throw new AppError('INVALID_ARGS', `Multiple packages matched "${app}"`, { matches }); - } - - throw new AppError('APP_NOT_INSTALLED', `No package found matching "${app}"`); -} - -export async function listAndroidApps( - device: DeviceInfo, - filter: 'user-installed' | 'all' = 'all', -): Promise> { - const launchable = await listAndroidLaunchablePackages(device); - const packageIds = - filter === 'user-installed' - ? (await listAndroidUserInstalledPackages(device)).filter((pkg) => launchable.has(pkg)) - : Array.from(launchable); - return packageIds - .sort((a, b) => a.localeCompare(b)) - .map((pkg) => ({ package: pkg, name: inferAndroidAppName(pkg) })); -} - -async function listAndroidLaunchablePackages(device: DeviceInfo): Promise> { - const packages = new Set(); - for (const category of resolveAndroidLaunchCategories(device, { includeFallbackWhenUnknown: true })) { - const result = await runCmd( - 'adb', - adbArgs(device, [ - 'shell', - 'cmd', - 'package', - 'query-activities', - '--brief', - '-a', - 'android.intent.action.MAIN', - '-c', - category, - ]), - { allowFailure: true }, - ); - if (result.exitCode !== 0 || result.stdout.trim().length === 0) { - continue; - } - for (const line of result.stdout.split('\n')) { - const trimmed = line.trim(); - if (!trimmed) continue; - const firstToken = trimmed.split(/\s+/)[0]; - const pkg = firstToken.includes('/') ? firstToken.split('/')[0] : firstToken; - if (pkg) packages.add(pkg); - } - } - return packages; -} - -function resolveAndroidLauncherCategory(device: DeviceInfo): string { - return resolveAndroidLaunchCategories(device)[0] ?? ANDROID_LAUNCHER_CATEGORY; -} - -function resolveAndroidLaunchCategories( - device: DeviceInfo, - options: { includeFallbackWhenUnknown?: boolean } = {}, -): string[] { - if (device.target === 'tv') { - return [ANDROID_LEANBACK_CATEGORY]; - } - if (device.target === 'mobile') { - return [ANDROID_LAUNCHER_CATEGORY]; - } - if (options.includeFallbackWhenUnknown) { - return [ANDROID_LAUNCHER_CATEGORY, ANDROID_LEANBACK_CATEGORY]; - } - return [ANDROID_LAUNCHER_CATEGORY]; -} - -async function listAndroidUserInstalledPackages(device: DeviceInfo): Promise { - const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'list', 'packages', '-3'])); - return result.stdout - .split('\n') - .map((line: string) => line.replace('package:', '').trim()) - .filter(Boolean); -} - -export function inferAndroidAppName(packageName: string): string { - const ignoredTokens = new Set([ - 'com', - 'android', - 'google', - 'app', - 'apps', - 'service', - 'services', - 'mobile', - 'client', - ]); - const tokens = packageName - .split('.') - .flatMap((segment) => segment.split(/[_-]+/)) - .map((token) => token.trim().toLowerCase()) - .filter((token) => token.length > 0); - // Fallback to last token if every token is ignored (e.g. "com.android.app.services" → "Services"). - let chosen = tokens[tokens.length - 1] ?? packageName; - for (let index = tokens.length - 1; index >= 0; index -= 1) { - const token = tokens[index]; - if (!ignoredTokens.has(token)) { - chosen = token; - break; - } - } - return chosen - .split(/[^a-z0-9]+/i) - .filter(Boolean) - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); -} - -export async function getAndroidAppState( - device: DeviceInfo, -): Promise<{ package?: string; activity?: string }> { - const windowFocus = await readAndroidFocus(device, [ - ['shell', 'dumpsys', 'window', 'windows'], - ['shell', 'dumpsys', 'window'], - ]); - if (windowFocus) return windowFocus; - - const activityFocus = await readAndroidFocus(device, [ - ['shell', 'dumpsys', 'activity', 'activities'], - ['shell', 'dumpsys', 'activity'], - ]); - if (activityFocus) return activityFocus; - return {}; -} - -export async function getAndroidKeyboardState( - device: DeviceInfo, -): Promise { - const result = await runCmd('adb', adbArgs(device, ['shell', 'dumpsys', 'input_method']), { - allowFailure: true, - }); - if (result.exitCode !== 0) { - throw new AppError('COMMAND_FAILED', 'Failed to query Android keyboard state', { - stdout: result.stdout, - stderr: result.stderr, - exitCode: result.exitCode, - }); - } - return parseAndroidKeyboardState(result.stdout); -} - -export async function dismissAndroidKeyboard(device: DeviceInfo): Promise<{ - attempts: number; - wasVisible: boolean; - dismissed: boolean; - visible: boolean; - inputType?: string; - type?: AndroidKeyboardType; -}> { - const initialState = await getAndroidKeyboardState(device); - let state = initialState; - let attempts = 0; - - while (state.visible && attempts < ANDROID_KEYBOARD_DISMISS_MAX_ATTEMPTS) { - await backAndroid(device); - attempts += 1; - await sleep(ANDROID_KEYBOARD_DISMISS_RETRY_DELAY_MS); - state = await getAndroidKeyboardState(device); - } - - return { - attempts, - wasVisible: initialState.visible, - dismissed: initialState.visible && !state.visible, - visible: state.visible, - inputType: state.inputType, - type: state.type, - }; -} - -function parseAndroidKeyboardState(stdout: string): AndroidKeyboardState { - const visibility = parseAndroidKeyboardVisibility(stdout); - let visible = visibility ?? false; - if (visibility === null) { - const imeWindowVisibility = stdout.match(/\bmImeWindowVis=0x([0-9a-fA-F]+)\b/); - if (imeWindowVisibility?.[1]) { - const flags = Number.parseInt(imeWindowVisibility[1], 16); - if (!Number.isNaN(flags)) { - visible = (flags & 0x1) !== 0; - } - } - } - - const inputTypeMatches = Array.from(stdout.matchAll(/\binputType=0x([0-9a-fA-F]+)\b/gi)); - const lastInputType = inputTypeMatches.length > 0 - ? inputTypeMatches[inputTypeMatches.length - 1]?.[1] - : undefined; - const inputType = lastInputType ? `0x${lastInputType.toLowerCase()}` : undefined; - - return { - visible, - inputType, - type: inputType ? classifyAndroidKeyboardType(inputType) : undefined, - }; -} - -function parseAndroidKeyboardVisibility(stdout: string): boolean | null { - const latestByKey = new Map(); - const pattern = /\b(mInputShown|mIsInputViewShown|isInputViewShown)=([a-zA-Z]+)\b/g; - for (const match of stdout.matchAll(pattern)) { - const key = match[1]; - const value = match[2]?.toLowerCase(); - if (!key || (value !== 'true' && value !== 'false')) continue; - latestByKey.set(key, value === 'true'); - } - if (latestByKey.size === 0) return null; - for (const visible of latestByKey.values()) { - if (visible) return true; - } - return false; -} - -function classifyAndroidKeyboardType(inputType: string): AndroidKeyboardType { - const parsed = Number.parseInt(inputType.replace(/^0x/i, ''), 16); - if (Number.isNaN(parsed)) return 'unknown'; - const inputClass = parsed & ANDROID_INPUT_TYPE_CLASS_MASK; - if (inputClass === ANDROID_INPUT_TYPE_CLASS_NUMBER) return 'number'; - if (inputClass === ANDROID_INPUT_TYPE_CLASS_PHONE) return 'phone'; - if (inputClass === ANDROID_INPUT_TYPE_CLASS_DATETIME) return 'datetime'; - if (inputClass !== ANDROID_INPUT_TYPE_CLASS_TEXT) return 'unknown'; - - const variation = parsed & ANDROID_INPUT_TYPE_VARIATION_MASK; - if (variation === ANDROID_TEXT_VARIATION_EMAIL_ADDRESS || variation === ANDROID_TEXT_VARIATION_WEB_EMAIL_ADDRESS) { - return 'email'; - } - if ( - variation === ANDROID_TEXT_VARIATION_PASSWORD || - variation === ANDROID_TEXT_VARIATION_WEB_PASSWORD || - variation === ANDROID_TEXT_VARIATION_VISIBLE_PASSWORD - ) { - return 'password'; - } - return 'text'; -} - -async function readAndroidFocus( - device: DeviceInfo, - commands: string[][], -): Promise<{ package?: string; activity?: string } | null> { - for (const args of commands) { - const result = await runCmd('adb', adbArgs(device, args), { allowFailure: true }); - const text = result.stdout ?? ''; - const parsed = parseAndroidFocus(text); - if (parsed) return parsed; - } - return null; -} - -function parseAndroidFocus(text: string): { package?: string; activity?: string } | null { - const patterns = [ - /mCurrentFocus=Window\{[^}]*\s([\w.]+)\/([\w.$]+)/, - /mFocusedApp=AppWindowToken\{[^}]*\s([\w.]+)\/([\w.$]+)/, - /mResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/, - /ResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/, - ]; - for (const pattern of patterns) { - const match = pattern.exec(text); - if (match) { - return { package: match[1], activity: match[2] }; - } - } - return null; -} - -export async function openAndroidApp( - device: DeviceInfo, - app: string, - activity?: string, -): Promise { - if (!device.booted) { - await waitForAndroidBoot(device.id); - } - const deepLinkTarget = app.trim(); - if (isDeepLinkTarget(deepLinkTarget)) { - if (activity) { - throw new AppError('INVALID_ARGS', 'Activity override is not supported when opening a deep link URL'); - } - await runCmd('adb', adbArgs(device, [ - 'shell', - 'am', - 'start', - '-W', - '-a', - 'android.intent.action.VIEW', - '-d', - deepLinkTarget, - ])); - return; - } - const resolved = await resolveAndroidApp(device, app); - const launchCategory = resolveAndroidLauncherCategory(device); - if (resolved.type === 'intent') { - if (activity) { - throw new AppError('INVALID_ARGS', 'Activity override requires a package name, not an intent'); - } - await runCmd('adb', adbArgs(device, ['shell', 'am', 'start', '-W', '-a', resolved.value])); - return; - } - if (activity) { - const component = activity.includes('/') - ? activity - : `${resolved.value}/${activity.startsWith('.') ? activity : `.${activity}`}`; - await runCmd( - 'adb', - adbArgs(device, [ - 'shell', - 'am', - 'start', - '-W', - '-a', - 'android.intent.action.MAIN', - '-c', - ANDROID_DEFAULT_CATEGORY, - '-c', - launchCategory, - '-n', - component, - ]), - ); - return; - } - const primaryResult = await runCmd( - 'adb', - adbArgs(device, [ - 'shell', - 'am', - 'start', - '-W', - '-a', - 'android.intent.action.MAIN', - '-c', - ANDROID_DEFAULT_CATEGORY, - '-c', - launchCategory, - '-p', - resolved.value, - ]), - { allowFailure: true }, - ); - if (primaryResult.exitCode === 0 && !isAmStartError(primaryResult.stdout, primaryResult.stderr)) { - return; - } - const component = await resolveAndroidLaunchComponent(device, resolved.value); - if (!component) { - throw new AppError('COMMAND_FAILED', `Failed to launch ${resolved.value}`, { - stdout: primaryResult.stdout, - stderr: primaryResult.stderr, - }); - } - await runCmd( - 'adb', - adbArgs(device, [ - 'shell', - 'am', - 'start', - '-W', - '-a', - 'android.intent.action.MAIN', - '-c', - ANDROID_DEFAULT_CATEGORY, - '-c', - launchCategory, - '-n', - component, - ]), - ); -} - -async function resolveAndroidLaunchComponent( - device: DeviceInfo, - packageName: string, -): Promise { - const categories = Array.from(new Set( - resolveAndroidLaunchCategories(device, { includeFallbackWhenUnknown: true }), - )); - for (const category of categories) { - const result = await runCmd( - 'adb', - adbArgs(device, [ - 'shell', - 'cmd', - 'package', - 'resolve-activity', - '--brief', - '-a', - 'android.intent.action.MAIN', - '-c', - category, - packageName, - ]), - { allowFailure: true }, - ); - if (result.exitCode !== 0) { - continue; - } - const component = parseAndroidLaunchComponent(result.stdout); - if (component) return component; - } - return null; -} - -export function isAmStartError(stdout: string, stderr: string): boolean { - const output = `${stdout}\n${stderr}`; - return /Error:.*(?:Activity not started|unable to resolve Intent)/i.test(output); -} - -export function parseAndroidLaunchComponent(stdout: string): string | null { - const lines = stdout - .split('\n') - .map((line: string) => line.trim()) - .filter(Boolean); - for (let index = lines.length - 1; index >= 0; index -= 1) { - const line = lines[index]; - if (!line.includes('/')) continue; - return line.split(/\s+/)[0]; - } - return null; -} - -export async function openAndroidDevice(device: DeviceInfo): Promise { - if (!device.booted) { - await waitForAndroidBoot(device.id); - } -} - -export async function closeAndroidApp(device: DeviceInfo, app: string): Promise { - const trimmed = app.trim(); - if (trimmed.toLowerCase() === 'settings') { - await runCmd('adb', adbArgs(device, ['shell', 'am', 'force-stop', 'com.android.settings'])); - return; - } - const resolved = await resolveAndroidApp(device, app); - if (resolved.type === 'intent') { - throw new AppError('INVALID_ARGS', 'Close requires a package name, not an intent'); - } - await runCmd('adb', adbArgs(device, ['shell', 'am', 'force-stop', resolved.value])); -} - -async function uninstallAndroidApp( - device: DeviceInfo, - app: string, -): Promise<{ package: string }> { - const resolved = await resolveAndroidApp(device, app); - if (resolved.type === 'intent') { - throw new AppError('INVALID_ARGS', 'App uninstall requires a package name, not an intent'); - } - const result = await runCmd('adb', adbArgs(device, ['uninstall', resolved.value]), { allowFailure: true }); - if (result.exitCode !== 0) { - const output = `${result.stdout}\n${result.stderr}`.toLowerCase(); - if (!output.includes('unknown package') && !output.includes('not installed')) { - throw new AppError('COMMAND_FAILED', `adb uninstall failed for ${resolved.value}`, { - stdout: result.stdout, - stderr: result.stderr, - exitCode: result.exitCode, - }); - } - } - return { package: resolved.value }; -} - -type BundletoolInvocation = - | { cmd: 'bundletool'; prefixArgs: readonly string[] } - | { cmd: 'java'; prefixArgs: readonly string[] }; - -let cachedBundletoolInvocation: - | { key: string; invocation: BundletoolInvocation } - | null = null; - -function bundletoolInvocationCacheKey(): string { - return `${process.env.PATH ?? ''}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR ?? ''}`; -} - -async function resolveBundletoolInvocation(): Promise { - const cacheKey = bundletoolInvocationCacheKey(); - if (cachedBundletoolInvocation?.key === cacheKey) { - return cachedBundletoolInvocation.invocation; - } - - if (await whichCmd('bundletool')) { - const invocation = { cmd: 'bundletool', prefixArgs: [] } as const; - cachedBundletoolInvocation = { key: cacheKey, invocation }; - return invocation; - } - - const bundletoolJar = process.env.AGENT_DEVICE_BUNDLETOOL_JAR?.trim(); - if (!bundletoolJar) { - throw new AppError( - 'TOOL_MISSING', - 'bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.', - ); - } - try { - await fs.access(bundletoolJar); - } catch { - throw new AppError( - 'TOOL_MISSING', - `AGENT_DEVICE_BUNDLETOOL_JAR points to a missing file: ${bundletoolJar}`, - ); - } - const invocation = { cmd: 'java', prefixArgs: ['-jar', bundletoolJar] } as const; - cachedBundletoolInvocation = { key: cacheKey, invocation }; - return invocation; -} - -async function runBundletool(args: string[]): Promise { - const invocation = await resolveBundletoolInvocation(); - await runCmd(invocation.cmd, [...invocation.prefixArgs, ...args]); -} - -function isAndroidAppBundlePath(appPath: string): boolean { - return path.extname(appPath).toLowerCase() === '.aab'; -} - -function resolveBundletoolBuildMode(): string { - const mode = process.env.AGENT_DEVICE_ANDROID_BUNDLETOOL_MODE?.trim(); - return mode && mode.length > 0 ? mode : 'universal'; -} - -async function installAndroidAppBundle(device: DeviceInfo, appPath: string): Promise { - const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'agent-device-aab-')); - const apksPath = path.join(tempDir, 'bundle.apks'); - const mode = resolveBundletoolBuildMode(); - try { - await runBundletool([ - 'build-apks', - '--bundle', - appPath, - '--output', - apksPath, - '--mode', - mode, - ]); - await runBundletool([ - 'install-apks', - '--apks', - apksPath, - '--device-id', - device.id, - ]); - } finally { - await fs.rm(tempDir, { recursive: true, force: true }); - } -} - -async function installAndroidAppFiles(device: DeviceInfo, appPath: string): Promise { - if (isAndroidAppBundlePath(appPath)) { - await installAndroidAppBundle(device, appPath); - return; - } - await runCmd('adb', adbArgs(device, ['install', '-r', appPath])); -} - -export async function installAndroidApp(device: DeviceInfo, appPath: string): Promise { - if (!device.booted) { - await waitForAndroidBoot(device.id); - } - await installAndroidAppFiles(device, appPath); -} - -export async function reinstallAndroidApp( - device: DeviceInfo, - app: string, - appPath: string, -): Promise<{ package: string }> { - if (!device.booted) { - await waitForAndroidBoot(device.id); - } - const { package: pkg } = await uninstallAndroidApp(device, app); - await installAndroidAppFiles(device, appPath); - return { package: pkg }; -} - -export async function pressAndroid(device: DeviceInfo, x: number, y: number): Promise { - await runCmd('adb', adbArgs(device, ['shell', 'input', 'tap', String(x), String(y)])); -} - -export async function swipeAndroid( - device: DeviceInfo, - x1: number, - y1: number, - x2: number, - y2: number, - durationMs = 250, -): Promise { - await runCmd( - 'adb', - adbArgs(device, [ - 'shell', - 'input', - 'swipe', - String(x1), - String(y1), - String(x2), - String(y2), - String(durationMs), - ]), - ); -} - -export async function backAndroid(device: DeviceInfo): Promise { - await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '4'])); -} - -export async function homeAndroid(device: DeviceInfo): Promise { - await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '3'])); -} - -export async function appSwitcherAndroid(device: DeviceInfo): Promise { - await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '187'])); -} - -export async function longPressAndroid( - device: DeviceInfo, - x: number, - y: number, - durationMs = 800, -): Promise { - await runCmd( - 'adb', - adbArgs(device, [ - 'shell', - 'input', - 'swipe', - String(x), - String(y), - String(x), - String(y), - String(durationMs), - ]), - ); -} - -export async function typeAndroid(device: DeviceInfo, text: string): Promise { - const shouldInjectViaClipboard = shouldUseClipboardTextInjection(text); - if (shouldInjectViaClipboard) { - const clipboardResult = await typeAndroidViaClipboard(device, text); - if (clipboardResult === 'ok') return; - } - try { - const encoded = encodeAndroidInputText(text); - await runCmd('adb', adbArgs(device, ['shell', 'input', 'text', encoded])); - } catch (error) { - if (shouldInjectViaClipboard && isAndroidInputTextUnsupported(error)) { - throw new AppError( - 'COMMAND_FAILED', - 'Non-ASCII text input is not supported on this Android shell. Install an ADB keyboard IME or use ASCII input.', - { textPreview: text.slice(0, 32) }, - error instanceof Error ? error : undefined, - ); - } - throw error; - } -} - -export async function readAndroidClipboardText(device: DeviceInfo): Promise { - const stdout = await runAndroidClipboardShellCommand( - device, - ['shell', 'cmd', 'clipboard', 'get', 'text'], - 'read', - ); - return normalizeAndroidClipboardText(stdout); -} - -export async function writeAndroidClipboardText(device: DeviceInfo, text: string): Promise { - await runAndroidClipboardShellCommand( - device, - ['shell', 'cmd', 'clipboard', 'set', 'text', text], - 'write', - ); -} - -export async function focusAndroid(device: DeviceInfo, x: number, y: number): Promise { - await pressAndroid(device, x, y); -} - -export async function fillAndroid( - device: DeviceInfo, - x: number, - y: number, - text: string, -): Promise { - const textCodePointLength = Array.from(text).length; - const requiresClipboardInjection = shouldUseClipboardTextInjection(text); - const attempts: Array<{ - strategy: 'input_text' | 'clipboard_paste' | 'chunked_input'; - clearPadding: number; - minClear: number; - maxClear: number; - }> = [{ strategy: 'input_text', clearPadding: 12, minClear: 8, maxClear: 48 }]; - if (!requiresClipboardInjection) { - attempts.push({ strategy: 'clipboard_paste', clearPadding: 12, minClear: 8, maxClear: 48 }); - attempts.push({ strategy: 'chunked_input', clearPadding: 24, minClear: 16, maxClear: 96 }); - } - - let lastActual: string | null = null; - - for (const attempt of attempts) { - await focusAndroid(device, x, y); - const clearCount = clampCount( - textCodePointLength + attempt.clearPadding, - attempt.minClear, - attempt.maxClear, - ); - await clearFocusedText(device, clearCount); - if (attempt.strategy === 'input_text') { - await typeAndroid(device, text); - } else if (attempt.strategy === 'clipboard_paste') { - const clipboardResult = await typeAndroidViaClipboard(device, text); - if (clipboardResult !== 'ok') { - continue; - } - } else { - await typeAndroidChunked(device, text, 1, 15); - } - lastActual = await readInputValueAtPoint(device, x, y); - if (lastActual === text) return; - } - - throw new AppError('COMMAND_FAILED', 'Android fill verification failed', { - expected: text, - actual: lastActual ?? null, - }); -} - -export async function scrollAndroid( - device: DeviceInfo, - direction: string, - amount = 0.6, -): Promise { - const size = await getAndroidScreenSize(device); - const { width, height } = size; - const distanceX = Math.floor(width * amount); - const distanceY = Math.floor(height * amount); - - const centerX = Math.floor(width / 2); - const centerY = Math.floor(height / 2); - - let x1 = centerX; - let y1 = centerY; - let x2 = centerX; - let y2 = centerY; - - switch (direction) { - case 'up': - // Content moves up -> swipe down. - y1 = centerY - Math.floor(distanceY / 2); - y2 = centerY + Math.floor(distanceY / 2); - break; - case 'down': - // Content moves down -> swipe up. - y1 = centerY + Math.floor(distanceY / 2); - y2 = centerY - Math.floor(distanceY / 2); - break; - case 'left': - // Content moves left -> swipe right. - x1 = centerX - Math.floor(distanceX / 2); - x2 = centerX + Math.floor(distanceX / 2); - break; - case 'right': - // Content moves right -> swipe left. - x1 = centerX + Math.floor(distanceX / 2); - x2 = centerX - Math.floor(distanceX / 2); - break; - default: - throw new AppError('INVALID_ARGS', `Unknown direction: ${direction}`); - } - - await runCmd( - 'adb', - adbArgs(device, [ - 'shell', - 'input', - 'swipe', - String(x1), - String(y1), - String(x2), - String(y2), - '300', - ]), - ); -} - -export async function scrollIntoViewAndroid(device: DeviceInfo, text: string): Promise { - const maxAttempts = 8; - for (let i = 0; i < maxAttempts; i += 1) { - let xml = ''; - try { - xml = await dumpUiHierarchy(device); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - throw new AppError('UNSUPPORTED_OPERATION', `uiautomator dump failed: ${message}`); - } - if (findBounds(xml, text)) return; - await scrollAndroid(device, 'down', 0.5); - } - throw new AppError( - 'COMMAND_FAILED', - `Could not find element containing "${text}" after scrolling`, - ); -} - -export async function screenshotAndroid(device: DeviceInfo, outPath: string): Promise { - const result = await runCmd('adb', adbArgs(device, ['exec-out', 'screencap', '-p']), { - binaryStdout: true, - }); - if (!result.stdoutBuffer) { - throw new AppError('COMMAND_FAILED', 'Failed to capture screenshot'); - } - await fs.writeFile(outPath, result.stdoutBuffer); -} - -export async function setAndroidSetting( - device: DeviceInfo, - setting: string, - state: string, - appPackage?: string, - options?: PermissionSettingOptions, -): Promise { - const normalized = setting.toLowerCase(); - switch (normalized) { - case 'wifi': { - const enabled = parseSettingState(state); - await runCmd('adb', adbArgs(device, ['shell', 'svc', 'wifi', enabled ? 'enable' : 'disable'])); - return; - } - case 'airplane': { - const enabled = parseSettingState(state); - const flag = enabled ? '1' : '0'; - const bool = enabled ? 'true' : 'false'; - await runCmd('adb', adbArgs(device, ['shell', 'settings', 'put', 'global', 'airplane_mode_on', flag])); - await runCmd('adb', adbArgs(device, ['shell', 'am', 'broadcast', '-a', 'android.intent.action.AIRPLANE_MODE', '--ez', 'state', bool])); - return; - } - case 'location': { - const enabled = parseSettingState(state); - const mode = enabled ? '3' : '0'; - await runCmd('adb', adbArgs(device, ['shell', 'settings', 'put', 'secure', 'location_mode', mode])); - return; - } - case 'appearance': { - const target = await resolveAndroidAppearanceTarget(device, state); - await runCmd('adb', adbArgs(device, ['shell', 'cmd', 'uimode', 'night', target === 'dark' ? 'yes' : 'no'])); - return; - } - case 'fingerprint': { - const action = parseAndroidFingerprintAction(state); - await runAndroidFingerprintCommand(device, action); - return; - } - case 'permission': { - if (!appPackage) { - throw new AppError( - 'INVALID_ARGS', - 'permission setting requires an active app in session', - ); - } - const action = parsePermissionAction(state); - const target = parseAndroidPermissionTarget(options?.permissionTarget, options?.permissionMode); - if (target.kind === 'notifications') { - await setAndroidNotificationPermission(device, appPackage, action, target); - return; - } - const pmAction = action === 'grant' ? 'grant' : 'revoke'; - if (target.type === 'photos') { - await setAndroidPhotoPermission(device, appPackage, pmAction); - return; - } - await runCmd('adb', adbArgs(device, ['shell', 'pm', pmAction, appPackage, target.value])); - return; - } - default: - throw new AppError('INVALID_ARGS', `Unsupported setting: ${setting}`); - } -} - -type AndroidFingerprintAction = 'match' | 'nonmatch'; - -function parseAndroidFingerprintAction(state: string): AndroidFingerprintAction { - const normalized = state.trim().toLowerCase(); - if (normalized === 'match') return 'match'; - if (normalized === 'nonmatch') return 'nonmatch'; - throw new AppError( - 'INVALID_ARGS', - `Invalid fingerprint state: ${state}. Use match|nonmatch.`, - ); -} - -async function runAndroidFingerprintCommand( - device: DeviceInfo, - action: AndroidFingerprintAction, -): Promise { - const attempts = androidFingerprintCommandAttempts(device, action); - const failures: Array<{ args: string[]; stdout: string; stderr: string; exitCode: number }> = []; - - for (const args of attempts) { - const result = await runCmd('adb', adbArgs(device, args), { allowFailure: true }); - if (result.exitCode === 0) return; - failures.push({ - args, - stdout: result.stdout, - stderr: result.stderr, - exitCode: result.exitCode, - }); - } - - const attemptsPayload = failures.map((failure) => ({ - args: failure.args.join(' '), - exitCode: failure.exitCode, - stderr: failure.stderr.slice(0, 400), - })); - const capabilityMissing = failures.length > 0 && failures.every((failure) => - isAndroidFingerprintCapabilityMissing(failure.stdout, failure.stderr) - ); - if (capabilityMissing) { - throw new AppError( - 'UNSUPPORTED_OPERATION', - 'Android fingerprint simulation is not supported on this target/runtime.', - { - deviceId: device.id, - action, - hint: 'Use an Android emulator with biometric support, or a device/runtime that exposes cmd fingerprint.', - attempts: attemptsPayload, - }, - ); - } - throw new AppError('COMMAND_FAILED', 'Failed to simulate Android fingerprint.', { - deviceId: device.id, - action, - attempts: attemptsPayload, - }); -} - -function androidFingerprintCommandAttempts( - device: DeviceInfo, - action: AndroidFingerprintAction, -): string[][] { - const fingerprintId = action === 'match' ? '1' : '9999'; - const attempts: string[][] = [ - ['shell', 'cmd', 'fingerprint', 'touch', fingerprintId], - ['shell', 'cmd', 'fingerprint', 'finger', fingerprintId], - ]; - if (device.kind === 'emulator') { - attempts.push(['emu', 'finger', 'touch', fingerprintId]); - } - return attempts; -} - -function isAndroidFingerprintCapabilityMissing(stdout: string, stderr: string): boolean { - const text = `${stdout}\n${stderr}`.toLowerCase(); - return ( - text.includes('unknown command') || - text.includes("can't find service: fingerprint") || - text.includes('service fingerprint was not found') || - text.includes('fingerprint cmd unavailable') || - text.includes('emu command is not supported') || - text.includes('emulator console is not running') || - (text.includes('fingerprint') && text.includes('not found')) - ); -} - -export async function pushAndroidNotification( - device: DeviceInfo, - packageName: string, - payload: AndroidBroadcastPayload, -): Promise<{ action: string; extrasCount: number }> { - const action = typeof payload.action === 'string' && payload.action.trim() - ? payload.action.trim() - : `${packageName}.TEST_PUSH`; - const args = ['shell', 'am', 'broadcast', '-a', action, '-p', packageName]; - const receiver = typeof payload.receiver === 'string' ? payload.receiver.trim() : ''; - if (receiver) { - args.push('-n', receiver); - } - const rawExtras = payload.extras; - if (rawExtras !== undefined && (typeof rawExtras !== 'object' || rawExtras === null || Array.isArray(rawExtras))) { - throw new AppError('INVALID_ARGS', 'Android push payload extras must be an object'); - } - const extras = rawExtras ?? {}; - let extrasCount = 0; - for (const [key, rawValue] of Object.entries(extras)) { - if (!key) continue; - appendBroadcastExtra(args, key, rawValue); - extrasCount += 1; - } - await runCmd('adb', adbArgs(device, args)); - return { action, extrasCount }; -} - -export async function snapshotAndroid( - device: DeviceInfo, - options: SnapshotOptions = {}, -): Promise<{ - nodes: RawSnapshotNode[]; - truncated?: boolean; -}> { - const xml = await dumpUiHierarchy(device); - return parseUiHierarchy(xml, 800, options); -} - -export async function ensureAdb(): Promise { - const adbAvailable = await whichCmd('adb'); - if (!adbAvailable) throw new AppError('TOOL_MISSING', 'adb not found in PATH'); -} - -async function getAndroidScreenSize( - device: DeviceInfo, -): Promise<{ width: number; height: number }> { - const result = await runCmd('adb', adbArgs(device, ['shell', 'wm', 'size'])); - const match = result.stdout.match(/Physical size:\s*(\d+)x(\d+)/); - if (!match) throw new AppError('COMMAND_FAILED', 'Unable to read screen size'); - return { width: Number(match[1]), height: Number(match[2]) }; -} - -async function dumpUiHierarchy(device: DeviceInfo): Promise { - return withRetry(() => dumpUiHierarchyOnce(device), { - shouldRetry: isRetryableAdbError, - }); -} - -async function dumpUiHierarchyOnce(device: DeviceInfo): Promise { - // Preferred: stream XML directly to stdout, avoiding file I/O race conditions. - const streamed = await runCmd( - 'adb', - adbArgs(device, ['exec-out', 'uiautomator', 'dump', '/dev/tty']), - { allowFailure: true }, - ); - if (streamed.exitCode === 0) { - const fromStream = extractUiDumpXml(streamed.stdout, streamed.stderr); - if (fromStream) return fromStream; - } - - // Fallback: dump to file and read back. - // If `cat` fails with "no such file", the outer withRetry (via isRetryableAdbError) handles it. - const dumpPath = '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/sdcard/window_dump.xml'; - const dumpResult = await runCmd( - 'adb', - adbArgs(device, ['shell', 'uiautomator', 'dump', dumpPath]), - ); - const actualPath = resolveDumpPath(dumpPath, dumpResult.stdout, dumpResult.stderr); - - const result = await runCmd('adb', adbArgs(device, ['shell', 'cat', actualPath])); - const xml = extractUiDumpXml(result.stdout, result.stderr); - if (!xml) { - throw new AppError('COMMAND_FAILED', 'uiautomator dump did not return XML', { - stdout: result.stdout, - stderr: result.stderr, - }); - } - return xml; -} - -function resolveDumpPath(defaultPath: string, stdout: string, stderr: string): string { - const text = `${stdout}\n${stderr}`; - const match = /dumped to:\s*(\S+)/i.exec(text); - return match?.[1] ?? defaultPath; -} - -function extractUiDumpXml(stdout: string, stderr: string): string | null { - const text = `${stdout}\n${stderr}`; - const start = text.indexOf('= 0 ? start : text.indexOf(''); - if (end < 0 || end < hierarchyStart) return null; - const xml = text.slice(hierarchyStart, end + ''.length).trim(); - return xml.length > 0 ? xml : null; -} - -function isRetryableAdbError(err: unknown): boolean { - if (!(err instanceof AppError)) return false; - if (err.code !== 'COMMAND_FAILED') return false; - const stderr = `${(err.details as any)?.stderr ?? ''}`.toLowerCase(); - if (stderr.includes('device offline')) return true; - if (stderr.includes('device not found')) return true; - if (stderr.includes('transport error')) return true; - if (stderr.includes('connection reset')) return true; - if (stderr.includes('broken pipe')) return true; - if (stderr.includes('timed out')) return true; - if (stderr.includes('no such file or directory')) return true; - return false; -} - -function parseSettingState(state: string): boolean { - const normalized = state.toLowerCase(); - if (normalized === 'on' || normalized === 'true' || normalized === '1') return true; - if (normalized === 'off' || normalized === 'false' || normalized === '0') return false; - throw new AppError('INVALID_ARGS', `Invalid setting state: ${state}`); -} - -async function resolveAndroidAppearanceTarget( - device: DeviceInfo, - state: string, -): Promise<'light' | 'dark'> { - const action = parseAppearanceAction(state); - if (action !== 'toggle') return action; - - const currentResult = await runCmd('adb', adbArgs(device, ['shell', 'cmd', 'uimode', 'night']), { - allowFailure: true, - }); - if (currentResult.exitCode !== 0) { - throw new AppError('COMMAND_FAILED', 'Failed to read current Android appearance', { - stdout: currentResult.stdout, - stderr: currentResult.stderr, - exitCode: currentResult.exitCode, - }); - } - const current = parseAndroidAppearance(currentResult.stdout, currentResult.stderr); - if (!current) { - throw new AppError('COMMAND_FAILED', 'Unable to determine current Android appearance for toggle', { - stdout: currentResult.stdout, - stderr: currentResult.stderr, - }); - } - if (current === 'auto') return 'dark'; - return current === 'dark' ? 'light' : 'dark'; -} - -function parseAndroidAppearance(stdout: string, stderr: string): 'light' | 'dark' | 'auto' | null { - const match = /night mode:\s*(yes|no|auto)\b/i.exec(`${stdout}\n${stderr}`); - if (!match) return null; - const value = match[1].toLowerCase(); - if (value === 'yes') return 'dark'; - if (value === 'no') return 'light'; - if (value === 'auto') return 'auto'; - return null; -} - -function parseAndroidPermissionTarget( - permissionTarget: string | undefined, - permissionMode: string | undefined, -): - | { kind: 'pm'; value: string; type: 'camera' | 'microphone' | 'photos' | 'contacts' } - | { kind: 'notifications'; appOps: string; permission: string } { - const normalized = parsePermissionTarget(permissionTarget); - if (permissionMode?.trim()) { - throw new AppError( - 'INVALID_ARGS', - `Permission mode is only supported for photos. Received: ${permissionMode}.`, - ); - } - if (normalized === 'camera') return { kind: 'pm', value: 'android.permission.CAMERA', type: 'camera' }; - if (normalized === 'microphone') { - return { kind: 'pm', value: 'android.permission.RECORD_AUDIO', type: 'microphone' }; - } - if (normalized === 'photos') { - return { kind: 'pm', value: 'android.permission.READ_MEDIA_IMAGES', type: 'photos' }; - } - if (normalized === 'contacts') { - return { kind: 'pm', value: 'android.permission.READ_CONTACTS', type: 'contacts' }; - } - if (normalized === 'notifications') { - return { - kind: 'notifications', - appOps: 'POST_NOTIFICATION', - permission: 'android.permission.POST_NOTIFICATIONS', - }; - } - throw new AppError( - 'INVALID_ARGS', - `Unsupported permission target on Android: ${permissionTarget}. Use camera|microphone|photos|contacts|notifications.`, - ); -} - -async function setAndroidPhotoPermission( - device: DeviceInfo, - appPackage: string, - pmAction: 'grant' | 'revoke', -): Promise { - const sdkInt = await getAndroidSdkInt(device); - const candidates = - sdkInt !== null && sdkInt >= 33 - ? ['android.permission.READ_MEDIA_IMAGES', 'android.permission.READ_EXTERNAL_STORAGE'] - : ['android.permission.READ_EXTERNAL_STORAGE', 'android.permission.READ_MEDIA_IMAGES']; - - const failures: Array<{ permission: string; stderr: string; exitCode: number }> = []; - for (const permission of candidates) { - const result = await runCmd( - 'adb', - adbArgs(device, ['shell', 'pm', pmAction, appPackage, permission]), - { allowFailure: true }, - ); - if (result.exitCode === 0) return; - failures.push({ permission, stderr: result.stderr, exitCode: result.exitCode }); - } - - throw new AppError('COMMAND_FAILED', `Failed to ${pmAction} Android photos permission`, { - appPackage, - sdkInt, - attempts: failures, - }); -} - -async function setAndroidNotificationPermission( - device: DeviceInfo, - appPackage: string, - action: 'grant' | 'deny' | 'reset', - target: { appOps: string; permission: string }, -): Promise { - const appOpsMode = action === 'grant' ? 'allow' : action === 'deny' ? 'deny' : 'default'; - if (action === 'grant') { - await runCmd( - 'adb', - adbArgs(device, ['shell', 'pm', 'grant', appPackage, target.permission]), - { allowFailure: true }, - ); - } else { - await runCmd( - 'adb', - adbArgs(device, ['shell', 'pm', 'revoke', appPackage, target.permission]), - { allowFailure: true }, - ); - if (action === 'reset') { - await runCmd( - 'adb', - adbArgs(device, ['shell', 'pm', 'clear-permission-flags', appPackage, target.permission, 'user-set']), - { allowFailure: true }, - ); - await runCmd( - 'adb', - adbArgs(device, ['shell', 'pm', 'clear-permission-flags', appPackage, target.permission, 'user-fixed']), - { allowFailure: true }, - ); - } - } - await runCmd('adb', adbArgs(device, ['shell', 'appops', 'set', appPackage, target.appOps, appOpsMode])); -} - -async function getAndroidSdkInt(device: DeviceInfo): Promise { - const result = await runCmd('adb', adbArgs(device, ['shell', 'getprop', 'ro.build.version.sdk']), { - allowFailure: true, - }); - if (result.exitCode !== 0) return null; - const value = Number.parseInt(result.stdout.trim(), 10); - if (!Number.isFinite(value) || value <= 0) return null; - return value; -} -function appendBroadcastExtra(args: string[], key: string, value: unknown): void { - if (typeof value === 'string') { - args.push('--es', key, value); - return; - } - if (typeof value === 'boolean') { - args.push('--ez', key, value ? 'true' : 'false'); - return; - } - if (typeof value === 'number' && Number.isFinite(value)) { - if (Number.isInteger(value)) { - args.push('--ei', key, String(value)); - return; - } - args.push('--ef', key, String(value)); - return; - } - throw new AppError( - 'INVALID_ARGS', - `Unsupported Android broadcast extra type for "${key}". Use string, boolean, or number.`, - ); -} -async function typeAndroidChunked( - device: DeviceInfo, - text: string, - chunkSize: number, - delayMs: number, -): Promise { - const size = Math.max(1, Math.floor(chunkSize)); - const chars = Array.from(text); - for (let i = 0; i < chars.length; i += size) { - const chunk = chars.slice(i, i + size).join(''); - await typeAndroid(device, chunk); - if (delayMs > 0 && i + size < chars.length) { - await sleep(delayMs); - } - } -} - -function shouldUseClipboardTextInjection(text: string): boolean { - for (const char of text) { - const code = char.codePointAt(0); - if (code === undefined) continue; - if (code < 0x20 || code > 0x7e) return true; - } - return false; -} - -function encodeAndroidInputText(text: string): string { - // Android shell input uses `%s` as the escaped token for spaces. - return text.replace(/ /g, '%s'); -} - -async function typeAndroidViaClipboard( - device: DeviceInfo, - text: string, -): Promise<'ok' | 'unsupported' | 'failed'> { - const setClipboard = await runCmd( - 'adb', - adbArgs(device, ['shell', 'cmd', 'clipboard', 'set', 'text', text]), - { allowFailure: true }, - ); - if (setClipboard.exitCode !== 0) return 'failed'; - if (isClipboardShellUnsupported(setClipboard.stdout, setClipboard.stderr)) return 'unsupported'; - - const pasteByName = await runCmd( - 'adb', - adbArgs(device, ['shell', 'input', 'keyevent', 'KEYCODE_PASTE']), - { allowFailure: true }, - ); - if (pasteByName.exitCode === 0) return 'ok'; - - const pasteByCode = await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '279']), { - allowFailure: true, - }); - return pasteByCode.exitCode === 0 ? 'ok' : 'failed'; -} - -function isClipboardShellUnsupported(stdout: string, stderr: string): boolean { - const haystack = `${stdout}\n${stderr}`.toLowerCase(); - return haystack.includes('no shell command implementation') || haystack.includes('unknown command'); -} - -async function runAndroidClipboardShellCommand( - device: DeviceInfo, - args: string[], - operation: 'read' | 'write', -): Promise { - const result = await runCmd('adb', adbArgs(device, args), { allowFailure: true }); - if (isClipboardShellUnsupported(result.stdout, result.stderr)) { - throw new AppError( - 'UNSUPPORTED_OPERATION', - `Android shell clipboard ${operation} is not supported on this device.`, - ); - } - if (result.exitCode !== 0) { - throw new AppError('COMMAND_FAILED', `Failed to ${operation} Android clipboard text`, { - stdout: result.stdout, - stderr: result.stderr, - exitCode: result.exitCode, - }); - } - return result.stdout; -} - -function normalizeAndroidClipboardText(stdout: string): string { - const normalized = stdout.replace(/\r\n/g, '\n').replace(/\n$/, ''); - const prefixed = normalized.match(/^clipboard text:\s*(.*)$/i); - if (prefixed) return prefixed[1] ?? ''; - if (normalized.trim().toLowerCase() === 'null') return ''; - return normalized; -} - -function isAndroidInputTextUnsupported(error: unknown): boolean { - if (!(error instanceof AppError)) return false; - if (error.code !== 'COMMAND_FAILED') return false; - const stderr = String((error.details as any)?.stderr ?? '').toLowerCase(); - if (stderr.includes("exception occurred while executing 'text'")) return true; - if (stderr.includes('nullpointerexception') && stderr.includes('inputshellcommand.sendtext')) return true; - return false; -} - -async function clearFocusedText(device: DeviceInfo, count: number): Promise { - const deletes = Math.max(0, count); - await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', 'KEYCODE_MOVE_END']), { - allowFailure: true, - }); - const batchSize = 24; - for (let i = 0; i < deletes; i += batchSize) { - const size = Math.min(batchSize, deletes - i); - await runCmd( - 'adb', - adbArgs(device, ['shell', 'input', 'keyevent', ...Array(size).fill('KEYCODE_DEL')]), - { - allowFailure: true, - }, - ); - } -} - -async function readInputValueAtPoint( - device: DeviceInfo, - x: number, - y: number, -): Promise { - const xml = await dumpUiHierarchy(device); - const nodeRegex = /]*>/g; - let match: RegExpExecArray | null; - let focusedEdit: { text: string; area: number } | null = null; - let editAtPoint: { text: string; area: number } | null = null; - let anyAtPoint: { text: string; area: number } | null = null; - - while ((match = nodeRegex.exec(xml)) !== null) { - const node = match[0]; - const attrs = readNodeAttributes(node); - const rect = parseBounds(attrs.bounds); - if (!rect) continue; - const className = attrs.className ?? ''; - const text = decodeXmlEntities(attrs.text ?? ''); - const focused = attrs.focused ?? false; - if (!text) continue; - const area = Math.max(1, rect.width * rect.height); - const containsPoint = - x >= rect.x && - x <= rect.x + rect.width && - y >= rect.y && - y <= rect.y + rect.height; - - if (focused && isEditTextClass(className)) { - if (!focusedEdit || area <= focusedEdit.area) { - focusedEdit = { text, area }; - } - continue; - } - if (containsPoint && isEditTextClass(className)) { - if (!editAtPoint || area <= editAtPoint.area) { - editAtPoint = { text, area }; - } - continue; - } - if (containsPoint) { - if (!anyAtPoint || area <= anyAtPoint.area) { - anyAtPoint = { text, area }; - } - } - } - - return focusedEdit?.text ?? editAtPoint?.text ?? anyAtPoint?.text ?? null; -} - -function isEditTextClass(className: string): boolean { - const lower = className.toLowerCase(); - return lower.includes('edittext') || lower.includes('textfield'); -} - -function decodeXmlEntities(value: string): string { - return value - .replace(/"/g, '"') - .replace(/'/g, "'") - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/&/g, '&'); -} - -async function sleep(ms: number): Promise { - await new Promise((resolve) => setTimeout(resolve, ms)); -} - -function clampCount(value: number, min: number, max: number): number { - return Math.max(min, Math.min(max, value)); -} +export { ensureAdb } from './adb.ts'; + +export { + resolveAndroidApp, + listAndroidApps, + inferAndroidAppName, + getAndroidAppState, + openAndroidApp, + isAmStartError, + parseAndroidLaunchComponent, + openAndroidDevice, + closeAndroidApp, + installAndroidApp, + reinstallAndroidApp, +} from './app-lifecycle.ts'; + +export { + pressAndroid, + swipeAndroid, + backAndroid, + homeAndroid, + appSwitcherAndroid, + longPressAndroid, + typeAndroid, + focusAndroid, + fillAndroid, + scrollAndroid, + scrollIntoViewAndroid, +} from './input-actions.ts'; + +export { + type AndroidKeyboardState, + getAndroidKeyboardState, + dismissAndroidKeyboard, + readAndroidClipboardText, + writeAndroidClipboardText, +} from './device-input-state.ts'; + +export { setAndroidSetting } from './settings.ts'; + +export { pushAndroidNotification } from './notifications.ts'; + +export { snapshotAndroid, screenshotAndroid } from './snapshot.ts'; diff --git a/src/platforms/android/input-actions.ts b/src/platforms/android/input-actions.ts new file mode 100644 index 0000000000..3fb08fbd29 --- /dev/null +++ b/src/platforms/android/input-actions.ts @@ -0,0 +1,378 @@ +import { runCmd } from '../../utils/exec.ts'; +import { AppError } from '../../utils/errors.ts'; +import type { DeviceInfo } from '../../utils/device.ts'; +import { findBounds, parseBounds, readNodeAttributes } from './ui-hierarchy.ts'; +import { dumpUiHierarchy } from './snapshot.ts'; +import { adbArgs, isClipboardShellUnsupported, sleep } from './adb.ts'; + +export async function pressAndroid(device: DeviceInfo, x: number, y: number): Promise { + await runCmd('adb', adbArgs(device, ['shell', 'input', 'tap', String(x), String(y)])); +} + +export async function swipeAndroid( + device: DeviceInfo, + x1: number, + y1: number, + x2: number, + y2: number, + durationMs = 250, +): Promise { + await runCmd( + 'adb', + adbArgs(device, [ + 'shell', + 'input', + 'swipe', + String(x1), + String(y1), + String(x2), + String(y2), + String(durationMs), + ]), + ); +} + +export async function backAndroid(device: DeviceInfo): Promise { + await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '4'])); +} + +export async function homeAndroid(device: DeviceInfo): Promise { + await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '3'])); +} + +export async function appSwitcherAndroid(device: DeviceInfo): Promise { + await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '187'])); +} + +export async function longPressAndroid( + device: DeviceInfo, + x: number, + y: number, + durationMs = 800, +): Promise { + await runCmd( + 'adb', + adbArgs(device, [ + 'shell', + 'input', + 'swipe', + String(x), + String(y), + String(x), + String(y), + String(durationMs), + ]), + ); +} + +export async function typeAndroid(device: DeviceInfo, text: string): Promise { + const shouldInjectViaClipboard = shouldUseClipboardTextInjection(text); + if (shouldInjectViaClipboard) { + const clipboardResult = await typeAndroidViaClipboard(device, text); + if (clipboardResult === 'ok') return; + } + try { + const encoded = encodeAndroidInputText(text); + await runCmd('adb', adbArgs(device, ['shell', 'input', 'text', encoded])); + } catch (error) { + if (shouldInjectViaClipboard && isAndroidInputTextUnsupported(error)) { + throw new AppError( + 'COMMAND_FAILED', + 'Non-ASCII text input is not supported on this Android shell. Install an ADB keyboard IME or use ASCII input.', + { textPreview: text.slice(0, 32) }, + error instanceof Error ? error : undefined, + ); + } + throw error; + } +} + +export async function focusAndroid(device: DeviceInfo, x: number, y: number): Promise { + await pressAndroid(device, x, y); +} + +export async function fillAndroid( + device: DeviceInfo, + x: number, + y: number, + text: string, +): Promise { + const textCodePointLength = Array.from(text).length; + const requiresClipboardInjection = shouldUseClipboardTextInjection(text); + const attempts: Array<{ + strategy: 'input_text' | 'clipboard_paste' | 'chunked_input'; + clearPadding: number; + minClear: number; + maxClear: number; + }> = [{ strategy: 'input_text', clearPadding: 12, minClear: 8, maxClear: 48 }]; + if (!requiresClipboardInjection) { + attempts.push({ strategy: 'clipboard_paste', clearPadding: 12, minClear: 8, maxClear: 48 }); + attempts.push({ strategy: 'chunked_input', clearPadding: 24, minClear: 16, maxClear: 96 }); + } + + let lastActual: string | null = null; + + for (const attempt of attempts) { + await focusAndroid(device, x, y); + const clearCount = clampCount( + textCodePointLength + attempt.clearPadding, + attempt.minClear, + attempt.maxClear, + ); + await clearFocusedText(device, clearCount); + if (attempt.strategy === 'input_text') { + await typeAndroid(device, text); + } else if (attempt.strategy === 'clipboard_paste') { + const clipboardResult = await typeAndroidViaClipboard(device, text); + if (clipboardResult !== 'ok') { + continue; + } + } else { + await typeAndroidChunked(device, text, 1, 15); + } + lastActual = await readInputValueAtPoint(device, x, y); + if (lastActual === text) return; + } + + throw new AppError('COMMAND_FAILED', 'Android fill verification failed', { + expected: text, + actual: lastActual ?? null, + }); +} + +export async function scrollAndroid( + device: DeviceInfo, + direction: string, + amount = 0.6, +): Promise { + const size = await getAndroidScreenSize(device); + const { width, height } = size; + const distanceX = Math.floor(width * amount); + const distanceY = Math.floor(height * amount); + + const centerX = Math.floor(width / 2); + const centerY = Math.floor(height / 2); + + let x1 = centerX; + let y1 = centerY; + let x2 = centerX; + let y2 = centerY; + + switch (direction) { + case 'up': + // Content moves up -> swipe down. + y1 = centerY - Math.floor(distanceY / 2); + y2 = centerY + Math.floor(distanceY / 2); + break; + case 'down': + // Content moves down -> swipe up. + y1 = centerY + Math.floor(distanceY / 2); + y2 = centerY - Math.floor(distanceY / 2); + break; + case 'left': + // Content moves left -> swipe right. + x1 = centerX - Math.floor(distanceX / 2); + x2 = centerX + Math.floor(distanceX / 2); + break; + case 'right': + // Content moves right -> swipe left. + x1 = centerX + Math.floor(distanceX / 2); + x2 = centerX - Math.floor(distanceX / 2); + break; + default: + throw new AppError('INVALID_ARGS', `Unknown direction: ${direction}`); + } + + await runCmd( + 'adb', + adbArgs(device, [ + 'shell', + 'input', + 'swipe', + String(x1), + String(y1), + String(x2), + String(y2), + '300', + ]), + ); +} + +export async function scrollIntoViewAndroid(device: DeviceInfo, text: string): Promise { + const maxAttempts = 8; + for (let i = 0; i < maxAttempts; i += 1) { + let xml = ''; + try { + xml = await dumpUiHierarchy(device); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new AppError('UNSUPPORTED_OPERATION', `uiautomator dump failed: ${message}`); + } + if (findBounds(xml, text)) return; + await scrollAndroid(device, 'down', 0.5); + } + throw new AppError( + 'COMMAND_FAILED', + `Could not find element containing "${text}" after scrolling`, + ); +} + +async function getAndroidScreenSize( + device: DeviceInfo, +): Promise<{ width: number; height: number }> { + const result = await runCmd('adb', adbArgs(device, ['shell', 'wm', 'size'])); + const match = result.stdout.match(/Physical size:\s*(\d+)x(\d+)/); + if (!match) throw new AppError('COMMAND_FAILED', 'Unable to read screen size'); + return { width: Number(match[1]), height: Number(match[2]) }; +} + +async function typeAndroidChunked( + device: DeviceInfo, + text: string, + chunkSize: number, + delayMs: number, +): Promise { + const size = Math.max(1, Math.floor(chunkSize)); + const chars = Array.from(text); + for (let i = 0; i < chars.length; i += size) { + const chunk = chars.slice(i, i + size).join(''); + await typeAndroid(device, chunk); + if (delayMs > 0 && i + size < chars.length) { + await sleep(delayMs); + } + } +} + +function shouldUseClipboardTextInjection(text: string): boolean { + for (const char of text) { + const code = char.codePointAt(0); + if (code === undefined) continue; + if (code < 0x20 || code > 0x7e) return true; + } + return false; +} + +function encodeAndroidInputText(text: string): string { + // Android shell input uses `%s` as the escaped token for spaces. + return text.replace(/ /g, '%s'); +} + +async function typeAndroidViaClipboard( + device: DeviceInfo, + text: string, +): Promise<'ok' | 'unsupported' | 'failed'> { + const setClipboard = await runCmd( + 'adb', + adbArgs(device, ['shell', 'cmd', 'clipboard', 'set', 'text', text]), + { allowFailure: true }, + ); + if (setClipboard.exitCode !== 0) return 'failed'; + if (isClipboardShellUnsupported(setClipboard.stdout, setClipboard.stderr)) return 'unsupported'; + + const pasteByName = await runCmd( + 'adb', + adbArgs(device, ['shell', 'input', 'keyevent', 'KEYCODE_PASTE']), + { allowFailure: true }, + ); + if (pasteByName.exitCode === 0) return 'ok'; + + const pasteByCode = await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '279']), { + allowFailure: true, + }); + return pasteByCode.exitCode === 0 ? 'ok' : 'failed'; +} + +function isAndroidInputTextUnsupported(error: unknown): boolean { + if (!(error instanceof AppError)) return false; + if (error.code !== 'COMMAND_FAILED') return false; + const stderr = String((error.details as any)?.stderr ?? '').toLowerCase(); + if (stderr.includes("exception occurred while executing 'text'")) return true; + if (stderr.includes('nullpointerexception') && stderr.includes('inputshellcommand.sendtext')) return true; + return false; +} + +async function clearFocusedText(device: DeviceInfo, count: number): Promise { + const deletes = Math.max(0, count); + await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', 'KEYCODE_MOVE_END']), { + allowFailure: true, + }); + const batchSize = 24; + for (let i = 0; i < deletes; i += batchSize) { + const size = Math.min(batchSize, deletes - i); + await runCmd( + 'adb', + adbArgs(device, ['shell', 'input', 'keyevent', ...Array(size).fill('KEYCODE_DEL')]), + { + allowFailure: true, + }, + ); + } +} + +async function readInputValueAtPoint( + device: DeviceInfo, + x: number, + y: number, +): Promise { + const xml = await dumpUiHierarchy(device); + const nodeRegex = /]*>/g; + let match: RegExpExecArray | null; + let focusedEdit: { text: string; area: number } | null = null; + let editAtPoint: { text: string; area: number } | null = null; + let anyAtPoint: { text: string; area: number } | null = null; + + while ((match = nodeRegex.exec(xml)) !== null) { + const node = match[0]; + const attrs = readNodeAttributes(node); + const rect = parseBounds(attrs.bounds); + if (!rect) continue; + const className = attrs.className ?? ''; + const text = decodeXmlEntities(attrs.text ?? ''); + const focused = attrs.focused ?? false; + if (!text) continue; + const area = Math.max(1, rect.width * rect.height); + const containsPoint = + x >= rect.x && + x <= rect.x + rect.width && + y >= rect.y && + y <= rect.y + rect.height; + + if (focused && isEditTextClass(className)) { + if (!focusedEdit || area <= focusedEdit.area) { + focusedEdit = { text, area }; + } + continue; + } + if (containsPoint && isEditTextClass(className)) { + if (!editAtPoint || area <= editAtPoint.area) { + editAtPoint = { text, area }; + } + continue; + } + if (containsPoint) { + if (!anyAtPoint || area <= anyAtPoint.area) { + anyAtPoint = { text, area }; + } + } + } + + return focusedEdit?.text ?? editAtPoint?.text ?? anyAtPoint?.text ?? null; +} + +function isEditTextClass(className: string): boolean { + const lower = className.toLowerCase(); + return lower.includes('edittext') || lower.includes('textfield'); +} + +function decodeXmlEntities(value: string): string { + return value + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/&/g, '&'); +} + +function clampCount(value: number, min: number, max: number): number { + return Math.max(min, Math.min(max, value)); +} diff --git a/src/platforms/android/notifications.ts b/src/platforms/android/notifications.ts new file mode 100644 index 0000000000..37c178b172 --- /dev/null +++ b/src/platforms/android/notifications.ts @@ -0,0 +1,61 @@ +import { runCmd } from '../../utils/exec.ts'; +import { AppError } from '../../utils/errors.ts'; +import type { DeviceInfo } from '../../utils/device.ts'; +import { adbArgs } from './adb.ts'; + +type AndroidBroadcastPayload = { + action?: string; + receiver?: string; + extras?: Record; +}; + +export async function pushAndroidNotification( + device: DeviceInfo, + packageName: string, + payload: AndroidBroadcastPayload, +): Promise<{ action: string; extrasCount: number }> { + const action = typeof payload.action === 'string' && payload.action.trim() + ? payload.action.trim() + : `${packageName}.TEST_PUSH`; + const args = ['shell', 'am', 'broadcast', '-a', action, '-p', packageName]; + const receiver = typeof payload.receiver === 'string' ? payload.receiver.trim() : ''; + if (receiver) { + args.push('-n', receiver); + } + const rawExtras = payload.extras; + if (rawExtras !== undefined && (typeof rawExtras !== 'object' || rawExtras === null || Array.isArray(rawExtras))) { + throw new AppError('INVALID_ARGS', 'Android push payload extras must be an object'); + } + const extras = rawExtras ?? {}; + let extrasCount = 0; + for (const [key, rawValue] of Object.entries(extras)) { + if (!key) continue; + appendBroadcastExtra(args, key, rawValue); + extrasCount += 1; + } + await runCmd('adb', adbArgs(device, args)); + return { action, extrasCount }; +} + +function appendBroadcastExtra(args: string[], key: string, value: unknown): void { + if (typeof value === 'string') { + args.push('--es', key, value); + return; + } + if (typeof value === 'boolean') { + args.push('--ez', key, value ? 'true' : 'false'); + return; + } + if (typeof value === 'number' && Number.isFinite(value)) { + if (Number.isInteger(value)) { + args.push('--ei', key, String(value)); + return; + } + args.push('--ef', key, String(value)); + return; + } + throw new AppError( + 'INVALID_ARGS', + `Unsupported Android broadcast extra type for "${key}". Use string, boolean, or number.`, + ); +} diff --git a/src/platforms/android/settings.ts b/src/platforms/android/settings.ts new file mode 100644 index 0000000000..8a9cbf1d66 --- /dev/null +++ b/src/platforms/android/settings.ts @@ -0,0 +1,314 @@ +import { runCmd } from '../../utils/exec.ts'; +import { AppError } from '../../utils/errors.ts'; +import type { DeviceInfo } from '../../utils/device.ts'; +import { + parsePermissionAction, + parsePermissionTarget, + type PermissionSettingOptions, +} from '../permission-utils.ts'; +import { parseAppearanceAction } from '../appearance.ts'; +import { adbArgs } from './adb.ts'; + +export async function setAndroidSetting( + device: DeviceInfo, + setting: string, + state: string, + appPackage?: string, + options?: PermissionSettingOptions, +): Promise { + const normalized = setting.toLowerCase(); + switch (normalized) { + case 'wifi': { + const enabled = parseSettingState(state); + await runCmd('adb', adbArgs(device, ['shell', 'svc', 'wifi', enabled ? 'enable' : 'disable'])); + return; + } + case 'airplane': { + const enabled = parseSettingState(state); + const flag = enabled ? '1' : '0'; + const bool = enabled ? 'true' : 'false'; + await runCmd('adb', adbArgs(device, ['shell', 'settings', 'put', 'global', 'airplane_mode_on', flag])); + await runCmd('adb', adbArgs(device, ['shell', 'am', 'broadcast', '-a', 'android.intent.action.AIRPLANE_MODE', '--ez', 'state', bool])); + return; + } + case 'location': { + const enabled = parseSettingState(state); + const mode = enabled ? '3' : '0'; + await runCmd('adb', adbArgs(device, ['shell', 'settings', 'put', 'secure', 'location_mode', mode])); + return; + } + case 'appearance': { + const target = await resolveAndroidAppearanceTarget(device, state); + await runCmd('adb', adbArgs(device, ['shell', 'cmd', 'uimode', 'night', target === 'dark' ? 'yes' : 'no'])); + return; + } + case 'fingerprint': { + const action = parseAndroidFingerprintAction(state); + await runAndroidFingerprintCommand(device, action); + return; + } + case 'permission': { + if (!appPackage) { + throw new AppError( + 'INVALID_ARGS', + 'permission setting requires an active app in session', + ); + } + const action = parsePermissionAction(state); + const target = parseAndroidPermissionTarget(options?.permissionTarget, options?.permissionMode); + if (target.kind === 'notifications') { + await setAndroidNotificationPermission(device, appPackage, action, target); + return; + } + const pmAction = action === 'grant' ? 'grant' : 'revoke'; + if (target.type === 'photos') { + await setAndroidPhotoPermission(device, appPackage, pmAction); + return; + } + await runCmd('adb', adbArgs(device, ['shell', 'pm', pmAction, appPackage, target.value])); + return; + } + default: + throw new AppError('INVALID_ARGS', `Unsupported setting: ${setting}`); + } +} + +type AndroidFingerprintAction = 'match' | 'nonmatch'; + +function parseAndroidFingerprintAction(state: string): AndroidFingerprintAction { + const normalized = state.trim().toLowerCase(); + if (normalized === 'match') return 'match'; + if (normalized === 'nonmatch') return 'nonmatch'; + throw new AppError( + 'INVALID_ARGS', + `Invalid fingerprint state: ${state}. Use match|nonmatch.`, + ); +} + +async function runAndroidFingerprintCommand( + device: DeviceInfo, + action: AndroidFingerprintAction, +): Promise { + const attempts = androidFingerprintCommandAttempts(device, action); + const failures: Array<{ args: string[]; stdout: string; stderr: string; exitCode: number }> = []; + + for (const args of attempts) { + const result = await runCmd('adb', adbArgs(device, args), { allowFailure: true }); + if (result.exitCode === 0) return; + failures.push({ + args, + stdout: result.stdout, + stderr: result.stderr, + exitCode: result.exitCode, + }); + } + + const attemptsPayload = failures.map((failure) => ({ + args: failure.args.join(' '), + exitCode: failure.exitCode, + stderr: failure.stderr.slice(0, 400), + })); + const capabilityMissing = failures.length > 0 && failures.every((failure) => + isAndroidFingerprintCapabilityMissing(failure.stdout, failure.stderr) + ); + if (capabilityMissing) { + throw new AppError( + 'UNSUPPORTED_OPERATION', + 'Android fingerprint simulation is not supported on this target/runtime.', + { + deviceId: device.id, + action, + hint: 'Use an Android emulator with biometric support, or a device/runtime that exposes cmd fingerprint.', + attempts: attemptsPayload, + }, + ); + } + throw new AppError('COMMAND_FAILED', 'Failed to simulate Android fingerprint.', { + deviceId: device.id, + action, + attempts: attemptsPayload, + }); +} + +function androidFingerprintCommandAttempts( + device: DeviceInfo, + action: AndroidFingerprintAction, +): string[][] { + const fingerprintId = action === 'match' ? '1' : '9999'; + const attempts: string[][] = [ + ['shell', 'cmd', 'fingerprint', 'touch', fingerprintId], + ['shell', 'cmd', 'fingerprint', 'finger', fingerprintId], + ]; + if (device.kind === 'emulator') { + attempts.push(['emu', 'finger', 'touch', fingerprintId]); + } + return attempts; +} + +function isAndroidFingerprintCapabilityMissing(stdout: string, stderr: string): boolean { + const text = `${stdout}\n${stderr}`.toLowerCase(); + return ( + text.includes('unknown command') || + text.includes("can't find service: fingerprint") || + text.includes('service fingerprint was not found') || + text.includes('fingerprint cmd unavailable') || + text.includes('emu command is not supported') || + text.includes('emulator console is not running') || + (text.includes('fingerprint') && text.includes('not found')) + ); +} + +function parseSettingState(state: string): boolean { + const normalized = state.toLowerCase(); + if (normalized === 'on' || normalized === 'true' || normalized === '1') return true; + if (normalized === 'off' || normalized === 'false' || normalized === '0') return false; + throw new AppError('INVALID_ARGS', `Invalid setting state: ${state}`); +} + +async function resolveAndroidAppearanceTarget( + device: DeviceInfo, + state: string, +): Promise<'light' | 'dark'> { + const action = parseAppearanceAction(state); + if (action !== 'toggle') return action; + + const currentResult = await runCmd('adb', adbArgs(device, ['shell', 'cmd', 'uimode', 'night']), { + allowFailure: true, + }); + if (currentResult.exitCode !== 0) { + throw new AppError('COMMAND_FAILED', 'Failed to read current Android appearance', { + stdout: currentResult.stdout, + stderr: currentResult.stderr, + exitCode: currentResult.exitCode, + }); + } + const current = parseAndroidAppearance(currentResult.stdout, currentResult.stderr); + if (!current) { + throw new AppError('COMMAND_FAILED', 'Unable to determine current Android appearance for toggle', { + stdout: currentResult.stdout, + stderr: currentResult.stderr, + }); + } + if (current === 'auto') return 'dark'; + return current === 'dark' ? 'light' : 'dark'; +} + +function parseAndroidAppearance(stdout: string, stderr: string): 'light' | 'dark' | 'auto' | null { + const match = /night mode:\s*(yes|no|auto)\b/i.exec(`${stdout}\n${stderr}`); + if (!match) return null; + const value = match[1].toLowerCase(); + if (value === 'yes') return 'dark'; + if (value === 'no') return 'light'; + if (value === 'auto') return 'auto'; + return null; +} + +function parseAndroidPermissionTarget( + permissionTarget: string | undefined, + permissionMode: string | undefined, +): + | { kind: 'pm'; value: string; type: 'camera' | 'microphone' | 'photos' | 'contacts' } + | { kind: 'notifications'; appOps: string; permission: string } { + const normalized = parsePermissionTarget(permissionTarget); + if (permissionMode?.trim()) { + throw new AppError( + 'INVALID_ARGS', + `Permission mode is only supported for photos. Received: ${permissionMode}.`, + ); + } + if (normalized === 'camera') return { kind: 'pm', value: 'android.permission.CAMERA', type: 'camera' }; + if (normalized === 'microphone') { + return { kind: 'pm', value: 'android.permission.RECORD_AUDIO', type: 'microphone' }; + } + if (normalized === 'photos') { + return { kind: 'pm', value: 'android.permission.READ_MEDIA_IMAGES', type: 'photos' }; + } + if (normalized === 'contacts') { + return { kind: 'pm', value: 'android.permission.READ_CONTACTS', type: 'contacts' }; + } + if (normalized === 'notifications') { + return { + kind: 'notifications', + appOps: 'POST_NOTIFICATION', + permission: 'android.permission.POST_NOTIFICATIONS', + }; + } + throw new AppError( + 'INVALID_ARGS', + `Unsupported permission target on Android: ${permissionTarget}. Use camera|microphone|photos|contacts|notifications.`, + ); +} + +async function setAndroidPhotoPermission( + device: DeviceInfo, + appPackage: string, + pmAction: 'grant' | 'revoke', +): Promise { + const sdkInt = await getAndroidSdkInt(device); + const candidates = + sdkInt !== null && sdkInt >= 33 + ? ['android.permission.READ_MEDIA_IMAGES', 'android.permission.READ_EXTERNAL_STORAGE'] + : ['android.permission.READ_EXTERNAL_STORAGE', 'android.permission.READ_MEDIA_IMAGES']; + + const failures: Array<{ permission: string; stderr: string; exitCode: number }> = []; + for (const permission of candidates) { + const result = await runCmd( + 'adb', + adbArgs(device, ['shell', 'pm', pmAction, appPackage, permission]), + { allowFailure: true }, + ); + if (result.exitCode === 0) return; + failures.push({ permission, stderr: result.stderr, exitCode: result.exitCode }); + } + + throw new AppError('COMMAND_FAILED', `Failed to ${pmAction} Android photos permission`, { + appPackage, + sdkInt, + attempts: failures, + }); +} + +async function setAndroidNotificationPermission( + device: DeviceInfo, + appPackage: string, + action: 'grant' | 'deny' | 'reset', + target: { appOps: string; permission: string }, +): Promise { + const appOpsMode = action === 'grant' ? 'allow' : action === 'deny' ? 'deny' : 'default'; + if (action === 'grant') { + await runCmd( + 'adb', + adbArgs(device, ['shell', 'pm', 'grant', appPackage, target.permission]), + { allowFailure: true }, + ); + } else { + await runCmd( + 'adb', + adbArgs(device, ['shell', 'pm', 'revoke', appPackage, target.permission]), + { allowFailure: true }, + ); + if (action === 'reset') { + await runCmd( + 'adb', + adbArgs(device, ['shell', 'pm', 'clear-permission-flags', appPackage, target.permission, 'user-set']), + { allowFailure: true }, + ); + await runCmd( + 'adb', + adbArgs(device, ['shell', 'pm', 'clear-permission-flags', appPackage, target.permission, 'user-fixed']), + { allowFailure: true }, + ); + } + } + await runCmd('adb', adbArgs(device, ['shell', 'appops', 'set', appPackage, target.appOps, appOpsMode])); +} + +async function getAndroidSdkInt(device: DeviceInfo): Promise { + const result = await runCmd('adb', adbArgs(device, ['shell', 'getprop', 'ro.build.version.sdk']), { + allowFailure: true, + }); + if (result.exitCode !== 0) return null; + const value = Number.parseInt(result.stdout.trim(), 10); + if (!Number.isFinite(value) || value <= 0) return null; + return value; +} diff --git a/src/platforms/android/snapshot.ts b/src/platforms/android/snapshot.ts new file mode 100644 index 0000000000..2ba4e4bba6 --- /dev/null +++ b/src/platforms/android/snapshot.ts @@ -0,0 +1,98 @@ +import { promises as fs } from 'node:fs'; +import { runCmd } from '../../utils/exec.ts'; +import { withRetry } from '../../utils/retry.ts'; +import { AppError } from '../../utils/errors.ts'; +import type { DeviceInfo } from '../../utils/device.ts'; +import type { RawSnapshotNode, SnapshotOptions } from '../../utils/snapshot.ts'; +import { parseUiHierarchy } from './ui-hierarchy.ts'; +import { adbArgs } from './adb.ts'; + +export async function snapshotAndroid( + device: DeviceInfo, + options: SnapshotOptions = {}, +): Promise<{ + nodes: RawSnapshotNode[]; + truncated?: boolean; +}> { + const xml = await dumpUiHierarchy(device); + return parseUiHierarchy(xml, 800, options); +} + +export async function screenshotAndroid(device: DeviceInfo, outPath: string): Promise { + const result = await runCmd('adb', adbArgs(device, ['exec-out', 'screencap', '-p']), { + binaryStdout: true, + }); + if (!result.stdoutBuffer) { + throw new AppError('COMMAND_FAILED', 'Failed to capture screenshot'); + } + await fs.writeFile(outPath, result.stdoutBuffer); +} + +export async function dumpUiHierarchy(device: DeviceInfo): Promise { + return withRetry(() => dumpUiHierarchyOnce(device), { + shouldRetry: isRetryableAdbError, + }); +} + +async function dumpUiHierarchyOnce(device: DeviceInfo): Promise { + // Preferred: stream XML directly to stdout, avoiding file I/O race conditions. + const streamed = await runCmd( + 'adb', + adbArgs(device, ['exec-out', 'uiautomator', 'dump', '/dev/tty']), + { allowFailure: true }, + ); + if (streamed.exitCode === 0) { + const fromStream = extractUiDumpXml(streamed.stdout, streamed.stderr); + if (fromStream) return fromStream; + } + + // Fallback: dump to file and read back. + // If `cat` fails with "no such file", the outer withRetry (via isRetryableAdbError) handles it. + const dumpPath = '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/sdcard/window_dump.xml'; + const dumpResult = await runCmd( + 'adb', + adbArgs(device, ['shell', 'uiautomator', 'dump', dumpPath]), + ); + const actualPath = resolveDumpPath(dumpPath, dumpResult.stdout, dumpResult.stderr); + + const result = await runCmd('adb', adbArgs(device, ['shell', 'cat', actualPath])); + const xml = extractUiDumpXml(result.stdout, result.stderr); + if (!xml) { + throw new AppError('COMMAND_FAILED', 'uiautomator dump did not return XML', { + stdout: result.stdout, + stderr: result.stderr, + }); + } + return xml; +} + +function resolveDumpPath(defaultPath: string, stdout: string, stderr: string): string { + const text = `${stdout}\n${stderr}`; + const match = /dumped to:\s*(\S+)/i.exec(text); + return match?.[1] ?? defaultPath; +} + +function extractUiDumpXml(stdout: string, stderr: string): string | null { + const text = `${stdout}\n${stderr}`; + const start = text.indexOf('= 0 ? start : text.indexOf(''); + if (end < 0 || end < hierarchyStart) return null; + const xml = text.slice(hierarchyStart, end + ''.length).trim(); + return xml.length > 0 ? xml : null; +} + +function isRetryableAdbError(err: unknown): boolean { + if (!(err instanceof AppError)) return false; + if (err.code !== 'COMMAND_FAILED') return false; + const stderr = `${(err.details as any)?.stderr ?? ''}`.toLowerCase(); + if (stderr.includes('device offline')) return true; + if (stderr.includes('device not found')) return true; + if (stderr.includes('transport error')) return true; + if (stderr.includes('connection reset')) return true; + if (stderr.includes('broken pipe')) return true; + if (stderr.includes('timed out')) return true; + if (stderr.includes('no such file or directory')) return true; + return false; +}