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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions src/backends/adb-backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
? `<node ${attrs} visible-to-user="true">${children}</node>`
: `<node ${attrs} visible-to-user="true" />`;
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 = `<?xml version="1.0" encoding="UTF-8"?><hierarchy rotation="0">${windows.join('')}</hierarchy>`;
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);
});
});
40 changes: 26 additions & 14 deletions src/backends/adb-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -942,20 +942,15 @@ export class AdbBackend implements DeviceBackend {
}

async dismissAlert(accept: boolean): Promise<void> {
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<LogsResult> {
Expand Down Expand Up @@ -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 `<app>: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) {
Expand Down
127 changes: 127 additions & 0 deletions src/backends/idb-backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>[],
): Record<string, unknown> => ({
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<string, unknown>[]): Record<string, unknown> =>
element(
'Alert',
'',
[36, 360, 330, 150],
[
element(
'StaticText',
'Open in \u201cMetaMask\u201d?',
[52, 380, 298, 22],
),
...buttons,
],
);

const showScreen = (
screen: Record<string, unknown>[],
hitAtPoint: (x: number, y: number) => Record<string, unknown>,
): 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<string, unknown> =>
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;
Expand Down
22 changes: 9 additions & 13 deletions src/backends/idb-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1010,19 +1010,15 @@ export class IdbBackend implements DeviceBackend {
async dismissAlert(accept: boolean): Promise<void> {
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<LogsResult> {
Expand Down
Loading
Loading