diff --git a/src/backends/adb-backend.test.ts b/src/backends/adb-backend.test.ts index 2291152..8c1413a 100644 --- a/src/backends/adb-backend.test.ts +++ b/src/backends/adb-backend.test.ts @@ -2190,3 +2190,127 @@ describe('AdbBackend clipboard', () => { await expect(backend.getClipboard()).rejects.toThrow(/not supported/u); }); }); + +describe('AdbBackend.dismissAlert', () => { + let backend: AdbBackend; + + const node = (attrs: string, children = ''): string => + children + ? `${children}` + : ``; + const window = (index: number, layer: number, content: string): string => + node( + `window-index="${index}" window-type="1" window-layer="${layer}" window-bounds="[0,0][1080,2400]" class="android.widget.FrameLayout" drawing-order="0" bounds="[0,0][1080,2400]"`, + content, + ); + const button = (text: string, bounds: string, id = ''): string => + node( + `text="${text}" resource-id="${id}" class="android.widget.Button" clickable="true" drawing-order="1" bounds="${bounds}"`, + ); + const appWindow = window( + 0, + 0, + [ + button('Tokens', '[0,300][540,400]'), + button('Notifications', '[540,300][1080,400]'), + button('Continue', '[0,2200][1080,2300]'), + button('Allow', '[0,1900][1080,2000]'), + ].join(''), + ); + const dialog = (buttons: string): string => + window( + 1, + 1, + node( + 'resource-id="android:id/content" class="android.widget.FrameLayout" drawing-order="1" bounds="[28,503][1052,1076]"', + node( + 'text="Device name" resource-id="com.android.settings:id/alertTitle" class="android.widget.TextView" drawing-order="1" bounds="[133,592][947,677]"', + ) + buttons, + ), + ); + const okCancel = + button('Cancel', '[596,876][792,1002]', 'android:id/button2') + + button('OK', '[813,876][946,1002]', 'android:id/button1'); + + const tapCalls = (): unknown[][] => + mockExecStrict.mock.calls.filter(([, args]) => args?.includes('tap')); + + const showScreen = (...windows: string[]): void => { + const xml = `${windows.join('')}`; + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('wm')) { + return 'Physical size: 1080x2400'; + } + return args?.includes('cat') ? xml : ''; + }); + }; + + beforeEach(() => { + vi.clearAllMocks(); + process.env.DEVICE_MCP_ADB_SNAPSHOT = 'dump'; + backend = new AdbBackend('emulator-5556'); + }); + + afterEach(() => { + delete process.env.DEVICE_MCP_ADB_SNAPSHOT; + }); + + it.each([true, false])( + 'refuses with no alert on screen (accept: %s) and taps nothing', + async (accept) => { + showScreen(appWindow); + + await expect(backend.dismissAlert(accept)).rejects.toThrow( + 'No alert on screen', + ); + expect(tapCalls()).toHaveLength(0); + }, + ); + + it.each([ + [true, ['880', '939']], + [false, ['694', '939']], + ])( + 'taps the alert button (accept: %s), not a matching label behind it', + async (accept, point) => { + showScreen(appWindow, dialog(okCancel)); + + await backend.dismissAlert(accept); + + expect(tapCalls()).toStrictEqual([ + ['adb', ['-s', 'emulator-5556', 'shell', 'input', 'tap', ...point]], + ]); + }, + ); + + it('refuses when only a button outside the alert matches', async () => { + showScreen( + appWindow, + dialog(button('Later', '[596,876][792,1002]', 'android:id/button2')), + ); + + await expect(backend.dismissAlert(true)).rejects.toThrow( + 'No alert button found in the alert', + ); + expect(tapCalls()).toHaveLength(0); + }); + + it('refuses when something covers the alert button', async () => { + showScreen( + appWindow, + dialog(okCancel), + window( + 2, + 2, + node( + 'content-desc="Tools" class="android.widget.ImageView" drawing-order="1" bounds="[800,850][960,1030]"', + ), + ), + ); + + await expect(backend.dismissAlert(true)).rejects.toMatchObject({ + code: 'TARGET_OBSCURED', + }); + expect(tapCalls()).toHaveLength(0); + }); +}); diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index 68393e8..d50997f 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -54,7 +54,7 @@ import type { WindowSize, } from './types.js'; import { runWebViewCdp } from './webview-cdp.js'; -import { ACCEPT_LABELS, DENY_LABELS } from '../utils/alert-labels.js'; +import { findAlertButton, NO_ALERT_MESSAGE } from '../utils/alert-labels.js'; import { assertAndroidHittable, hasInputMethodAbove, @@ -942,20 +942,15 @@ export class AdbBackend implements DeviceBackend { } async dismissAlert(accept: boolean): Promise { - const snap = await this.snapshot(); - const candidates = accept ? ACCEPT_LABELS : DENY_LABELS; - - for (const label of candidates) { - const element = findElement(snap.hierarchy, { text: label }); - if (element) { - const cx = Math.round(element.frame.x + element.frame.width / 2); - const cy = Math.round(element.frame.y + element.frame.height / 2); - await this.tapCoordinates(cx, cy); - return; - } + const alert = findAndroidAlert((await this.snapshot()).hierarchy); + if (!alert) { + throw new Error(NO_ALERT_MESSAGE); } - - throw new Error(`No alert button found. Tried: ${candidates.join(', ')}`); + const button = findAlertButton(alert, accept); + await this.tapElement( + { text: button.value ?? button.label }, + { element: button }, + ); } async getLogs(durationSeconds = 30, filter?: string): Promise { @@ -1309,6 +1304,23 @@ export class AdbBackend implements DeviceBackend { } } +const ALERT_MARKER_ID = + /^(?:[\w.]+:id\/alertTitle|android:id\/button[123]|com\.(?:google\.)?android\.permissioncontroller:id\/.+)$/u; + +/** + * The window root that holds an `AlertDialog` (its title or button ids, also + * AppCompat's `:id/alertTitle`) or a runtime permission dialog. + * + * @param roots - The snapshot's window roots. + * @returns The alert's window root, or undefined when no alert is shown. + */ +function findAndroidAlert(roots: UIElement[]): UIElement | undefined { + const hasMarker = (element: UIElement): boolean => + ALERT_MARKER_ID.test(element.identifier ?? '') || + (element.children ?? []).some(hasMarker); + return roots.find(hasMarker); +} + function collectAndroidAlertTexts(elements: UIElement[]): string[] { const texts: string[] = []; for (const el of elements) { diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index 94a89c8..e4a76cc 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -1846,6 +1846,133 @@ describe('IdbBackend tap hit-test', () => { }); }); +describe('IdbBackend.dismissAlert', () => { + const udid = 'AAAA1111-BBBB-CCCC-DDDD-EEEE2222FFFF'; + let backend: IdbBackend; + + const element = ( + type: string, + label: string, + frame: [number, number, number, number], + children?: Record[], + ): Record => ({ + type, + AXLabel: label, + frame: { x: frame[0], y: frame[1], width: frame[2], height: frame[3] }, + ...(children && { children }), + }); + const ok = element('Button', 'OK', [201, 466, 165, 44]); + const cancel = element('Button', 'Cancel', [36, 466, 165, 44]); + const appScreen = [ + element('Button', 'Tokens', [0, 300, 201, 44]), + element('Button', 'Notifications', [201, 300, 201, 44]), + element('Button', 'Continue', [16, 800, 370, 48]), + element('Button', 'Allow', [16, 700, 370, 48]), + ]; + const alert = (buttons: Record[]): Record => + element( + 'Alert', + '', + [36, 360, 330, 150], + [ + element( + 'StaticText', + 'Open in \u201cMetaMask\u201d?', + [52, 380, 298, 22], + ), + ...buttons, + ], + ); + + const showScreen = ( + screen: Record[], + hitAtPoint: (x: number, y: number) => Record, + ): void => { + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.[0] === 'describe' && args.includes('--json')) { + return JSON.stringify({ + os_version: '26.5', + screen_dimensions: { width_points: 402, height_points: 874 }, + }); + } + if (args?.[1] === 'describe-all') { + return JSON.stringify([ + element('Application', 'MetaMask', [0, 0, 402, 874], screen), + ]); + } + if (args?.[1] === 'describe-point') { + return JSON.stringify(hitAtPoint(Number(args[2]), Number(args[3]))); + } + return ''; + }); + }; + const hitButtons = (x: number): Record => + x > 201 ? ok : cancel; + + const tapCalls = (): unknown[][] => + mockExecStrict.mock.calls + .filter(([, args]) => args?.[1] === 'tap') + .map(([, args]) => args.slice(2, 4)); + + beforeEach(() => { + vi.clearAllMocks(); + connectionState.alive = true; + mockSupportsApi.mockResolvedValue(true); + mockSupportsNested.mockResolvedValue(true); + mockExec.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); + backend = new IdbBackend(udid); + }); + + it.each([true, false])( + 'refuses with no alert on screen (accept: %s) and taps nothing', + async (accept) => { + showScreen(appScreen, hitButtons); + + await expect(backend.dismissAlert(accept)).rejects.toThrow( + 'No alert on screen', + ); + expect(tapCalls()).toHaveLength(0); + }, + ); + + it.each([ + [true, ['284', '488']], + [false, ['119', '488']], + ])( + 'taps the alert button (accept: %s), not a matching label behind it', + async (accept, point) => { + showScreen([...appScreen, alert([cancel, ok])], hitButtons); + + await backend.dismissAlert(accept); + + expect(tapCalls()).toStrictEqual([point]); + }, + ); + + it('refuses when only a button outside the alert matches', async () => { + showScreen( + [...appScreen, alert([element('Button', 'Later', [36, 466, 330, 44])])], + hitButtons, + ); + + await expect(backend.dismissAlert(true)).rejects.toThrow( + 'No alert button found in the alert', + ); + expect(tapCalls()).toHaveLength(0); + }); + + it('refuses when something covers the alert button', async () => { + showScreen([...appScreen, alert([cancel, ok])], () => + element('Button', 'Tools', [260, 440, 80, 80]), + ); + + await expect(backend.dismissAlert(true)).rejects.toBeInstanceOf( + TargetObscuredError, + ); + expect(tapCalls()).toHaveLength(0); + }); +}); + describe('IdbBackend device description cache', () => { const udid = 'AAAA1111-BBBB-CCCC-DDDD-EEEE2222FFFF'; let backend: IdbBackend; diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index c6c47bb..0478288 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -22,7 +22,7 @@ import type { UIElement, WindowSize, } from './types.js'; -import { ACCEPT_LABELS, DENY_LABELS } from '../utils/alert-labels.js'; +import { findAlertButton, NO_ALERT_MESSAGE } from '../utils/alert-labels.js'; import { findElement, findAncestors, @@ -1010,19 +1010,15 @@ export class IdbBackend implements DeviceBackend { async dismissAlert(accept: boolean): Promise { await this.ensureConnected(); const snap = await this.snapshot(); - const candidates = accept ? ACCEPT_LABELS : DENY_LABELS; - - for (const label of candidates) { - const element = findElement(snap.hierarchy, { label }); - if (element) { - const cx = Math.round(element.frame.x + element.frame.width / 2); - const cy = Math.round(element.frame.y + element.frame.height / 2); - await this.tapCoordinates(cx, cy); - return; - } + const alert = findElement(snap.hierarchy, { type: 'Alert', exact: true }); + if (!alert) { + throw new Error(NO_ALERT_MESSAGE); } - - throw new Error(`No alert button found. Tried: ${candidates.join(', ')}`); + const button = findAlertButton(alert, accept); + await this.tapElement( + { label: button.label ?? button.value }, + { element: button }, + ); } async getLogs(durationSeconds = 30, filter?: string): Promise { diff --git a/src/utils/alert-labels.ts b/src/utils/alert-labels.ts index 30083ee..5f8c370 100644 --- a/src/utils/alert-labels.ts +++ b/src/utils/alert-labels.ts @@ -1,3 +1,5 @@ +import type { UIElement } from '../backends/types.js'; + export const ACCEPT_LABELS = [ 'Allow', 'OK', @@ -21,3 +23,39 @@ export const DENY_LABELS = [ 'Maybe Later', 'DENY', ]; + +export const NO_ALERT_MESSAGE = + 'No alert on screen; nothing was tapped.\n' + + 'Use device_snapshot to inspect the current UI hierarchy.'; + +/** + * The button to tap inside an alert: the first label of the accept or deny + * list that a descendant's label or text equals, ignoring case. + * + * @param alert - The alert container. + * @param accept - Accept (true) or deny (false). + * @returns The button. + * @throws When no descendant has one of the labels. + */ +export function findAlertButton(alert: UIElement, accept: boolean): UIElement { + const labels = accept ? ACCEPT_LABELS : DENY_LABELS; + const descendants = flatten(alert.children ?? []); + for (const label of labels) { + const wanted = label.toLowerCase(); + const button = descendants.find((element) => + [element.label, element.value].some( + (text) => text?.toLowerCase() === wanted, + ), + ); + if (button) { + return button; + } + } + throw new Error( + `No alert button found in the alert; nothing was tapped. Tried: ${labels.join(', ')}`, + ); +} + +function flatten(elements: UIElement[]): UIElement[] { + return elements.flatMap((el) => [el, ...flatten(el.children ?? [])]); +}