diff --git a/src/backends/adb-backend.test.ts b/src/backends/adb-backend.test.ts index 71749f6..00b2d24 100644 --- a/src/backends/adb-backend.test.ts +++ b/src/backends/adb-backend.test.ts @@ -737,6 +737,243 @@ describe('AdbBackend.tapElement', () => { }); }); +describe('AdbBackend.typeText', () => { + let backend: AdbBackend; + + const inputCalls = (): string[][] => + mockExecStrict.mock.calls.map(([, args]) => (args ?? []).slice(3)); + + const selectAllCalls = (): string[][] => + mockExec.mock.calls.map(([, args]) => (args ?? []).slice(3)); + + beforeEach(() => { + vi.clearAllMocks(); + mockExecStrict.mockResolvedValue(''); + mockExec.mockResolvedValue({ stdout: '', stderr: '', exitCode: 0 }); + backend = new AdbBackend('emulator-5554'); + }); + + it('also selects all with Ctrl+A before the delete', async () => { + await backend.typeText('abc'); + + expect(selectAllCalls()).toStrictEqual([ + ['input', 'keycombination', 'KEYCODE_CTRL_LEFT', 'KEYCODE_A'], + ]); + }); + + it('sends Ctrl+A before the DEL', async () => { + await backend.typeText('abc'); + + const delIndex = inputCalls().findIndex( + (args) => args.join(' ') === 'input keyevent 67', + ); + const [selectAllOrder] = mockExec.mock.invocationCallOrder; + const delOrder = mockExecStrict.mock.invocationCallOrder[delIndex]; + expect(selectAllOrder).toBeLessThan(delOrder); + }); + + it('still clears and types when Ctrl+A is not supported', async () => { + mockExec.mockResolvedValue({ + stdout: '', + stderr: 'Error: Unknown command: keycombination', + exitCode: 255, + }); + + await backend.typeText('abc'); + + expect(inputCalls().at(-1)).toStrictEqual(['input', 'text', 'abc']); + }); + + it('clears the field, then types the escaped text', async () => { + await backend.typeText('a b&c'); + + expect(inputCalls()).toStrictEqual([ + ['input', 'keyevent', 'KEYCODE_MOVE_HOME'], + [ + 'input', + 'keyevent', + '--longpress', + 'KEYCODE_SHIFT_LEFT', + 'KEYCODE_MOVE_END', + ], + ['input', 'keyevent', '67'], + ['input', 'text', 'a%sb\\&c'], + ]); + }); + + it('only clears the field for an empty string', async () => { + await backend.typeText(''); + + expect(inputCalls()).toStrictEqual([ + ['input', 'keyevent', 'KEYCODE_MOVE_HOME'], + [ + 'input', + 'keyevent', + '--longpress', + 'KEYCODE_SHIFT_LEFT', + 'KEYCODE_MOVE_END', + ], + ['input', 'keyevent', '67'], + ]); + }); +}); + +describe('AdbBackend.dismissKeyboard', () => { + let backend: AdbBackend; + + // `grep -m1 mInputShown` prints only this line. + const imeLine = (shown: boolean): string => + ` mInputShown=${String(shown)}\n`; + + const isStateRead = (args?: string[]): boolean => + args?.some((arg) => arg.includes('input_method')) ?? false; + + // Polls in the 2 s window after a key: at 0, 100, …, 2000 ms. + const POLL_READS = 21; + + const keyEvents = (): string[] => + mockExecStrict.mock.calls + .map(([, args]) => args ?? []) + .filter((args) => args.includes('keyevent')) + .map((args) => args[args.length - 1]); + + const dumpCount = (): number => + mockExecStrict.mock.calls.filter(([, args]) => isStateRead(args)).length; + + /** + * Fake device: the keyboard is shown until one of `hidesOn` keycodes is + * sent, then it hides after `lag` more `dumpsys` reads. + * + * @param options - The fake's behaviour. + * @param options.shown - Whether the keyboard is shown at the start. + * @param options.hidesOn - The keycodes that hide it. + * @param options.lag - Reads that still see it shown after the key. + * @param options.dump - Overrides the dump text. + */ + const fakeDevice = ({ + shown, + hidesOn = ['111', '4'], + lag = 0, + dump, + }: { + shown: boolean; + hidesOn?: string[]; + lag?: number; + dump?: string; + }): void => { + let isShown = shown; + let reads = -1; + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (isStateRead(args)) { + if (reads >= 0) { + reads -= 1; + if (reads < 0) { + isShown = false; + } + } + return dump ?? imeLine(isShown); + } + const key = args?.[args.length - 1] ?? ''; + if (args?.includes('keyevent') && hidesOn.includes(key) && isShown) { + reads = lag; + } + return ''; + }); + }; + + beforeEach(() => { + vi.clearAllMocks(); + backend = new AdbBackend('emulator-5554'); + }); + + it('sends no key when the keyboard is not shown', async () => { + fakeDevice({ shown: false }); + + await backend.dismissKeyboard(); + + expect(keyEvents()).toStrictEqual([]); + expect(dumpCount()).toBe(1); + }); + + it('reads only the mInputShown line of the input method dump', async () => { + fakeDevice({ shown: false }); + + await backend.dismissKeyboard(); + + expect(mockExecStrict).toHaveBeenCalledWith('adb', [ + '-s', + 'emulator-5554', + 'shell', + 'dumpsys input_method | grep -m1 mInputShown || true', + ]); + }); + + it('sends ESCAPE and checks that the keyboard hid', async () => { + fakeDevice({ shown: true }); + + await backend.dismissKeyboard(); + + expect(keyEvents()).toStrictEqual(['111']); + expect(dumpCount()).toBe(2); + }); + + it('polls until the keyboard hides after ESCAPE', async () => { + fakeDevice({ shown: true, lag: 3 }); + + await withoutRetryDelay(async () => backend.dismissKeyboard()); + + expect(keyEvents()).toStrictEqual(['111']); + expect(dumpCount()).toBe(5); + }); + + it('sends BACK once when ESCAPE does not hide the keyboard', async () => { + fakeDevice({ shown: true, hidesOn: ['4'] }); + + await withoutRetryDelay(async () => backend.dismissKeyboard()); + + expect(keyEvents()).toStrictEqual(['111', '4']); + // The first read, the polls after ESCAPE, the read right before BACK and + // the first poll after BACK. + expect(dumpCount()).toBe(1 + POLL_READS + 1 + 1); + }); + + it('waits up to 2 s for ESCAPE to hide the keyboard', async () => { + fakeDevice({ shown: true, lag: POLL_READS - 1 }); + + await withoutRetryDelay(async () => backend.dismissKeyboard()); + + expect(keyEvents()).toStrictEqual(['111']); + }); + + it('skips BACK when the read right before it sees the keyboard hidden', async () => { + fakeDevice({ shown: true, hidesOn: ['111'], lag: POLL_READS }); + + await withoutRetryDelay(async () => backend.dismissKeyboard()); + + expect(keyEvents()).toStrictEqual(['111']); + expect(dumpCount()).toBe(1 + POLL_READS + 1); + }); + + it('throws when the keyboard stays shown after ESCAPE and BACK', async () => { + fakeDevice({ shown: true, hidesOn: [] }); + + await expect( + withoutRetryDelay(async () => backend.dismissKeyboard()), + ).rejects.toThrow('Keyboard still shown after ESCAPE and BACK'); + expect(keyEvents()).toStrictEqual(['111', '4']); + }); + + it('sends only ESCAPE when the keyboard state cannot be read', async () => { + // grep prints nothing, for example when the service can't be dumped. + fakeDevice({ shown: true, dump: '' }); + + await backend.dismissKeyboard(); + + expect(keyEvents()).toStrictEqual(['111']); + expect(dumpCount()).toBe(1); + }); +}); + describe('AdbBackend.screenshot', () => { let backend: AdbBackend; diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index 578f865..ab2dda0 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -111,6 +111,20 @@ const HELPER_RETRY_MIN_REMAINING_MS = 1_000; // A failed capture suggests a busy screen, where each dump can waste ~11 s. const HELPER_FIRST_FALLBACK_DUMP_ATTEMPTS = 1; +const KEYCODE_ESCAPE = '111'; + +const KEYCODE_BACK = '4'; + +// How long the keyboard may take to hide after each key. +const KEYBOARD_HIDE_TIMEOUT_MS = 2_000; + +const KEYBOARD_POLL_INTERVAL_MS = 100; + +// Reads only the `mInputShown` line: the full dump is ~1 MB. `|| true` keeps a +// missing line from failing the command, so that state reads as unknown. +const KEYBOARD_STATE_COMMAND = + 'dumpsys input_method | grep -m1 mInputShown || true'; + /** * - `helper-first`: helper, then dump on non-trust failures (default with APK). * - `auto`: quick dump, then helper; skip later quick dumps once the helper wins. @@ -345,7 +359,8 @@ export class AdbBackend implements DeviceBackend { } async typeText(text: string): Promise { - // Android keyevent 29+shift = Ctrl+A (select all), 67 = DEL + // Select the text (Shift + MOVE_END from the start, then Ctrl+A), then + // delete it with DEL (67). await this.#adb(['shell', 'input', 'keyevent', 'KEYCODE_MOVE_HOME']); await this.#adb([ 'shell', @@ -355,7 +370,24 @@ export class AdbBackend implements DeviceBackend { 'KEYCODE_SHIFT_LEFT', 'KEYCODE_MOVE_END', ]); + // In a React Native field (API 36) the Shift selection selects nothing, + // so DEL removed one character. `keycombination` (newer Android only) is + // best effort: without it the clear is no worse than before. + await exec('adb', [ + '-s', + this.#serial, + 'shell', + 'input', + 'keycombination', + 'KEYCODE_CTRL_LEFT', + 'KEYCODE_A', + ]); await this.#adb(['shell', 'input', 'keyevent', '67']); + // `input text` with no argument throws on the device, and the field is + // already empty. + if (text.length === 0) { + return; + } // Android input text requires escaping spaces and special chars const escaped = text.replace(/ /gu, '%s').replace(/[&|;<>]/gu, '\\$&'); await this.#adb(['shell', 'input', 'text', escaped]); @@ -822,8 +854,82 @@ export class AdbBackend implements DeviceBackend { await this.#adb(['shell', 'input', 'keyevent', keyMap[button]]); } + /** + * Hides the software keyboard, and does nothing when no keyboard is shown. + * Sends ESCAPE and polls for up to {@link KEYBOARD_HIDE_TIMEOUT_MS} until the + * keyboard hides. If it is still shown, reads the state once more and sends + * BACK only when that read still sees the keyboard (while the keyboard is + * shown, BACK only hides it), then checks again. + * + * Remaining risk: if the keyboard hides between that last read and BACK + * (one adb round trip, tens of ms), BACK reaches the app and can navigate + * back. This needs ESCAPE to take more than the poll window to hide the + * keyboard and then finish within that gap. + * + * When the state can't be read (`mInputShown` is missing), this behaves + * like 0.8.0: it sends ESCAPE only and does not check the result, because + * BACK sent blind could navigate. + * + * @throws When the keyboard is still shown after ESCAPE and BACK. + */ async dismissKeyboard(): Promise { - await this.#adb(['shell', 'input', 'keyevent', '111']); + const shown = await this.#isKeyboardShown(); + if (shown === false) { + return; + } + await this.#adb(['shell', 'input', 'keyevent', KEYCODE_ESCAPE]); + if (shown === undefined) { + return; + } + if (await this.#waitForKeyboardHidden()) { + return; + } + // Keep the gap between the last read and BACK as small as possible. + if ((await this.#isKeyboardShown()) !== true) { + return; + } + await this.#adb(['shell', 'input', 'keyevent', KEYCODE_BACK]); + if (await this.#waitForKeyboardHidden()) { + return; + } + throw new Error( + 'Keyboard still shown after ESCAPE and BACK. ' + + 'Use device_snapshot to inspect the current UI hierarchy.', + ); + } + + /** + * Whether the input method (software keyboard) is shown, from the + * `mInputShown` line of `dumpsys input_method`. + * + * @returns The state, or `undefined` when there is no `mInputShown` line. + */ + async #isKeyboardShown(): Promise { + const line = await this.#adb(['shell', KEYBOARD_STATE_COMMAND]); + const match = line.match(/\bmInputShown=(true|false)\b/u); + return match ? match[1] === 'true' : undefined; + } + + /** + * Polls until the keyboard is hidden. A state that can't be read counts as + * hidden, so BACK is never sent blind. + * + * @returns True once it is hidden; false when it is still shown after + * {@link KEYBOARD_HIDE_TIMEOUT_MS}. + */ + async #waitForKeyboardHidden(): Promise { + const deadline = Date.now() + KEYBOARD_HIDE_TIMEOUT_MS; + for (;;) { + if ((await this.#isKeyboardShown()) !== true) { + return true; + } + if (Date.now() + KEYBOARD_POLL_INTERVAL_MS > deadline) { + return false; + } + await new Promise((resolve) => { + setTimeout(resolve, KEYBOARD_POLL_INTERVAL_MS); + }); + } } async dismissAlert(accept: boolean): Promise { diff --git a/src/tools/dismiss-keyboard.ts b/src/tools/dismiss-keyboard.ts index a39fe10..fa11ae1 100644 --- a/src/tools/dismiss-keyboard.ts +++ b/src/tools/dismiss-keyboard.ts @@ -15,7 +15,9 @@ export function registerDismissKeyboardTool( 'Hide the on-screen keyboard. Call after typing to reveal elements ' + 'that may be obscured by the keyboard. On iOS this presses Return ' + 'when a keyboard is shown (which can submit a single-field form) ' + - 'and does nothing otherwise.', + 'and does nothing otherwise. On Android it does nothing when no ' + + 'keyboard is shown, and fails when the keyboard is still shown ' + + 'after ESCAPE and BACK.', inputSchema: {}, }, async () => { diff --git a/src/tools/type-text.ts b/src/tools/type-text.ts index 9e87e0d..b8fc1ee 100644 --- a/src/tools/type-text.ts +++ b/src/tools/type-text.ts @@ -15,7 +15,8 @@ export function registerTypeTool( description: 'Type text into the currently focused input field. ' + 'Tap an input element first to focus it, then call this. ' + - 'The field is cleared before typing on all backends.', + 'The field is cleared before typing on all backends. On Android ' + + '(adb), an empty string clears the field.', inputSchema: { text: z.string().describe('Text to type'), },