import { execFile } from 'node:child_process'; import fs, { unlink } from 'node:fs'; import * as fsActual from 'node:fs' with { rstest: 'importActual' }; import type { ExecutorContext } from '@midscene/core'; import * as CoreUtils from '@midscene/core/utils'; import * as ImgUtils from '@midscene/shared/img'; import * as sharedImgActual from '@midscene/shared/img' with { rstest: 'importActual', }; import { type Mock, type Mocked, afterEach, beforeEach, describe, expect, it, rs, } from '@rstest/core'; import { ADB } from 'appium-adb'; import { AndroidDevice, escapeForShell } from '../../src/device'; import { ScrcpyFreshFrameUnavailableError } from '../../src/scrcpy-manager'; // Mock the entire appium-adb module const createMockAdb = () => ({ executable: { path: '/mock/platform-tools/adb', defaultArgs: [], }, EXEC_OUTPUT_FORMAT: { FULL: 'full', STDOUT: 'stdout', }, startUri: rs.fn(), startApp: rs.fn(), activateApp: rs.fn(), shell: rs.fn(), getScreenDensity: rs.fn(), takeScreenshot: rs.fn(), pull: rs.fn(), inputText: rs.fn(), keyevent: rs.fn(), clearTextField: rs.fn(), hideKeyboard: rs.fn(), push: rs.fn(), isSoftKeyboardPresent: rs.fn().mockResolvedValue(false), getApiLevel: rs.fn().mockResolvedValue(35), }); let mockAdbInstance: ReturnType; const createValidPngBuffer = (size = 64) => { const signature = Buffer.from([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, ]); const iend = Buffer.from([ 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, ]); return Buffer.concat([ signature, Buffer.alloc(Math.max(size - signature.length - iend.length, 0)), iend, ]); }; const fallbackPngDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAGCAIAAABxZ0isAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEUlEQVR4nGMQqbiDFTEMpAQAorNDgTX/VEoAAAAASUVORK5CYII='; const fallbackPngBuffer = Buffer.from( fallbackPngDataUrl.split(',')[1], 'base64', ); const buildExpectedClearInputCommand = (displayId?: number) => { const displayArgument = displayId === undefined ? '' : ` -d ${displayId}`; const deletionKeyCodes = Array.from({ length: 100 }, () => '67 112').join( ' ', ); return `input${displayArgument} keyevent 123 ${deletionKeyCodes}`; }; rs.mock('appium-adb', () => { const MockADB = rs.fn(() => { if (!mockAdbInstance) { mockAdbInstance = createMockAdb(); } return mockAdbInstance; }); Object.assign(MockADB, { createADB: rs.fn(async () => { if (!mockAdbInstance) { mockAdbInstance = createMockAdb(); } return mockAdbInstance; }), }); return { ADB: MockADB, getSdkRootFromEnv: rs.fn(() => undefined), }; }); rs.mock('@midscene/core/utils'); rs.mock('node:child_process', () => ({ execFile: rs.fn( ( _file: unknown, _args: unknown, _options: unknown, callback?: (error: Error | null) => void, ) => { callback?.(null); return { unref: rs.fn() }; }, ), })); rs.mock('@midscene/shared/img', () => { const original = sharedImgActual; const validateScreenshotBuffer = original.validateScreenshotBuffer ?? (( screenshotBuffer: Buffer | undefined, options: { label: string; minBufferSize?: number; }, ) => { const bufferSize = screenshotBuffer?.length ?? 0; if (!screenshotBuffer || bufferSize === 0) { throw new Error( `${options.label} validation failed: buffer size ${bufferSize} bytes`, ); } if (!original.isValidImageBuffer(screenshotBuffer)) { throw new Error(`${options.label} buffer has invalid image format`); } if (options.minBufferSize && bufferSize < options.minBufferSize) { throw new Error( `${options.label} validation failed: buffer size ${bufferSize} bytes (minimum: ${options.minBufferSize})`, ); } }); return { ...original, createImgBase64ByFormat: rs.fn(), resizeAndConvertImgBuffer: rs.fn(), validateScreenshotBuffer, }; }); rs.mock('node:fs', () => { const original = fsActual as unknown as { default: Record; }; const unlink = rs.fn( (_path: unknown, callback: (error: NodeJS.ErrnoException | null) => void) => callback(null), ); return { ...original, unlink, promises: { readFile: rs.fn(), }, default: { ...original.default, unlink, promises: { readFile: rs.fn(), }, }, }; }); describe('AndroidDevice', () => { let device: AndroidDevice; // Mapped mock types erase generic return types such as runInImeContext. // Retain the real ADB signatures alongside the mock controls. let mockAdb: Mocked & ADB; beforeEach(() => { rs.mocked(execFile).mockClear(); // Ensure mockAdbInstance is available if (!mockAdbInstance) { mockAdbInstance = createMockAdb(); } // Create a new mock instance for each test mockAdb = new ADB() as Mocked & ADB; mockAdb.executable.defaultArgs = []; // Disable buffer size validation for tests to allow small mock buffers // Disable scrcpy to avoid shell calls during normalizeScrcpyConfig device = new AndroidDevice('test-device', { minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); // Manually assign the mocked adb instance rs.spyOn(device, 'getAdb').mockResolvedValue(mockAdb); }); afterEach(() => { rs.restoreAllMocks(); rs.unstubAllEnvs(); }); it('should throw error if deviceId is not provided', () => { expect(() => new AndroidDevice(undefined as any)).toThrow( 'deviceId is required for AndroidDevice', ); }); it('should include the ADB executable in proxied command errors', async () => { mockAdb.shell.mockRejectedValue(new Error('protocol fault')); const adbProxy = (device as any).createAdbProxy(mockAdb); await expect(adbProxy.shell(['wm', 'size'])).rejects.toThrow( 'ADB error with device test-device when calling shell (ADB executable: /mock/platform-tools/adb)', ); }); it('pushes yadb from unpacked Electron resources', async () => { const unpackedYadbPath = String.raw`C:\Program Files\Midscene Studio\resources\app.asar.unpacked\node_modules\@midscene\android\bin\yadb`; rs.spyOn(device as any, 'resolveYadbBinPath').mockReturnValue( unpackedYadbPath, ); await device.ensureYadb(); await device.ensureYadb(); expect(mockAdb.push).toHaveBeenCalledTimes(1); expect(mockAdb.push).toHaveBeenCalledWith( unpackedYadbPath, '/data/local/tmp', ); }); describe('UI tree', () => { const hierarchy = (children: string) => ` ${children} `; const mockUiautomatorHierarchy = (xml: string) => { mockAdb.shell.mockImplementation(async (command) => { if (String(command) === 'cat /sdcard/midscene_window_dump.xml') { return xml; } return ''; }); }; it('returns a snapshot from the accessibility hierarchy', async () => { mockUiautomatorHierarchy( hierarchy( '', ), ); mockAdb.getScreenDensity.mockResolvedValue(320); const beforeCapture = Date.now(); const snapshot = await device.getUITree(); expect(snapshot).toMatchObject({ platform: 'android', root: { type: 'android.widget.FrameLayout', bounds: { left: 0, top: 0, width: 200, height: 400 }, children: [ { type: 'android.widget.Button', attrs: { 'resource-id': 'submit', text: 'Submit' }, bounds: { left: 10, top: 20, width: 80, height: 30 }, }, ], }, }); expect(snapshot.capturedAt).toBeGreaterThanOrEqual(beforeCapture); expect(mockAdb.getScreenDensity).toHaveBeenCalledOnce(); expect(mockAdb.shell).toHaveBeenCalledWith( 'cat /sdcard/midscene_window_dump.xml', expect.objectContaining({ timeout: 5_000 }), ); }); it('retries uiautomator within one total dump budget', async () => { mockAdb.getScreenDensity.mockResolvedValue(160); mockAdb.shell.mockImplementation(async (command) => { const value = String(command); if (value.startsWith('uiautomator dump')) { throw new Error('layout dump failed'); } return ''; }); await expect(device.getUITree()).rejects.toThrow('layout dump failed'); const dumpCommands = mockAdb.shell.mock.calls .map(([command]) => String(command)) .filter((command) => command.startsWith('uiautomator dump')); expect(dumpCommands).toEqual([ 'uiautomator dump --compressed /sdcard/midscene_window_dump.xml', 'uiautomator dump --compressed /sdcard/midscene_window_dump.xml', 'uiautomator dump --compressed /sdcard/midscene_window_dump.xml', ]); }); it('rejects a tree captured from a different logical display', async () => { const secondaryDisplayDevice = new AndroidDevice('test-device', { displayId: 2, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); rs.spyOn(secondaryDisplayDevice, 'getAdb').mockResolvedValue(mockAdb); mockAdb.shell.mockImplementation(async (command) => { const value = String(command); if (value === 'cat /sdcard/midscene_window_dump.xml') { return ` `; } if (value === 'dumpsys window displays') { return `Display: mDisplayId=2 (organized) mCurrentFocus=Window{abc u0 com.expected.display/.MainActivity} mFocusedApp=ActivityRecord{def u0 com.expected.display/.MainActivity}`; } if (value === 'dumpsys window windows') { return `Window #0 Window{abc u0 com.wrong.display/.MainActivity}: mDisplayId=3 rootTaskId=10 mOwnerUid=10001 package=com.wrong.display`; } return ''; }); await expect(secondaryDisplayDevice.getUITree()).rejects.toThrow( /UI tree display mismatch.*displayId=2.*com\.expected\.display.*com\.wrong\.display/, ); }); it('accepts a system overlay owned by the configured display', async () => { const secondaryDisplayDevice = new AndroidDevice('test-device', { displayId: 2, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); rs.spyOn(secondaryDisplayDevice, 'getAdb').mockResolvedValue(mockAdb); rs.spyOn(secondaryDisplayDevice, 'size').mockResolvedValue({ width: 400, height: 800, }); mockAdb.shell.mockImplementation(async (command) => { const value = String(command); if (value === 'cat /sdcard/midscene_window_dump.xml') { return ` `; } if (value === 'dumpsys window displays') { return `Display: mDisplayId=2 (organized) mCurrentFocus=Window{abc u0 com.expected.display/.MainActivity}`; } if (value === 'dumpsys window windows') { return `Window #0 Window{abc u0 StatusBar}: mDisplayId=2 rootTaskId=1 mOwnerUid=10002 package=com.android.systemui`; } return ''; }); await expect(secondaryDisplayDevice.getUITree()).resolves.toMatchObject({ root: { attrs: { package: 'com.android.systemui' } }, }); }); it('rejects a tree whose display ownership cannot be verified', async () => { const secondaryDisplayDevice = new AndroidDevice('test-device', { displayId: 2, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); rs.spyOn(secondaryDisplayDevice, 'getAdb').mockResolvedValue(mockAdb); mockAdb.shell.mockImplementation(async (command) => { const value = String(command); if (value === 'cat /sdcard/midscene_window_dump.xml') { return ` `; } if (value === 'dumpsys window displays') { return `Display: mDisplayId=2 (organized) mCurrentFocus=Window{abc u0 com.expected.display/.MainActivity}`; } if (value === 'dumpsys window windows') return ''; return ''; }); await expect(secondaryDisplayDevice.getUITree()).rejects.toThrow( /no window display ownership found.*com\.unknown\.display/, ); }); it('records capturedAt immediately after reading the hierarchy', async () => { const secondaryDisplayDevice = new AndroidDevice('test-device', { displayId: 2, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); rs.spyOn(secondaryDisplayDevice, 'getAdb').mockResolvedValue(mockAdb); rs.spyOn(secondaryDisplayDevice, 'size').mockResolvedValue({ width: 400, height: 800, }); let currentTime = 10; rs.spyOn(Date, 'now').mockImplementation(() => currentTime); mockAdb.shell.mockImplementation(async (command) => { const value = String(command); if (value === 'cat /sdcard/midscene_window_dump.xml') { currentTime = 100; return ` `; } if (value === 'dumpsys window displays') { currentTime = 200; return `Display: mDisplayId=2 (organized) mCurrentFocus=Window{abc u0 com.expected.display/.MainActivity}`; } if (value === 'dumpsys window windows') { return `Window #0 Window{abc u0 com.expected.display/.MainActivity}: mDisplayId=2 rootTaskId=10 mOwnerUid=10001 package=com.expected.display`; } return ''; }); await expect(secondaryDisplayDevice.getUITree()).resolves.toMatchObject({ capturedAt: 100, }); }); it('rejects a tree whose bounds exceed the configured display', async () => { const secondaryDisplayDevice = new AndroidDevice('test-device', { displayId: 2, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); rs.spyOn(secondaryDisplayDevice, 'getAdb').mockResolvedValue(mockAdb); rs.spyOn(secondaryDisplayDevice, 'size').mockResolvedValue({ width: 400, height: 800, }); mockAdb.shell.mockImplementation(async (command) => { const value = String(command); if (value === 'cat /sdcard/midscene_window_dump.xml') { return ` `; } if (value === 'dumpsys window displays') { return `Display: mDisplayId=2 (organized) mCurrentFocus=Window{abc u0 com.expected.display/.MainActivity}`; } if (value === 'dumpsys window windows') { return `Window #0 Window{abc u0 com.expected.display/.MainActivity}: mDisplayId=2 rootTaskId=10 mOwnerUid=10001 package=com.expected.display`; } return ''; }); await expect(secondaryDisplayDevice.getUITree()).rejects.toThrow( /UI tree bounds exceed displayId=2.*600x800.*400x800/, ); }); }); describe('launch', () => { it('should start URI for http/https links', async () => { const uri = 'https://example.com'; await device.launch(uri); expect(mockAdb.startUri).toHaveBeenCalledWith(uri); }); it('should start app for package/activity format', async () => { const uri = 'com.android.settings/.Settings'; await device.launch(uri); expect(mockAdb.startApp).toHaveBeenCalledWith({ pkg: 'com.android.settings', activity: '.Settings', }); }); it('should activate app for package name format', async () => { const uri = 'com.android.settings'; await device.launch(uri); expect(mockAdb.activateApp).toHaveBeenCalledWith(uri); }); }); describe('terminate', () => { it('should force-stop app by package name', async () => { mockAdb.shell.mockResolvedValue(''); await device.terminate('com.android.settings'); expect(mockAdb.shell).toHaveBeenCalledWith( 'am force-stop com.android.settings', ); }); it('should use package part when uri contains slash', async () => { mockAdb.shell.mockResolvedValue(''); await device.terminate('com.android.settings/.Settings'); expect(mockAdb.shell).toHaveBeenCalledWith( 'am force-stop com.android.settings', ); }); it('should throw on terminate failure', async () => { mockAdb.shell.mockRejectedValue(new Error('force-stop failed')); await expect(device.terminate('com.bad.app')).rejects.toThrow( 'Failed to terminate com.bad.app', ); }); }); // Cross-platform contract for https://github.com/web-infra-dev/midscene/issues/2313: // Launch/Terminate on every mobile platform must expose the SAME `uri` field. // The shared tool-generator already rejects non-object schemas, but a future // author could still rename the field and silently break CLI ergonomics. it('lets custom action readiness replace the extra scroll settling delay', async () => { const scroll = rs .spyOn(device as any, 'scrollDownRaw') .mockResolvedValue(undefined); const delay = rs.spyOn(CoreUtils, 'sleep').mockResolvedValue(undefined); try { const action = device .actionSpace() .find((item) => item.name === 'Scroll')!; await action.call( { direction: 'down', scrollType: 'singleAction', distance: 100 }, { task: {}, skipDefaultWait: true } as ExecutorContext, ); expect(scroll).toHaveBeenCalledOnce(); expect(delay).not.toHaveBeenCalledWith(500); await action.call( { direction: 'down', scrollType: 'singleAction', distance: 100 }, { task: {} } as ExecutorContext, ); expect(delay).toHaveBeenCalledWith(500); } finally { scroll.mockRestore(); delay.mockRestore(); } }); describe('actionSpace platform actions', () => { it('includes RunAdbShell by default', () => { const actionNames = device.actionSpace().map((action) => action.name); expect(actionNames).toContain('RunAdbShell'); }); it('hides RunAdbShell when exposeRunAdbShellAction is false', () => { const deviceWithoutAdbShell = new AndroidDevice('test-device', { exposeRunAdbShellAction: false, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); const actions = deviceWithoutAdbShell.actionSpace(); expect(actions.map((action) => action.name)).not.toContain('RunAdbShell'); expect(actions.map((action) => action.interfaceAlias)).not.toContain( 'runAdbShell', ); expect(actions.map((action) => action.name)).toContain('Launch'); expect(actions.map((action) => action.name)).toContain('Terminate'); }); it('routes representative built-in action surfaces through one scrcpy barrier', async () => { const markActionBarrier = rs.fn().mockResolvedValue(undefined); (device as any).scrcpyAdapter = { markActionBarrier }; rs.spyOn(device as any, 'tapPoint').mockResolvedValue(undefined); rs.spyOn(device as any, 'homeRaw').mockResolvedValue(undefined); rs.spyOn(device as any, 'pullDownRaw').mockResolvedValue(undefined); rs.spyOn(device as any, 'launchRaw').mockResolvedValue(device); const cases: Array<[string, () => Promise]> = [ [ 'input primitive', () => device.inputPrimitives.pointer.tap({ x: 10, y: 20 }), ], ['direct API', () => device.home()], [ 'pull action', () => device .actionSpace() .find((action) => action.name === 'PullGesture')! .call({ direction: 'down' }), ], [ 'platform action', () => device .actionSpace() .find((action) => action.name === 'Launch')! .call({ uri: 'com.android.settings' }), ], ]; for (const [surface, invoke] of cases) { markActionBarrier.mockClear(); await invoke(); expect(markActionBarrier, surface).toHaveBeenCalledOnce(); } }); it('moves one scrcpy barrier for a composite action', async () => { const markActionBarrier = rs.fn().mockResolvedValue(undefined); const dragPoint = rs .spyOn(device as any, 'dragPoint') .mockResolvedValue(undefined); (device as any).scrcpyAdapter = { markActionBarrier }; await device.inputPrimitives.touch.swipe( { x: 100, y: 800 }, { x: 100, y: 200 }, { repeat: 3 }, ); expect(dragPoint).toHaveBeenCalledTimes(3); expect(markActionBarrier).toHaveBeenCalledOnce(); }); it('moves one scrcpy barrier when a composite action partially fails', async () => { const actionError = new Error('second swipe failed'); const markActionBarrier = rs.fn().mockResolvedValue(undefined); rs.spyOn(device as any, 'dragPoint') .mockResolvedValueOnce(undefined) .mockRejectedValueOnce(actionError); (device as any).scrcpyAdapter = { markActionBarrier }; await expect( device.inputPrimitives.touch.swipe( { x: 100, y: 800 }, { x: 100, y: 200 }, { repeat: 2 }, ), ).rejects.toBe(actionError); expect(markActionBarrier).toHaveBeenCalledOnce(); }); }); describe('Launch/Terminate action schema contract', () => { it('Launch paramSchema is a ZodObject with a `uri: ZodString` field', () => { const launchAction = device .actionSpace() .find((action) => action.name === 'Launch'); expect(launchAction).toBeDefined(); expect((launchAction!.paramSchema as any)?._def?.typeName).toBe( 'ZodObject', ); expect( (launchAction!.paramSchema as any).shape?.uri?._def?.typeName, ).toBe('ZodString'); }); it('Terminate paramSchema is a ZodObject with a `uri: ZodString` field', () => { const terminateAction = device .actionSpace() .find((action) => action.name === 'Terminate'); expect(terminateAction).toBeDefined(); expect((terminateAction!.paramSchema as any)?._def?.typeName).toBe( 'ZodObject', ); expect( (terminateAction!.paramSchema as any).shape?.uri?._def?.typeName, ).toBe('ZodString'); }); }); describe('RunAdbShell action output', () => { it('should expose non-empty stdout as planning feedback', async () => { const command = 'settings get system screen_brightness'; mockAdb.shell.mockResolvedValue({ stdout: '0\n', stderr: '', } as any); const runAdbShellAction = device .actionSpace() .find((action) => action.name === 'RunAdbShell'); const taskContext: { task: { planningFeedback?: string } } = { task: {}, }; await runAdbShellAction!.call( { command }, taskContext as ExecutorContext, ); expect(taskContext.task).toEqual({ planningFeedback: `Command: ${command} Stdout: 0 `, }); }); it('should omit planning feedback for empty stdout', async () => { const command = 'cmd clipboard set-text "Tracking #: 5K672F4C"'; mockAdb.shell.mockResolvedValue({ stdout: '', stderr: '', } as any); const runAdbShellAction = device .actionSpace() .find((action) => action.name === 'RunAdbShell'); const taskContext: { task: { planningFeedback?: string } } = { task: {}, }; await runAdbShellAction!.call( { command }, taskContext as ExecutorContext, ); expect(taskContext.task).toEqual({}); }); it('should pass full stdout into planning feedback (core handles truncation)', async () => { const command = 'cmd test'; mockAdb.shell.mockResolvedValue({ stdout: 'o'.repeat(240), stderr: '', } as any); const runAdbShellAction = device .actionSpace() .find((action) => action.name === 'RunAdbShell'); const taskContext: { task: { planningFeedback?: string } } = { task: {}, }; await runAdbShellAction!.call( { command }, taskContext as ExecutorContext, ); expect(taskContext.task.planningFeedback).toContain('o'.repeat(240)); expect(taskContext.task.planningFeedback).not.toContain('truncated'); }); it('should return stdout without requiring executor context', async () => { const command = 'settings get system screen_brightness'; mockAdb.shell.mockResolvedValue({ stdout: '0\n', stderr: '', } as any); const runAdbShellAction = device .actionSpace() .find((action) => action.name === 'RunAdbShell'); await expect(runAdbShellAction!.call({ command })).resolves.toBe('0\n'); }); it('should pass timeout through the RunAdbShell action', async () => { const command = 'sleep 2'; mockAdb.shell.mockResolvedValue({ stdout: '', stderr: '', } as any); const runAdbShellAction = device .actionSpace() .find((action) => action.name === 'RunAdbShell'); await runAdbShellAction!.call({ command, timeout: 2_000 }); expect(mockAdb.shell).toHaveBeenCalledWith(command, { timeout: 2_000, outputFormat: 'full', }); }); it('should throw when adb shell exits zero with stderr output', async () => { const command = 'cmd clipboard set-text "Tracking #: 5K672F4C"'; mockAdb.shell.mockResolvedValue({ stdout: '', stderr: 'No shell command implementation.', } as any); const runAdbShellAction = device .actionSpace() .find((action) => action.name === 'RunAdbShell'); await expect( runAdbShellAction!.call({ command }, {} as ExecutorContext), ).rejects.toThrow( /RunAdbShell command returned stderr\.[\s\S]*No shell command implementation\./, ); expect(mockAdb.shell).toHaveBeenCalledWith(command, { outputFormat: 'full', }); }); }); describe('size', () => { it('should calculate screen size', async () => { rs.spyOn(device as any, 'getScreenSize').mockResolvedValue({ override: '1080x1920', physical: '1080x1920', orientation: 0, }); mockAdb.getScreenDensity.mockResolvedValue(320); const size1 = await device.size(); const size2 = await device.size(); expect(size1).toEqual({ width: 540, height: 960 }); expect(size2).toEqual(size1); // Caching is removed, so it should be called twice expect(rs.spyOn(device as any, 'getScreenSize')).toHaveBeenCalledTimes(2); }); }); describe('adjustCoordinates derives scale from size()', () => { const mockPhysicalInfo = (w: number, h: number) => { rs.spyOn(device as any, 'getDevicePhysicalInfo').mockResolvedValue({ physicalWidth: w, physicalHeight: h, dpr: 2, orientation: 0, isCurrentOrientation: true, }); }; it('should derive scale from size() and physical dimensions', async () => { // Physical 1080x1920, logical 540x960 → scale 0.5 // coordinates: 200/0.5=400, 400/0.5=800 mockPhysicalInfo(1080, 1920); rs.spyOn(device, 'size').mockResolvedValue({ width: 540, height: 960, }); const adjusted = await (device as any).adjustCoordinates(200, 400); expect(adjusted).toEqual({ x: 400, y: 800 }); }); it('should work correctly when size() is overridden with custom dimensions', async () => { // Physical 1080x1920, user overrides size() → width=360 // scaleX = 360/1080 = 1/3, so 100/(1/3)=300, 200/(1/3)=600 mockPhysicalInfo(1080, 1920); rs.spyOn(device, 'size').mockResolvedValue({ width: 360, height: 640, }); const adjusted = await (device as any).adjustCoordinates(100, 200); expect(adjusted).toEqual({ x: 300, y: 600 }); }); it('pointer tap primitive should use correct physical coordinates when size() is overridden', async () => { // Physical 1080x1920, logical 540x960 → scale 0.5 // click at (100, 200) → physical (200, 400) mockPhysicalInfo(1080, 1920); rs.spyOn(device, 'size').mockResolvedValue({ width: 540, height: 960, }); await device.inputPrimitives.pointer.tap({ x: 100, y: 200 }); expect(mockAdb.shell).toHaveBeenCalledWith( 'input swipe 200 400 200 400 150', ); }); it('should handle 1:1 scale (no scaling)', async () => { mockPhysicalInfo(1080, 1920); rs.spyOn(device, 'size').mockResolvedValue({ width: 1080, height: 1920, }); const adjusted = await (device as any).adjustCoordinates(100, 200); expect(adjusted).toEqual({ x: 100, y: 200 }); }); it('should handle non-proportional X/Y scales', async () => { // Physical 1080x1920, logical 540x640 (non-proportional) // scaleX = 540/1080 = 0.5, scaleY = 640/1920 = 1/3 // x: 100/0.5=200, y: 100/(1/3)=300 mockPhysicalInfo(1080, 1920); rs.spyOn(device, 'size').mockResolvedValue({ width: 540, height: 640, }); const adjusted = await (device as any).adjustCoordinates(100, 100); expect(adjusted).toEqual({ x: 200, y: 300 }); }); it('should cache scale and not call size() repeatedly', async () => { mockPhysicalInfo(1080, 1920); const sizeSpy = rs.spyOn(device, 'size').mockResolvedValue({ width: 540, height: 960, }); await (device as any).adjustCoordinates(100, 100); await (device as any).adjustCoordinates(200, 200); await (device as any).adjustCoordinates(300, 300); // size() should only be called once due to caching expect(sizeSpy).toHaveBeenCalledTimes(1); }); }); describe('getScreenSize', () => { it('reuses the display dump for physical display lookup', async () => { const displayDevice = new AndroidDevice('test-device', { displayId: 1, usePhysicalDisplayIdForDisplayLookup: true, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); rs.spyOn(displayDevice, 'getAdb').mockResolvedValue(mockAdb); mockAdb.shell.mockImplementation(async (command: string | string[]) => { if (command === 'dumpsys display') { return `mDisplayId=1 mBaseDisplayInfo=DisplayInfo{"Inner", real 1080 x 1920, rotation 0, density 420, uniqueId "local:123"}`; } return ''; }); await expect(displayDevice.getScreenSize()).resolves.toMatchObject({ override: '1080x1920', physical: '1080x1920', orientation: 0, }); await expect(displayDevice.getDisplayDensity()).resolves.toBe(420); const displayDumpCalls = mockAdb.shell.mock.calls.filter( ([command]) => command === 'dumpsys display', ); expect(displayDumpCalls).toHaveLength(2); expect(mockAdb.shell).not.toHaveBeenCalledWith( 'dumpsys SurfaceFlinger --display-id 1', ); }); it('should use fallback to get orientation when primary method fails', async () => { mockAdb.shell.mockImplementation(async (command: string | string[]) => { if (Array.isArray(command) && command.join(' ') === 'wm size') { return 'Physical size: 1080x1920'; } if (command.includes('dumpsys input')) { return 'some other output'; // No match for SurfaceOrientation } if (command.includes('dumpsys display')) { return 'mCurrentOrientation=1'; } return ''; }); const screenSize = await (device as any).getScreenSize(); expect(screenSize.orientation).toBe(1); expect(mockAdb.shell).toHaveBeenCalledWith( 'dumpsys input | grep SurfaceOrientation', ); expect(mockAdb.shell).toHaveBeenCalledWith( 'dumpsys display | grep mCurrentOrientation', ); }); it('should get orientation with primary method and not use fallback', async () => { mockAdb.shell.mockImplementation(async (command: string | string[]) => { if (Array.isArray(command) && command.join(' ') === 'wm size') { return 'Physical size: 1080x1920'; } if (command.includes('dumpsys input')) { return 'SurfaceOrientation: 2'; } if (command.includes('dumpsys display')) { // This should not be called return 'mCurrentOrientation=1'; } return ''; }); const screenSize = await (device as any).getScreenSize(); expect(screenSize.orientation).toBe(2); expect(mockAdb.shell).toHaveBeenCalledWith( 'dumpsys input | grep SurfaceOrientation', ); expect(mockAdb.shell).not.toHaveBeenCalledWith( 'dumpsys display | grep mCurrentOrientation', ); }); }); describe('screenshotBase64', () => { beforeEach(() => { rs.spyOn(device, 'size').mockResolvedValue({ width: 1080, height: 1920, }); rs.spyOn(ImgUtils, 'resizeAndConvertImgBuffer').mockImplementation( async (format, buffer) => ({ buffer, format, }), ); }); it('should take screenshot successfully with takeScreenshot', async () => { const mockBuffer = createValidPngBuffer(); mockAdb.takeScreenshot.mockResolvedValue(mockBuffer); // Mock createImgBase64ByFormat rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( `data:image/png;base64,${mockBuffer.toString('base64')}`, ); const result = await device.screenshotBase64(); expect(result).toContain(mockBuffer.toString('base64')); expect(mockAdb.shell).not.toHaveBeenCalled(); }); it('should use yadb directly when screenshotStrategy is always-yadb', async () => { const alwaysYadbDevice = new AndroidDevice('test-device', { minScreenshotBufferSize: 0, screenshotStrategy: 'always-yadb', scrcpyConfig: { enabled: true, maxSize: 4 }, }); rs.spyOn(alwaysYadbDevice, 'getAdb').mockResolvedValue(mockAdb); const forceScreenshotSpy = rs .spyOn(alwaysYadbDevice, 'forceScreenshot') .mockResolvedValue(); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue('/tmp/yadb.png'); (fs.promises.readFile as Mock).mockResolvedValue(fallbackPngBuffer); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( fallbackPngDataUrl, ); const result = await alwaysYadbDevice.screenshotBase64(); expect(forceScreenshotSpy).toHaveBeenCalledWith( expect.stringMatching(/^\/data\/local\/tmp\/ms_[a-z0-9]+\.png$/), ); expect(mockAdb.takeScreenshot).not.toHaveBeenCalled(); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringMatching(/screencap/), ); expect(mockAdb.pull).toHaveBeenCalledWith( expect.stringMatching(/^\/data\/local\/tmp\/ms_[a-z0-9]+\.png$/), '/tmp/yadb.png', ); await expect(sharedImgActual.imageInfoOfBase64(result)).resolves.toEqual({ width: 4, height: 3, }); }); it('should reject always-yadb screenshots on a non-default display', async () => { const nonDefaultDisplayDevice = new AndroidDevice('test-device', { displayId: 1, minScreenshotBufferSize: 0, screenshotStrategy: 'always-yadb', scrcpyConfig: { enabled: false }, }); rs.spyOn(nonDefaultDisplayDevice, 'getAdb').mockResolvedValue(mockAdb); const forceScreenshotSpy = rs .spyOn(nonDefaultDisplayDevice, 'forceScreenshot') .mockResolvedValue(); const mockBuffer = createValidPngBuffer(); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue( '/tmp/yadb-non-default-display.png', ); (fs.promises.readFile as Mock).mockResolvedValue(mockBuffer); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( `data:image/png;base64,${mockBuffer.toString('base64')}`, ); await expect(nonDefaultDisplayDevice.screenshotBase64()).rejects.toThrow( "screenshotStrategy 'always-yadb' cannot target non-default displayId=1", ); expect(forceScreenshotSpy).not.toHaveBeenCalled(); }); it('should preserve remote ADB arguments when cleaning up screenshots', async () => { Object.assign(mockAdb.executable, { defaultArgs: ['-H', '192.168.1.10', '-P', '5038'], }); const alwaysYadbDevice = new AndroidDevice('test-device', { minScreenshotBufferSize: 0, screenshotStrategy: 'always-yadb', scrcpyConfig: { enabled: false }, }); rs.spyOn(alwaysYadbDevice, 'getAdb').mockResolvedValue(mockAdb); rs.spyOn(alwaysYadbDevice, 'forceScreenshot').mockResolvedValue(); const mockBuffer = createValidPngBuffer(); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue('/tmp/yadb-remote.png'); (fs.promises.readFile as Mock).mockResolvedValue(mockBuffer); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( `data:image/png;base64,${mockBuffer.toString('base64')}`, ); await alwaysYadbDevice.screenshotBase64(); expect(execFile).toHaveBeenCalledWith( '/mock/platform-tools/adb', [ '-H', '192.168.1.10', '-P', '5038', '-s', 'test-device', 'shell', expect.stringMatching(/^rm \/data\/local\/tmp\/ms_[a-z0-9]+\.png$/), ], { timeout: 3000 }, expect.any(Function), ); }); it('should use yadb directly when configured through the environment', async () => { rs.stubEnv('MIDSCENE_ANDROID_SCREENSHOT_STRATEGY', 'always-yadb'); const forceScreenshotSpy = rs .spyOn(device, 'forceScreenshot') .mockResolvedValue(); const mockBuffer = createValidPngBuffer(); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue('/tmp/yadb-env.png'); (fs.promises.readFile as Mock).mockResolvedValue(mockBuffer); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( `data:image/png;base64,${mockBuffer.toString('base64')}`, ); await device.screenshotBase64(); expect(forceScreenshotSpy).toHaveBeenCalledOnce(); expect(mockAdb.takeScreenshot).not.toHaveBeenCalled(); expect(mockAdb.pull).toHaveBeenCalledWith( expect.stringMatching(/^\/data\/local\/tmp\/ms_[a-z0-9]+\.png$/), '/tmp/yadb-env.png', ); }); it('should prefer an explicit auto strategy over the environment', async () => { rs.stubEnv('MIDSCENE_ANDROID_SCREENSHOT_STRATEGY', 'always-yadb'); const explicitAutoDevice = new AndroidDevice('test-device', { minScreenshotBufferSize: 0, screenshotStrategy: 'auto', scrcpyConfig: { enabled: false }, }); rs.spyOn(explicitAutoDevice, 'getAdb').mockResolvedValue(mockAdb); const forceScreenshotSpy = rs.spyOn( explicitAutoDevice, 'forceScreenshot', ); const mockBuffer = createValidPngBuffer(); mockAdb.takeScreenshot.mockResolvedValue(mockBuffer); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( `data:image/png;base64,${mockBuffer.toString('base64')}`, ); await explicitAutoDevice.screenshotBase64(); expect(mockAdb.takeScreenshot).toHaveBeenCalledOnce(); expect(forceScreenshotSpy).not.toHaveBeenCalled(); }); it('should report the scrcpy failure cause without assuming network backlog', async () => { const adapter = (device as any).getScrcpyAdapter(); rs.spyOn(adapter, 'isEnabled').mockReturnValue(true); rs.spyOn(adapter, 'screenshotBase64').mockRejectedValue( new Error('stream recovery failed'), ); rs.spyOn(device as any, 'getDevicePhysicalInfo').mockResolvedValue({ physicalWidth: 1080, physicalHeight: 1920, dpr: 1, orientation: 0, }); const mockBuffer = createValidPngBuffer(); mockAdb.takeScreenshot.mockResolvedValue(mockBuffer); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( `data:image/png;base64,${mockBuffer.toString('base64')}`, ); const warn = rs.spyOn(console, 'warn').mockImplementation(() => {}); await expect(device.screenshotBase64()).resolves.toContain( mockBuffer.toString('base64'), ); expect(warn).toHaveBeenCalledWith( '[Midscene]', expect.stringContaining('stream recovery failed'), ); expect(warn).not.toHaveBeenCalledWith( '[Midscene]', expect.stringContaining('--scrcpy-video-bit-rate'), ); }); it('should constrain an ADB fallback after a scrcpy freshness failure', async () => { const fallbackDevice = new AndroidDevice('test-device', { minScreenshotBufferSize: 0, scrcpyConfig: { enabled: true, maxSize: 4 }, }); rs.spyOn(fallbackDevice, 'getAdb').mockResolvedValue(mockAdb); const adapter = (fallbackDevice as any).getScrcpyAdapter(); rs.spyOn(adapter, 'screenshotBase64').mockRejectedValue( new ScrcpyFreshFrameUnavailableError('stale stream closed', { failureKind: 'freshness-target', timeoutMs: 300, videoBitRate: 100_000_000, }), ); const deviceInfo = { physicalWidth: 8, physicalHeight: 6, dpr: 1, orientation: 0, }; rs.spyOn( fallbackDevice as any, 'getDevicePhysicalInfo', ).mockResolvedValue(deviceInfo); mockAdb.takeScreenshot.mockResolvedValue(fallbackPngBuffer); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( fallbackPngDataUrl, ); rs.spyOn(console, 'warn').mockImplementation(() => {}); const result = await fallbackDevice.screenshotBase64(); await expect(sharedImgActual.imageInfoOfBase64(result)).resolves.toEqual({ width: 4, height: 3, }); }); it('reports structured scrcpy freshness diagnostics before using ADB fallback', async () => { const adapter = (device as any).getScrcpyAdapter(); rs.spyOn(adapter, 'isEnabled').mockReturnValue(true); rs.spyOn(adapter, 'screenshotBase64').mockRejectedValue( new ScrcpyFreshFrameUnavailableError('stale stream closed', { failureKind: 'freshness-target', timeoutMs: 300, videoBitRate: 4_000_000, }), ); const deviceInfo = { physicalWidth: 1080, physicalHeight: 1920, dpr: 1, orientation: 0, }; rs.spyOn(device as any, 'getDevicePhysicalInfo').mockResolvedValue( deviceInfo, ); const mockBuffer = createValidPngBuffer(); mockAdb.takeScreenshot.mockResolvedValue(mockBuffer); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( `data:image/png;base64,${mockBuffer.toString('base64')}`, ); const warn = rs.spyOn(console, 'warn').mockImplementation(() => {}); await expect(device.screenshotBase64()).resolves.toContain( mockBuffer.toString('base64'), ); expect(warn).toHaveBeenCalledWith( '[Midscene]', expect.stringContaining( 'does not by itself identify bandwidth or the configured video bitrate as the cause', ), ); expect(warn).not.toHaveBeenCalledWith( '[Midscene]', expect.stringContaining('--scrcpy-video-bit-rate'), ); expect(warn).toHaveBeenCalledTimes(1); }); it('should fall back to screencap and pull if takeScreenshot fails', async () => { const fallbackDevice = new AndroidDevice('test-device', { minScreenshotBufferSize: 0, scrcpyConfig: { enabled: true, maxSize: 4 }, }); rs.spyOn(fallbackDevice, 'getAdb').mockResolvedValue(mockAdb); rs.spyOn( (fallbackDevice as any).getScrcpyAdapter(), 'isEnabled', ).mockReturnValue(false); mockAdb.takeScreenshot.mockRejectedValue(new Error('fail')); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue('/tmp/test.png'); (fs.promises.readFile as Mock).mockResolvedValue(fallbackPngBuffer); // Mock createImgBase64ByFormat rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( fallbackPngDataUrl, ); const result = await fallbackDevice.screenshotBase64(); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringMatching(/screencap -p/), ); expect(mockAdb.pull).toHaveBeenCalled(); expect(fs.promises.readFile).toHaveBeenCalled(); await expect(sharedImgActual.imageInfoOfBase64(result)).resolves.toEqual({ width: 4, height: 3, }); // rm is now executed via execFile (fire-and-forget), not adb.shell }); it('should accept valid fallback screenshots larger than 1KB by default', async () => { const defaultDevice = new AndroidDevice('test-device', { scrcpyConfig: { enabled: false }, }); rs.spyOn(defaultDevice, 'getAdb').mockResolvedValue(mockAdb); mockAdb.takeScreenshot.mockRejectedValue(new Error('fail')); const smallValidPng = createValidPngBuffer(7 * 1024); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue('/tmp/small.png'); (fs.promises.readFile as Mock).mockResolvedValue(smallValidPng); rs.spyOn(ImgUtils, 'createImgBase64ByFormat').mockReturnValue( `data:image/png;base64,${smallValidPng.toString('base64')}`, ); const result = await defaultDevice.screenshotBase64(); expect(result).toContain(smallValidPng.toString('base64')); expect(mockAdb.pull).toHaveBeenCalled(); }); it('should reject valid fallback screenshots smaller than 1KB by default', async () => { const defaultDevice = new AndroidDevice('test-device', { scrcpyConfig: { enabled: false }, }); rs.spyOn(defaultDevice, 'getAdb').mockResolvedValue(mockAdb); mockAdb.takeScreenshot.mockRejectedValue(new Error('fail')); const tinyValidPng = createValidPngBuffer(512); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue('/tmp/tiny.png'); (fs.promises.readFile as Mock).mockResolvedValue(tinyValidPng); await expect(defaultDevice.screenshotBase64()).rejects.toThrow( 'Fallback screenshot validation failed: buffer size 512 bytes (minimum: 1024)', ); expect(unlink).toHaveBeenCalledWith( '/tmp/tiny.png', expect.any(Function), ); }); it('should reject empty fallback screenshots', async () => { mockAdb.takeScreenshot.mockRejectedValue(new Error('fail')); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue('/tmp/empty.png'); (fs.promises.readFile as Mock).mockResolvedValue(Buffer.alloc(0)); await expect(device.screenshotBase64()).rejects.toThrow( 'Fallback screenshot validation failed: buffer size 0 bytes', ); }); it('should enforce minScreenshotBufferSize when explicitly configured', async () => { const minSizeDevice = new AndroidDevice('test-device', { minScreenshotBufferSize: 10 * 1024, scrcpyConfig: { enabled: false }, }); rs.spyOn(minSizeDevice, 'getAdb').mockResolvedValue(mockAdb); mockAdb.takeScreenshot.mockRejectedValue(new Error('fail')); const smallValidPng = createValidPngBuffer(7 * 1024); rs.spyOn(CoreUtils, 'getTmpFile').mockReturnValue('/tmp/small.png'); (fs.promises.readFile as Mock).mockResolvedValue(smallValidPng); await expect(minSizeDevice.screenshotBase64()).rejects.toThrow( 'Fallback screenshot validation failed: buffer size 7168 bytes (minimum: 10240)', ); }); }); describe('mouse', () => { it('click should call shell with adjusted coordinates', async () => { rs.spyOn(device as any, 'adjustCoordinates').mockResolvedValue({ x: 200, y: 300, }); await device.inputPrimitives.pointer.tap({ x: 100, y: 150 }); expect(mockAdb.shell).toHaveBeenCalledWith( 'input swipe 200 300 200 300 150', ); }); it('drag should call shell with adjusted coordinates', async () => { const from = { x: 10, y: 20 }; const to = { x: 30, y: 40 }; rs.spyOn(device as any, 'adjustCoordinates') .mockResolvedValueOnce({ x: 20, y: 40 }) .mockResolvedValueOnce({ x: 60, y: 80 }); await device.inputPrimitives.pointer.dragAndDrop(from, to); expect(mockAdb.shell).toHaveBeenCalledWith( 'input swipe 20 40 60 80 1000', ); }); }); describe('keyboard', () => { // ========================================================================= // 1. escapeForShell — pure function tests (single-quote context) // In single quotes, only ' itself needs escaping; \n(0x0A) is converted // to literal \n for safe transport (yadb interprets it back to newline). // ========================================================================= describe('escapeForShell', () => { // Characters that need escaping in single-quote context it("' → '\\''", () => { expect(escapeForShell("it's")).toBe("it'\\''s"); }); it('\\n(0x0A) → literal \\n', () => { expect(escapeForShell('a\nb')).toBe('a\\nb'); }); // Characters that do NOT need escaping in single quotes it('should not escape backslash', () => { expect(escapeForShell('a\\b')).toBe('a\\b'); }); it('should not escape double quote', () => { expect(escapeForShell('a"b')).toBe('a"b'); }); it('should not escape backtick', () => { expect(escapeForShell('a`b')).toBe('a`b'); }); it('should not escape dollar sign', () => { expect(escapeForShell('a$b')).toBe('a$b'); }); it('should not escape space', () => { expect(escapeForShell('hello world')).toBe('hello world'); }); it('should not escape shell operators & | ; () <> ~ ^ *', () => { expect(escapeForShell('a&b|c;d(e)fh~i^j*k')).toBe( 'a&b|c;d(e)fh~i^j*k', ); }); it('should not escape ! @ # , . / \\ - _ : = + ? {} []', () => { expect(escapeForShell('!@#,./\\-_:=+?{}')).toBe('!@#,./\\-_:=+?{}'); expect(escapeForShell('a!b@c#d')).toBe('a!b@c#d'); }); it('should not escape %s %d %f', () => { expect(escapeForShell('100%s')).toBe('100%s'); }); it('should not escape non-ASCII characters', () => { expect(escapeForShell('你好café😀')).toBe('你好café😀'); }); // Combined: only ' is escaped, everything else passes through it("combined: it's $100\\each → it'\\''s $100\\each", () => { expect(escapeForShell("it's $100\\each")).toBe("it'\\''s $100\\each"); }); }); // ========================================================================= // 2. shouldUseYadbForText — routing decision // ========================================================================= describe('shouldUseYadbForText', () => { // --- Cases that should use yadb --- // Non-ASCII it('→ true: Chinese', () => { expect((device as any).shouldUseYadbForText('你好')).toBe(true); }); it('→ true: Japanese', () => { expect((device as any).shouldUseYadbForText('こんにちは')).toBe(true); }); it('→ true: Latin Unicode (ö)', () => { expect((device as any).shouldUseYadbForText('Schönberg')).toBe(true); }); it('→ true: emoji', () => { expect((device as any).shouldUseYadbForText('hello 😀')).toBe(true); }); // Format specifier %[a-zA-Z] it('→ true: %s', () => { expect((device as any).shouldUseYadbForText('Test%sString')).toBe(true); }); it('→ true: %d %f', () => { expect((device as any).shouldUseYadbForText('Value: %d')).toBe(true); expect((device as any).shouldUseYadbForText('Price: %f')).toBe(true); }); // Shell special characters [\\`$] it('→ true: backslash', () => { expect((device as any).shouldUseYadbForText('a\\b')).toBe(true); }); it('→ true: backtick', () => { expect((device as any).shouldUseYadbForText('a`b')).toBe(true); }); it('→ true: dollar sign', () => { expect((device as any).shouldUseYadbForText('$HOME')).toBe(true); }); // Contains both " and ' it('→ true: both quotes', () => { expect((device as any).shouldUseYadbForText('it\'s a "test"')).toBe( true, ); }); // Mixed triggers it('→ true: mixed (Latin Unicode + %s)', () => { expect( (device as any).shouldUseYadbForText('Schönberg,%sLiechtenstein'), ).toBe(true); }); // --- Cases that should use inputText --- it('→ false: pure ASCII letters/numbers', () => { expect((device as any).shouldUseYadbForText('Hello World 123')).toBe( false, ); }); it('→ false: empty string', () => { expect((device as any).shouldUseYadbForText('')).toBe(false); }); it('→ false: % not followed by letter', () => { expect((device as any).shouldUseYadbForText('100% complete')).toBe( false, ); }); it('→ false: only double quote (no single quote)', () => { expect((device as any).shouldUseYadbForText('say "hi"')).toBe(false); }); it('→ false: only single quote (no double quote)', () => { expect((device as any).shouldUseYadbForText("it's fine")).toBe(false); }); it('→ false: common punctuation ! @ # , . / - _ :', () => { expect((device as any).shouldUseYadbForText('test@email.com')).toBe( false, ); expect((device as any).shouldUseYadbForText('hello!')).toBe(false); expect((device as any).shouldUseYadbForText('a#b')).toBe(false); }); it('→ false: shell operators & | ; () <> ~ ^ *', () => { expect((device as any).shouldUseYadbForText('a&b')).toBe(false); expect((device as any).shouldUseYadbForText('a|b')).toBe(false); expect((device as any).shouldUseYadbForText('a;b')).toBe(false); expect((device as any).shouldUseYadbForText('a(b)c')).toBe(false); expect((device as any).shouldUseYadbForText('ac')).toBe(false); expect((device as any).shouldUseYadbForText('a*b')).toBe(false); }); }); // ========================================================================= // 3. keyboardType — integration tests // ========================================================================= describe('keyboardType', () => { beforeEach(() => { device.options = { imeStrategy: 'yadb-for-non-ascii', autoDismissKeyboard: false, }; rs.spyOn(device as any, 'ensureYadb').mockResolvedValue(undefined); const execYadbRaw = rs .spyOn(device as any, 'execYadbRaw') .mockResolvedValue(undefined); // Keyboard typing is a composite visual action and now calls the raw // yadb primitive to avoid creating a nested freshness barrier. Keep // the existing assertions pointed at that primitive's spy. (device as any).execYadb = execYadbRaw; mockAdb.isSoftKeyboardPresent.mockResolvedValue({ isKeyboardShown: false, canCloseKeyboard: true, }); }); it('should return early for empty string', async () => { await device.inputPrimitives.keyboard.typeText(''); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); expect((device as any).execYadb).not.toHaveBeenCalled(); }); // --------------------------------------------------------------- // 3a. input text path — pure ASCII goes through `input text` shell command // --------------------------------------------------------------- describe('input text path — appium-adb compatible characters', () => { it('pure ASCII: hello', async () => { await device.inputPrimitives.keyboard.typeText('hello'); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'hello'"); expect((device as any).execYadb).not.toHaveBeenCalled(); }); it('forces one input text call per Unicode character for sequential input', async () => { device.options = { ...device.options, inputStrategy: 'sequential', }; await device.inputPrimitives.keyboard.typeText('abc'); expect(mockAdb.shell.mock.calls).toEqual([ ["input text 'a'"], ["input text 'b'"], ["input text 'c'"], ]); }); it('rejects bulk input when the device has a positive keyboard delay', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', autoDismissKeyboard: false, keyboardTypeDelay: 10, }; const clearInputRaw = rs.spyOn(device as any, 'clearInputRaw'); await expect( device.inputPrimitives.keyboard.typeText('abc', { inputStrategy: 'bulk', target: { center: [10, 20] }, }), ).rejects.toThrow( 'inputStrategy "bulk" requires keyboardTypeDelay to be omitted or set to 0; use inputStrategy "sequential" for delayed input', ); expect(clearInputRaw).not.toHaveBeenCalled(); }); it('space: hello world', async () => { await device.inputPrimitives.keyboard.typeText('hello world'); expect(mockAdb.shell).toHaveBeenCalledWith( "input text 'hello world'", ); expect((device as any).execYadb).not.toHaveBeenCalled(); }); it('common punctuation: ! @ # ? = + , . / - _ :', async () => { const texts = [ 'hello!', 'user@host', 'a#b', 'a?b', 'a=b+c', 'a,b.c', 'a/b', 'a-b_c', 'a:b', ]; for (const text of texts) { mockAdb.shell.mockClear(); (device as any).execYadb.mockClear(); await device.inputPrimitives.keyboard.typeText(text); // shellEscapeArg wraps in single quotes expect(mockAdb.shell).toHaveBeenCalledWith(`input text '${text}'`); expect((device as any).execYadb).not.toHaveBeenCalled(); } }); it('brackets: {b} [b]', async () => { for (const text of ['a{b}c', 'a[b]c']) { mockAdb.shell.mockClear(); (device as any).execYadb.mockClear(); await device.inputPrimitives.keyboard.typeText(text); expect(mockAdb.shell).toHaveBeenCalledWith(`input text '${text}'`); expect((device as any).execYadb).not.toHaveBeenCalled(); } }); it('shell operators: & | ; () <> ~ ^ *', async () => { const texts = [ 'a&b', 'a|b', 'a;b', 'a(b)c', 'ac', 'a~b', 'a^b', 'a*b', ]; for (const text of texts) { mockAdb.shell.mockClear(); (device as any).execYadb.mockClear(); await device.inputPrimitives.keyboard.typeText(text); // These are now properly protected by single-quote wrapping expect(mockAdb.shell).toHaveBeenCalledWith(`input text '${text}'`); expect((device as any).execYadb).not.toHaveBeenCalled(); } }); it("single quote only: it's", async () => { await device.inputPrimitives.keyboard.typeText("it's"); // shellEscapeArg: 'it'\''s' — end quote, escaped quote, start quote expect(mockAdb.shell).toHaveBeenCalledWith("input text 'it'\\''s'"); expect((device as any).execYadb).not.toHaveBeenCalled(); }); it('double quote only: say"hi"', async () => { await device.inputPrimitives.keyboard.typeText('say"hi"'); expect(mockAdb.shell).toHaveBeenCalledWith(`input text 'say"hi"'`); expect((device as any).execYadb).not.toHaveBeenCalled(); }); it('percent not followed by letter: 100% done', async () => { await device.inputPrimitives.keyboard.typeText('100% done'); expect(mockAdb.shell).toHaveBeenCalledWith("input text '100% done'"); expect((device as any).execYadb).not.toHaveBeenCalled(); }); }); // --------------------------------------------------------------- // 3b. yadb path — characters incompatible with appium-adb (routed to yadb + escapeForShell) // --------------------------------------------------------------- describe('yadb path — appium-adb incompatible characters', () => { // 3b-1. Routing trigger + escapeForShell escaping // In single-quote context, only ' needs escaping; \, ", `, $ pass through describe('characters routed to yadb with escapeForShell applied', () => { it('\\ → execYadb unchanged (no escaping needed in single quotes)', async () => { await device.inputPrimitives.keyboard.typeText('a\\b'); expect((device as any).execYadb).toHaveBeenCalledWith('a\\b'); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); }); it('` → execYadb unchanged', async () => { await device.inputPrimitives.keyboard.typeText('a`b'); expect((device as any).execYadb).toHaveBeenCalledWith('a`b'); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); }); it('$ → execYadb unchanged', async () => { await device.inputPrimitives.keyboard.typeText('$HOME'); expect((device as any).execYadb).toHaveBeenCalledWith('$HOME'); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); }); it("both quotes → execYadb with ' escaped", async () => { await device.inputPrimitives.keyboard.typeText('it\'s a "test"'); expect((device as any).execYadb).toHaveBeenCalledWith( "it'\\''s a \"test\"", ); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); }); it('combined: $100\\each → unchanged (no escaping needed)', async () => { await device.inputPrimitives.keyboard.typeText('price: $100\\each'); expect((device as any).execYadb).toHaveBeenCalledWith( 'price: $100\\each', ); }); }); // 3b-2. Routing trigger but escapeForShell does not modify the text describe('characters NOT needing escapeForShell (pass through unchanged)', () => { it('non-ASCII: Chinese', async () => { await device.inputPrimitives.keyboard.typeText('你好'); expect((device as any).execYadb).toHaveBeenCalledWith('你好'); }); it('non-ASCII: Latin Unicode (ö)', async () => { await device.inputPrimitives.keyboard.typeText( 'Schönberg,Liechtenstein', ); expect((device as any).execYadb).toHaveBeenCalledWith( 'Schönberg,Liechtenstein', ); }); it('non-ASCII: emoji', async () => { await device.inputPrimitives.keyboard.typeText('hello 😀'); expect((device as any).execYadb).toHaveBeenCalledWith('hello 😀'); }); it('non-ASCII: Japanese', async () => { await device.inputPrimitives.keyboard.typeText('こんにちは'); expect((device as any).execYadb).toHaveBeenCalledWith('こんにちは'); }); it('format specifier: %s (yadb does not interpret %)', async () => { await device.inputPrimitives.keyboard.typeText('Test%sString'); expect((device as any).execYadb).toHaveBeenCalledWith( 'Test%sString', ); }); it('non-ASCII text preserves space, punctuation; single quote is escaped', async () => { await device.inputPrimitives.keyboard.typeText( "café's menu! @#&|;(){}[]<>~^*?=+,./:-_", ); // Non-ASCII triggers yadb; ' is escaped, everything else passes through expect((device as any).execYadb).toHaveBeenCalledWith( "café'\\''s menu! @#&|;(){}[]<>~^*?=+,./:-_", ); }); }); }); // --------------------------------------------------------------- // 3c. Newline handling // --------------------------------------------------------------- describe('newline handling', () => { // input text path: split('\n') + keyevent 66 via shell describe('input text path — split + keyevent 66', () => { it('middle newline: line1\\nline2', async () => { await device.inputPrimitives.keyboard.typeText('line1\nline2'); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'line1'"); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'line2'"); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 66'); }); it('multiple newlines: a\\nb\\nc', async () => { await device.inputPrimitives.keyboard.typeText('a\nb\nc'); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'a'"); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'b'"); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'c'"); // Two keyevents for two newlines const keyeventCalls = mockAdb.shell.mock.calls.filter( (call: any[]) => call[0] === 'input keyevent 66', ); expect(keyeventCalls).toHaveLength(2); }); it('trailing newline: hello\\n', async () => { await device.inputPrimitives.keyboard.typeText('hello\n'); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'hello'"); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 66'); }); it('leading newline: \\nhello', async () => { await device.inputPrimitives.keyboard.typeText('\nhello'); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'hello'"); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 66'); }); it('consecutive newlines: a\\n\\nb', async () => { await device.inputPrimitives.keyboard.typeText('a\n\nb'); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'a'"); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'b'"); // Two keyevents for two consecutive newlines const keyeventCalls = mockAdb.shell.mock.calls.filter( (call: any[]) => call[0] === 'input keyevent 66', ); expect(keyeventCalls).toHaveLength(2); }); it('just a newline: \\n', async () => { mockAdb.shell.mockClear(); await device.inputPrimitives.keyboard.typeText('\n'); // No `input text` call, just one keyevent const textCalls = mockAdb.shell.mock.calls.filter( (call: any[]) => typeof call[0] === 'string' && call[0].startsWith('input text'), ); expect(textCalls).toHaveLength(0); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 66'); }); it('no newline → no keyevent', async () => { mockAdb.shell.mockClear(); await device.inputPrimitives.keyboard.typeText('no-newline'); expect(mockAdb.shell).toHaveBeenCalledWith( "input text 'no-newline'", ); const keyeventCalls = mockAdb.shell.mock.calls.filter( (call: any[]) => call[0] === 'input keyevent 66', ); expect(keyeventCalls).toHaveLength(0); }); }); // yadb path: single execYadb call, \n(0x0A) converted to literal \n describe('yadb path — single execYadb call with \\n escaped', () => { it('non-ASCII with middle newline: 你好\\nworld', async () => { await device.inputPrimitives.keyboard.typeText('你好\nworld'); expect((device as any).execYadb).toHaveBeenCalledTimes(1); expect((device as any).execYadb).toHaveBeenCalledWith( '你好\\nworld', ); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); expect(mockAdb.shell).not.toHaveBeenCalledWith('input keyevent 66'); }); it('shell-special with middle newline: $10\\ntext', async () => { await device.inputPrimitives.keyboard.typeText( 'price: $10\nplain text', ); expect((device as any).execYadb).toHaveBeenCalledTimes(1); expect((device as any).execYadb).toHaveBeenCalledWith( 'price: $10\\nplain text', ); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); expect(mockAdb.shell).not.toHaveBeenCalledWith('input keyevent 66'); }); it('non-ASCII trailing newline: 你好\\n', async () => { await device.inputPrimitives.keyboard.typeText('你好\n'); expect((device as any).execYadb).toHaveBeenCalledTimes(1); expect((device as any).execYadb).toHaveBeenCalledWith('你好\\n'); expect(mockAdb.shell).not.toHaveBeenCalledWith('input keyevent 66'); }); it('always-yadb trailing newline: hello\\n', async () => { device.options = { imeStrategy: 'always-yadb', autoDismissKeyboard: false, }; await device.inputPrimitives.keyboard.typeText('hello\n'); expect((device as any).execYadb).toHaveBeenCalledWith('hello\\n'); expect(mockAdb.shell).not.toHaveBeenCalledWith('input keyevent 66'); }); it('always-yadb leading newline: \\nhello', async () => { device.options = { imeStrategy: 'always-yadb', autoDismissKeyboard: false, }; await device.inputPrimitives.keyboard.typeText('\nhello'); expect((device as any).execYadb).toHaveBeenCalledWith('\\nhello'); }); it('always-yadb consecutive newlines: a\\n\\nb', async () => { device.options = { imeStrategy: 'always-yadb', autoDismissKeyboard: false, }; await device.inputPrimitives.keyboard.typeText('a\n\nb'); expect((device as any).execYadb).toHaveBeenCalledWith('a\\n\\nb'); }); it('always-yadb just a newline: \\n', async () => { device.options = { imeStrategy: 'always-yadb', autoDismissKeyboard: false, }; await device.inputPrimitives.keyboard.typeText('\n'); expect((device as any).execYadb).toHaveBeenCalledWith('\\n'); expect(mockAdb.shell).not.toHaveBeenCalledWith('input keyevent 66'); }); }); }); // --------------------------------------------------------------- // 3d. IME strategy // --------------------------------------------------------------- describe('IME strategy', () => { it('always-yadb: pure ASCII also uses yadb', async () => { device.options = { imeStrategy: 'always-yadb', autoDismissKeyboard: false, }; await device.inputPrimitives.keyboard.typeText('hello world'); expect((device as any).execYadb).toHaveBeenCalledWith('hello world'); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); }); it('always-yadb: shell-special chars get escaped', async () => { device.options = { imeStrategy: 'always-yadb', autoDismissKeyboard: false, }; await device.inputPrimitives.keyboard.typeText( 'Schönberg,%sLiechtenstein', ); expect((device as any).execYadb).toHaveBeenCalledWith( 'Schönberg,%sLiechtenstein', ); }); it('yadb-for-non-ascii: pure ASCII uses input text', async () => { await device.inputPrimitives.keyboard.typeText('hello'); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'hello'"); expect((device as any).execYadb).not.toHaveBeenCalled(); }); it('yadb-for-non-ascii: non-ASCII uses yadb', async () => { await device.inputPrimitives.keyboard.typeText('你好,Schönberg'); expect((device as any).execYadb).toHaveBeenCalledWith( '你好,Schönberg', ); expect(mockAdb.shell).not.toHaveBeenCalledWith( expect.stringContaining('input text'), ); }); it('splits non-ASCII code points for explicit sequential input', async () => { await device.inputPrimitives.keyboard.typeText('你😀', { inputStrategy: 'sequential', }); expect((device as any).execYadb.mock.calls).toEqual([['你'], ['😀']]); }); it('preserves legacy yadb burst input when a delay is configured', async () => { device.options = { ...device.options, keyboardTypeDelay: 10, }; await device.inputPrimitives.keyboard.typeText('你😀'); expect((device as any).execYadb.mock.calls).toEqual([['你😀']]); }); }); }); it('type should hide keyboard when shown', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii' }; rs.spyOn(device as any, 'ensureYadb').mockResolvedValue(undefined); // First call returns true (keyboard shown), second returns false (keyboard hidden) mockAdb.isSoftKeyboardPresent .mockResolvedValueOnce({ isKeyboardShown: true, canCloseKeyboard: true, }) .mockResolvedValueOnce({ isKeyboardShown: false, canCloseKeyboard: true, }); await device.inputPrimitives.keyboard.typeText('hello'); expect(mockAdb.shell).toHaveBeenCalledWith("input text 'hello'"); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 111'); // ESC key }); it('press should call keyevent for mapped keys', async () => { await device.inputPrimitives.keyboard.keyboardPress('Enter'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 66'); }); describe('clearInput', () => { beforeEach(() => { mockAdb.shell.mockResolvedValue(''); }); it('should clear with cursor-independent keyevents without SDK branching', async () => { const ensureYadb = rs.spyOn(device as any, 'ensureYadb'); await device.clearInput(); expect(mockAdb.getApiLevel).not.toHaveBeenCalled(); expect(mockAdb.shell).toHaveBeenCalledTimes(1); expect(mockAdb.shell).toHaveBeenCalledWith( buildExpectedClearInputCommand(), ); expect(mockAdb.clearTextField).not.toHaveBeenCalled(); expect(ensureYadb).not.toHaveBeenCalled(); }); it('should clear before typing replacement text', async () => { const target = { center: [100, 200] as [number, number] } as any; rs.spyOn(device as any, 'tapPoint').mockResolvedValue(undefined); await device.inputPrimitives.keyboard.typeText('15', { target, replace: true, autoDismissKeyboard: false, }); expect(mockAdb.shell).toHaveBeenNthCalledWith( 1, buildExpectedClearInputCommand(), ); expect(mockAdb.shell).toHaveBeenNthCalledWith(2, "input text '15'"); }); it('should target the configured display for all clear keyevents', async () => { device.options = { displayId: 2 }; await device.clearInput(); expect(mockAdb.shell).toHaveBeenCalledTimes(1); expect(mockAdb.shell).toHaveBeenCalledWith( buildExpectedClearInputCommand(2), ); }); it('should preserve the explicit always-yadb clear strategy', async () => { device.options = { imeStrategy: 'always-yadb' }; const ensureYadb = rs .spyOn(device as any, 'ensureYadb') .mockResolvedValue(undefined); await device.clearInput(); expect(ensureYadb).toHaveBeenCalledTimes(1); expect(mockAdb.shell).toHaveBeenCalledWith( 'app_process -Djava.class.path=/data/local/tmp/yadb /data/local/tmp com.ysbing.yadb.Main -keyboardClear', ); expect(mockAdb.clearTextField).not.toHaveBeenCalled(); }); it('should use display-aware keyevents instead of yadb on a secondary display', async () => { device.options = { displayId: 2, imeStrategy: 'always-yadb' }; const ensureYadb = rs .spyOn(device as any, 'ensureYadb') .mockResolvedValue(undefined); await device.clearInput(); expect(mockAdb.shell).toHaveBeenCalledTimes(1); expect(mockAdb.shell).toHaveBeenCalledWith( buildExpectedClearInputCommand(2), ); expect(ensureYadb).not.toHaveBeenCalled(); }); it('should surface keyevent failures', async () => { mockAdb.shell.mockRejectedValueOnce(new Error('keyevent failed')); await expect(device.clearInput()).rejects.toThrow('keyevent failed'); }); }); it('press should reject key combinations before invoking ADB', async () => { await expect( device.inputPrimitives.keyboard.keyboardPress('Control+A'), ).rejects.toThrow( 'Android keyboardPress does not support key combinations: "Control+A"', ); expect(mockAdb.shell).not.toHaveBeenCalled(); }); it('press should handle case-insensitive key names', async () => { // Test lowercase keys await device.inputPrimitives.keyboard.keyboardPress('enter'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 66'); await device.inputPrimitives.keyboard.keyboardPress('escape'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 111'); await device.inputPrimitives.keyboard.keyboardPress('tab'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 61'); // Test uppercase keys (should still work) await device.inputPrimitives.keyboard.keyboardPress('ENTER'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 66'); await device.inputPrimitives.keyboard.keyboardPress('ESCAPE'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 111'); }); it('press should handle arrow key variations', async () => { // Test full arrow key names (lowercase) await device.inputPrimitives.keyboard.keyboardPress('arrowup'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 19'); await device.inputPrimitives.keyboard.keyboardPress('arrowdown'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 20'); // Test short arrow key names await device.inputPrimitives.keyboard.keyboardPress('up'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 19'); await device.inputPrimitives.keyboard.keyboardPress('down'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 20'); await device.inputPrimitives.keyboard.keyboardPress('left'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 21'); await device.inputPrimitives.keyboard.keyboardPress('right'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 22'); }); it('press should handle common key abbreviations', async () => { // Test 'esc' as abbreviation for 'Escape' await device.inputPrimitives.keyboard.keyboardPress('esc'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 111'); await device.inputPrimitives.keyboard.keyboardPress('ESC'); expect(mockAdb.shell).toHaveBeenCalledWith('input keyevent 111'); }); describe('autoDismissKeyboard option', () => { beforeEach(() => { rs.spyOn(device as any, 'ensureYadb').mockResolvedValue(undefined); }); it('should hide keyboard when autoDismissKeyboard is true (default)', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii' }; mockAdb.isSoftKeyboardPresent .mockResolvedValueOnce({ isKeyboardShown: true, canCloseKeyboard: true, }) // keyboard shown initially .mockResolvedValueOnce({ isKeyboardShown: false, canCloseKeyboard: true, }); // keyboard hidden after ESC await device.inputPrimitives.keyboard.typeText('hello'); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining("input text 'hello'"), ); expect(mockAdb.isSoftKeyboardPresent).toHaveBeenCalled(); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining('input keyevent 111'), ); // ESC key }); it('should hide keyboard when autoDismissKeyboard is explicitly true', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', autoDismissKeyboard: true, }; mockAdb.isSoftKeyboardPresent .mockResolvedValueOnce({ isKeyboardShown: true, canCloseKeyboard: true, }) // keyboard shown initially .mockResolvedValueOnce({ isKeyboardShown: false, canCloseKeyboard: true, }); // keyboard hidden after ESC await device.inputPrimitives.keyboard.typeText('hello'); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining("input text 'hello'"), ); expect(mockAdb.isSoftKeyboardPresent).toHaveBeenCalled(); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining('input keyevent 111'), ); // ESC key }); it('should not hide keyboard when autoDismissKeyboard is false', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', autoDismissKeyboard: false, }; mockAdb.isSoftKeyboardPresent.mockClear(); await device.inputPrimitives.keyboard.typeText('hello'); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining("input text 'hello'"), ); expect(mockAdb.isSoftKeyboardPresent).not.toHaveBeenCalled(); // No keyevent calls for keyboard dismissal const keyeventCalls = mockAdb.shell.mock.calls.filter( (c) => typeof c[0] === 'string' && c[0].includes('keyevent'), ); expect(keyeventCalls.length).toBe(0); }); it('should respect autoDismissKeyboard option passed to type method', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', autoDismissKeyboard: true, }; mockAdb.isSoftKeyboardPresent.mockClear(); // Override with false in method call await device.inputPrimitives.keyboard.typeText('hello', { autoDismissKeyboard: false, }); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining("input text 'hello'"), ); expect(mockAdb.isSoftKeyboardPresent).not.toHaveBeenCalled(); const keyeventCalls = mockAdb.shell.mock.calls.filter( (c) => typeof c[0] === 'string' && c[0].includes('keyevent'), ); expect(keyeventCalls.length).toBe(0); }); }); describe('keyboardDismissStrategy option', () => { beforeEach(() => { rs.spyOn(device as any, 'ensureYadb').mockResolvedValue(undefined); mockAdb.isSoftKeyboardPresent.mockClear(); }); // Helper: extract shell calls that contain 'keyevent' const getKeyeventShellCalls = () => mockAdb.shell.mock.calls.filter( (c) => typeof c[0] === 'string' && c[0].includes('keyevent'), ); it('should use esc-first strategy by default', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii' }; mockAdb.isSoftKeyboardPresent .mockResolvedValueOnce({ isKeyboardShown: true, canCloseKeyboard: true, }) // keyboard shown initially .mockResolvedValueOnce({ isKeyboardShown: false, canCloseKeyboard: true, }); // keyboard hidden after ESC await device.inputPrimitives.keyboard.typeText('hello'); const keyeventCalls = getKeyeventShellCalls(); expect(keyeventCalls[0][0]).toContain('111'); // ESC key first expect(keyeventCalls.length).toBe(1); }); it('should use back-first strategy when specified', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', keyboardDismissStrategy: 'back-first', }; mockAdb.isSoftKeyboardPresent .mockResolvedValueOnce({ isKeyboardShown: true, canCloseKeyboard: true, }) // keyboard shown initially .mockResolvedValueOnce({ isKeyboardShown: false, canCloseKeyboard: true, }); // keyboard hidden after BACK await device.inputPrimitives.keyboard.typeText('hello'); const keyeventCalls = getKeyeventShellCalls(); expect(keyeventCalls[0][0]).toContain('4'); // BACK key first expect(keyeventCalls.length).toBe(1); }); it('should try second key if first fails with esc-first strategy', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', keyboardDismissStrategy: 'esc-first', }; // Mock hideKeyboard to use a small timeout for faster test const originalHideKeyboard = (device as any).hideKeyboard.bind(device); rs.spyOn(device as any, 'hideKeyboard').mockImplementation( async (options) => { // Use 150ms timeout to ensure at least one check in the loop const result = await originalHideKeyboard(options, 150); return result; }, ); // Mock to simulate: keyboard shown -> ESC fails (stays shown) -> BACK succeeds (hidden) let callCount = 0; let currentKeyEvent = 0; // Track keyevent shell calls mockAdb.shell.mockImplementation(async (cmd: unknown) => { if (typeof cmd === 'string' && cmd.includes('keyevent')) { currentKeyEvent++; } return ''; }); mockAdb.isSoftKeyboardPresent.mockImplementation(() => { callCount++; // Initial check - keyboard is shown if (callCount === 1) { return Promise.resolve({ isKeyboardShown: true, canCloseKeyboard: true, }); } // If we're checking after the first key (ESC=111), keyboard stays shown if (currentKeyEvent === 1) { return Promise.resolve({ isKeyboardShown: true, canCloseKeyboard: true, }); } // After second key (BACK=4), keyboard is hidden if (currentKeyEvent === 2) { return Promise.resolve({ isKeyboardShown: false, canCloseKeyboard: true, }); } return Promise.resolve({ isKeyboardShown: true, canCloseKeyboard: true, }); }); await device.inputPrimitives.keyboard.typeText('hello'); const keyeventCalls = getKeyeventShellCalls(); expect(keyeventCalls[0][0]).toContain('111'); // ESC first expect(keyeventCalls[1][0]).toContain('4'); // BACK second expect(keyeventCalls.length).toBe(2); }); it('should try second key if first fails with back-first strategy', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', keyboardDismissStrategy: 'back-first', }; // Mock hideKeyboard to use a small timeout for faster test const originalHideKeyboard = (device as any).hideKeyboard.bind(device); rs.spyOn(device as any, 'hideKeyboard').mockImplementation( async (options) => { // Use 150ms timeout to ensure at least one check in the loop const result = await originalHideKeyboard(options, 150); return result; }, ); // Mock to simulate: keyboard shown -> BACK fails (stays shown) -> ESC succeeds (hidden) let callCount = 0; let currentKeyEvent = 0; // Track keyevent shell calls mockAdb.shell.mockImplementation(async (cmd: unknown) => { if (typeof cmd === 'string' && cmd.includes('keyevent')) { currentKeyEvent++; } return ''; }); mockAdb.isSoftKeyboardPresent.mockImplementation(() => { callCount++; // Initial check - keyboard is shown if (callCount === 1) { return Promise.resolve({ isKeyboardShown: true, canCloseKeyboard: true, }); } // If we're checking after the first key (BACK=4), keyboard stays shown if (currentKeyEvent === 1) { return Promise.resolve({ isKeyboardShown: true, canCloseKeyboard: true, }); } // After second key (ESC=111), keyboard is hidden if (currentKeyEvent === 2) { return Promise.resolve({ isKeyboardShown: false, canCloseKeyboard: true, }); } return Promise.resolve({ isKeyboardShown: true, canCloseKeyboard: true, }); }); await device.inputPrimitives.keyboard.typeText('hello'); const keyeventCalls = getKeyeventShellCalls(); expect(keyeventCalls[0][0]).toContain('4'); // BACK first expect(keyeventCalls[1][0]).toContain('111'); // ESC second expect(keyeventCalls.length).toBe(2); }); it('should respect keyboardDismissStrategy option passed to type method', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', keyboardDismissStrategy: 'esc-first', }; mockAdb.isSoftKeyboardPresent .mockResolvedValueOnce({ isKeyboardShown: true, canCloseKeyboard: true, }) // keyboard shown initially .mockResolvedValueOnce({ isKeyboardShown: false, canCloseKeyboard: true, }); // keyboard hidden after BACK // Override with back-first in method call await device.inputPrimitives.keyboard.typeText('hello', { // @ts-ignore: dist MobileInputPrimitives type has not caught up with AndroidDeviceInputOpt. keyboardDismissStrategy: 'back-first', }); const keyeventCalls = getKeyeventShellCalls(); expect(keyeventCalls[0][0]).toContain('4'); // BACK key first (overridden) expect(keyeventCalls.length).toBe(1); }); it('should log warning if both keys fail to hide keyboard', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii', keyboardDismissStrategy: 'esc-first', }; // Always return true (keyboard always shown) mockAdb.isSoftKeyboardPresent.mockResolvedValue({ isKeyboardShown: true, canCloseKeyboard: true, }); // Mock hideKeyboard to use a small timeout for faster test const originalHideKeyboard = (device as any).hideKeyboard.bind(device); rs.spyOn(device as any, 'hideKeyboard').mockImplementation( (options) => originalHideKeyboard(options, 100), // Use 100ms timeout instead of default 1000ms ); // Spy on console.warn to verify warning is logged const warnSpy = rs.spyOn(console, 'warn').mockImplementation(() => {}); // Should not throw error anymore await device.inputPrimitives.keyboard.typeText('hello', { autoDismissKeyboard: true, }); // Verify warning was logged expect(warnSpy).toHaveBeenCalledWith( '[Midscene]', 'Warning: Failed to hide the software keyboard after trying both ESC and BACK keys', ); // Clean up warnSpy.mockRestore(); }); it('should handle keyboard already hidden scenario', async () => { device.options = { imeStrategy: 'yadb-for-non-ascii' }; mockAdb.isSoftKeyboardPresent.mockResolvedValue({ isKeyboardShown: false, canCloseKeyboard: true, }); // keyboard already hidden await device.inputPrimitives.keyboard.typeText('hello'); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining("input text 'hello'"), ); expect(mockAdb.isSoftKeyboardPresent).toHaveBeenCalled(); const keyeventCalls = getKeyeventShellCalls(); expect(keyeventCalls.length).toBe(0); // No key events needed }); }); }); describe('scrolling', () => { beforeEach(() => { rs.spyOn(device, 'size').mockResolvedValue({ width: 1080, height: 1920, }); }); describe('untargeted scroll gesture coordinates', () => { beforeEach(() => { rs.spyOn(device as any, 'adjustCoordinates').mockImplementation( async (...args: unknown[]) => { const [x, y] = args as [number, number]; return { x, y }; }, ); rs.spyOn(console, 'warn').mockImplementation(() => {}); }); it.each([ ['scrollDown', 'input swipe 540 1632 540 288 1000'], ['scrollUp', 'input swipe 540 288 540 1632 1000'], ['scrollRight', 'input swipe 918 960 162 960 1000'], ['scrollLeft', 'input swipe 162 960 918 960 1000'], ] as const)( '%s keeps the default gesture within the central seventy percent of the screen', async (method, command) => { await device[method](); expect(mockAdb.shell).toHaveBeenCalledWith(command); expect(console.warn).not.toHaveBeenCalled(); }, ); it.each([ ['scrollUntilTop', 'input swipe 540 480 540 1920 100'], ['scrollUntilBottom', 'input swipe 540 1440 540 0 100'], ['scrollUntilLeft', 'input swipe 270 960 1080 960 100'], ['scrollUntilRight', 'input swipe 810 960 0 960 100'], ] as const)( '%s repeats the corrected boundary gesture', async (method, command) => { await device[method](); const swipes = mockAdb.shell.mock.calls.filter(([value]) => String(value).startsWith('input swipe'), ); expect(swipes).toHaveLength(10); for (const [value] of swipes) expect(value).toBe(command); }, ); it.each([ ['scrollDown', 100, 'input swipe 540 1440 540 1340 1000'], ['scrollUp', 100, 'input swipe 540 480 540 580 1000'], ['scrollRight', 100, 'input swipe 810 960 710 960 1000'], ['scrollLeft', 100, 'input swipe 270 960 370 960 1000'], ['scrollDown', 600, 'input swipe 540 1440 540 840 1000'], ['scrollUp', 600, 'input swipe 540 480 540 1080 1000'], ['scrollRight', 600, 'input swipe 810 960 210 960 1000'], ['scrollLeft', 600, 'input swipe 270 960 870 960 1000'], ] as const)( '%s preserves an explicit %ipx distance without clamping', async (method, distance, command) => { await device[method](distance); expect(mockAdb.shell).toHaveBeenCalledWith(command); expect(console.warn).not.toHaveBeenCalled(); }, ); it.each([ ['scrollDown', 'input swipe 960 918 960 162 1000'], ['scrollUp', 'input swipe 960 162 960 918 1000'], ['scrollRight', 'input swipe 1632 540 288 540 1000'], ['scrollLeft', 'input swipe 288 540 1632 540 1000'], ] as const)( '%s uses the current landscape dimensions for the default gesture', async (method, command) => { rs.spyOn(device, 'size').mockResolvedValue({ width: 1920, height: 1080, }); await device[method](); expect(mockAdb.shell).toHaveBeenCalledWith(command); expect(console.warn).not.toHaveBeenCalled(); }, ); }); it('scrollUp should call scroll with negative Y delta', async () => { const wheelSpy = rs .spyOn(device as any, 'scrollRaw') .mockResolvedValue(undefined); await device.scrollUp(100); expect(wheelSpy).toHaveBeenCalledWith(0, -100, undefined, true, 'up'); }); it('scrollDown should call scroll with positive Y delta', async () => { const wheelSpy = rs .spyOn(device as any, 'scrollRaw') .mockResolvedValue(undefined); await device.scrollDown(100); expect(wheelSpy).toHaveBeenCalledWith(0, 100, undefined, true, 'down'); }); describe('scroll input validation', () => { beforeEach(() => { rs.spyOn(console, 'warn').mockImplementation(() => {}); }); it('should throw error when both deltaX and deltaY are zero', async () => { await expect((device as any).scroll(0, 0)).rejects.toThrow( 'Scroll distance cannot be zero in both directions', ); }); it('should allow scrolling with non-zero deltaX and zero deltaY', async () => { rs.spyOn(device as any, 'adjustCoordinates') .mockResolvedValueOnce({ x: 270, y: 480 }) .mockResolvedValueOnce({ x: 170, y: 480 }); await expect((device as any).scroll(100, 0)).resolves.not.toThrow(); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining('input swipe'), ); expect(console.warn).not.toHaveBeenCalled(); }); it('should allow scrolling with zero deltaX and non-zero deltaY', async () => { rs.spyOn(device as any, 'adjustCoordinates') .mockResolvedValueOnce({ x: 270, y: 480 }) .mockResolvedValueOnce({ x: 270, y: 240 }); await expect((device as any).scroll(0, 100)).resolves.not.toThrow(); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining('input swipe'), ); expect(console.warn).not.toHaveBeenCalled(); }); it('should allow symmetric horizontal range from the same start position', async () => { const adjustCoordinatesSpy = rs .spyOn(device as any, 'adjustCoordinates') .mockImplementation(async (...args: unknown[]) => { const [x, y] = args as [number, number]; return { x, y }; }); await (device as any).scroll(9999999, 0); const rightSwipeCmd = (mockAdb.shell as Mock).mock.calls.at( -1, )?.[0] as string; await (device as any).scroll(-9999999, 0); const leftSwipeCmd = (mockAdb.shell as Mock).mock.calls.at( -1, )?.[0] as string; expect(rightSwipeCmd).toBe('input swipe 810 960 0 960 1000'); expect(leftSwipeCmd).toBe('input swipe 270 960 1080 960 1000'); expect(console.warn).not.toHaveBeenCalled(); adjustCoordinatesSpy.mockRestore(); }); it('should allow scrolling with both deltaX and deltaY non-zero', async () => { rs.spyOn(device as any, 'adjustCoordinates') .mockResolvedValueOnce({ x: 270, y: 480 }) .mockResolvedValueOnce({ x: 220, y: 405 }); await expect((device as any).scroll(50, 75)).resolves.not.toThrow(); expect(mockAdb.shell).toHaveBeenCalledWith( expect.stringContaining('input swipe'), ); expect(console.warn).not.toHaveBeenCalled(); }); it('should warn when explicit scrollDown distance exceeds the swipe boundary', async () => { rs.spyOn(device as any, 'adjustCoordinates').mockImplementation( async (...args: unknown[]) => { const [x, y] = args as [number, number]; return { x, y }; }, ); await device.scrollDown(9999999); expect(console.warn).toHaveBeenCalledWith( '[Midscene]', '[midscene] Android ADB swipe coordinates must stay within the screen bounds. The requested scroll distance (9999999px) exceeds the maximum single swipe distance (1440px) from the current start point, so it will be clamped. If you want to scroll to the bottom, use scrollToBottom instead.', ); }); it('should not warn for internal scrollToBottom clamp behavior', async () => { rs.spyOn(device as any, 'adjustCoordinates').mockImplementation( async (...args: unknown[]) => { const [x, y] = args as [number, number]; return { x, y }; }, ); await device.scrollUntilBottom(); expect(console.warn).not.toHaveBeenCalled(); }); }); describe('calculateScrollEndPoint', () => { it.each([ [{ x: 0, y: 200 }, -100, 0], [{ x: 1080, y: 200 }, 100, 0], [{ x: 200, y: 0 }, 0, -100], [{ x: 200, y: 1920 }, 0, 100], ])('rejects a scroll with no space from %j', (start, dx, dy) => { expect(() => (device as any).calculateScrollEndPoint(start, dx, dy, 1080, 1920), ).toThrow('No space'); }); it('should calculate end point for horizontal scroll within bounds', () => { const start = { x: 100, y: 200 }; const deltaX = 50; const deltaY = 0; const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); expect(result).toEqual({ x: 150, y: 200 }); }); it('should calculate end point for vertical scroll within bounds', () => { const start = { x: 100, y: 200 }; const deltaX = 0; const deltaY = 100; const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); expect(result).toEqual({ x: 100, y: 300 }); }); it('should limit scroll to screen boundaries - right edge', () => { const start = { x: 1000, y: 200 }; const deltaX = 200; // Would go beyond maxWidth const deltaY = 0; const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); expect(result).toEqual({ x: 1080, y: 200 }); // Capped at maxWidth }); it('should limit scroll to screen boundaries - left edge', () => { const start = { x: 100, y: 200 }; const deltaX = -200; // Would go beyond left edge const deltaY = 0; const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); expect(result).toEqual({ x: 0, y: 200 }); // Capped at 0 }); it('should limit scroll to screen boundaries - bottom edge', () => { const start = { x: 100, y: 1800 }; const deltaX = 0; const deltaY = 300; // Would go beyond maxHeight const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); expect(result).toEqual({ x: 100, y: 1920 }); // Capped at maxHeight }); it('should limit scroll to screen boundaries - top edge', () => { const start = { x: 100, y: 100 }; const deltaX = 0; const deltaY = -200; // Would go beyond top edge const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); expect(result).toEqual({ x: 100, y: 0 }); // Capped at 0 }); it('should maintain minimum scroll distance when available space is large', () => { const start = { x: 500, y: 500 }; const deltaX = 10; // Small delta, but current logic doesn't enforce minimum const deltaY = 0; const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); // Current implementation doesn't enforce minimum scroll distance // when delta is smaller than minimum, it just uses the delta expect(result.x).toBe(start.x + deltaX); expect(result.y).toBe(start.y); }); it('should respect available space when smaller than minimum scroll distance', () => { const start = { x: 1070, y: 200 }; // Very close to right edge const deltaX = 50; const deltaY = 0; const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); // Should only move to the edge, not enforce minimum distance expect(result).toEqual({ x: 1080, y: 200 }); }); it('should handle diagonal scrolling correctly', () => { const start = { x: 100, y: 100 }; const deltaX = 50; const deltaY = 75; const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); expect(result).toEqual({ x: 150, y: 175 }); }); it('should handle negative deltas correctly', () => { const start = { x: 500, y: 600 }; const deltaX = -100; const deltaY = -150; const maxWidth = 1080; const maxHeight = 1920; const result = (device as any).calculateScrollEndPoint( start, deltaX, deltaY, maxWidth, maxHeight, ); expect(result).toEqual({ x: 400, y: 450 }); }); it('rejects a stationary endpoint when both deltas are zero', () => { expect(() => (device as any).calculateScrollEndPoint( { x: 500, y: 600 }, 0, 0, 1080, 1920, ), ).toThrow('Scroll distance is too small'); }); it.each([ [{ x: 0, y: 0 }, -50], [{ x: 1080, y: 1920 }, 50], ])('rejects a diagonal scroll out of corner %j', (start, delta) => { expect(() => (device as any).calculateScrollEndPoint( start, delta, delta, 1080, 1920, ), ).toThrow('No space'); }); }); describe('scroll methods with calculateScrollEndPoint integration', () => { beforeEach(() => { rs.spyOn(device as any, 'dragPoint').mockResolvedValue(undefined); rs.spyOn(console, 'warn').mockImplementation(() => {}); }); it.each([Number.NaN, Number.POSITIVE_INFINITY, -1, 100000])( 'rejects invalid horizontal origin %s before a vertical drag', async (left) => { await expect( device.scrollDown(100, { left, top: 100 }), ).rejects.toThrow('origin'); expect((device as any).dragPoint).not.toHaveBeenCalled(); }, ); it('does not send a stationary drag when the origin is at the top edge', async () => { await expect( device.scrollDown(100, { left: 200, top: 0 }), ).rejects.toThrow('No space'); expect((device as any).dragPoint).not.toHaveBeenCalled(); }); it.each(['scrollUp', 'scrollDown', 'scrollLeft', 'scrollRight'] as const)( 'rejects a positive distance that rounds to zero in %s', async (method) => { for (const distance of [0.1, 0.49]) { await expect( device[method](distance, { left: 200, top: 200 }), ).rejects.toThrow('Scroll distance is too small'); } expect((device as any).dragPoint).not.toHaveBeenCalled(); }, ); it.each([ ['scrollUp', 200, 201], ['scrollDown', 200, 199], ['scrollLeft', 201, 200], ['scrollRight', 199, 200], ] as const)( 'preserves the smallest rounded movement in %s', async (method, x, y) => { await device[method](0.5, { left: 200, top: 200 }); expect((device as any).dragPoint).toHaveBeenCalledWith( { x: 200, y: 200 }, { x, y }, ); }, ); it('scrollDown with startPoint should use calculateScrollEndPoint', async () => { const startPoint = { left: 100, top: 200 }; const scrollDistance = 300; const calculateScrollEndPointSpy = rs.spyOn( device as any, 'calculateScrollEndPoint', ); await device.scrollDown(scrollDistance, startPoint); expect(calculateScrollEndPointSpy).toHaveBeenCalledWith( { x: 100, y: 200 }, 0, -scrollDistance, 1080, 1920, // height from mocked size() ); }); it('scrollUp with startPoint should use calculateScrollEndPoint', async () => { const startPoint = { left: 100, top: 200 }; const scrollDistance = 300; const calculateScrollEndPointSpy = rs.spyOn( device as any, 'calculateScrollEndPoint', ); await device.scrollUp(scrollDistance, startPoint); expect(calculateScrollEndPointSpy).toHaveBeenCalledWith( { x: 100, y: 200 }, 0, scrollDistance, 1080, 1920, // height from mocked size() ); }); it('scrollLeft with startPoint should use calculateScrollEndPoint', async () => { const startPoint = { left: 100, top: 200 }; const scrollDistance = 150; const calculateScrollEndPointSpy = rs.spyOn( device as any, 'calculateScrollEndPoint', ); await device.scrollLeft(scrollDistance, startPoint); expect(calculateScrollEndPointSpy).toHaveBeenCalledWith( { x: 100, y: 200 }, scrollDistance, 0, 1080, // width from mocked size() 1920, ); }); it('scrollRight with startPoint should use calculateScrollEndPoint', async () => { const startPoint = { left: 100, top: 200 }; const scrollDistance = 150; const calculateScrollEndPointSpy = rs.spyOn( device as any, 'calculateScrollEndPoint', ); await device.scrollRight(scrollDistance, startPoint); expect(calculateScrollEndPointSpy).toHaveBeenCalledWith( { x: 100, y: 200 }, -scrollDistance, 0, 1080, // width from mocked size() 1920, ); }); it('scrollDown with startPoint should call dragPoint with calculated end point', async () => { const startPoint = { left: 100, top: 200 }; const scrollDistance = 300; const mockEndPoint = { x: 100, y: 100 }; // Mocked calculated end point rs.spyOn(device as any, 'calculateScrollEndPoint').mockReturnValue( mockEndPoint, ); await device.scrollDown(scrollDistance, startPoint); expect((device as any).dragPoint).toHaveBeenCalledWith( { x: 100, y: 200 }, mockEndPoint, ); }); it('scrollUp with startPoint should call dragPoint with calculated end point', async () => { const startPoint = { left: 150, top: 400 }; const scrollDistance = 200; const mockEndPoint = { x: 150, y: 600 }; // Mocked calculated end point rs.spyOn(device as any, 'calculateScrollEndPoint').mockReturnValue( mockEndPoint, ); await device.scrollUp(scrollDistance, startPoint); expect((device as any).dragPoint).toHaveBeenCalledWith( { x: 150, y: 400 }, mockEndPoint, ); }); it('scrollLeft with startPoint should call dragPoint with calculated end point', async () => { const startPoint = { left: 500, top: 300 }; const scrollDistance = 100; const mockEndPoint = { x: 600, y: 300 }; // Mocked calculated end point rs.spyOn(device as any, 'calculateScrollEndPoint').mockReturnValue( mockEndPoint, ); await device.scrollLeft(scrollDistance, startPoint); expect((device as any).dragPoint).toHaveBeenCalledWith( { x: 500, y: 300 }, mockEndPoint, ); }); it('scrollRight with startPoint should call dragPoint with calculated end point', async () => { const startPoint = { left: 200, top: 250 }; const scrollDistance = 80; const mockEndPoint = { x: 120, y: 250 }; // Mocked calculated end point rs.spyOn(device as any, 'calculateScrollEndPoint').mockReturnValue( mockEndPoint, ); await device.scrollRight(scrollDistance, startPoint); expect((device as any).dragPoint).toHaveBeenCalledWith( { x: 200, y: 250 }, mockEndPoint, ); }); it('scroll methods should use default scroll distance when not provided', async () => { const startPoint = { left: 100, top: 200 }; const calculateScrollEndPointSpy = rs.spyOn( device as any, 'calculateScrollEndPoint', ); // scrollDown without distance should use screen height await device.scrollDown(undefined, startPoint); expect(calculateScrollEndPointSpy).toHaveBeenCalledWith( { x: 100, y: 200 }, 0, -1920, // negative screen height for scrollDown 1080, 1920, ); }); it('scrollDown with startPoint should warn when explicit distance is clamped', async () => { const startPoint = { left: 100, top: 100 }; await device.scrollDown(500, startPoint); expect(console.warn).toHaveBeenCalledWith( '[Midscene]', '[midscene] Android ADB swipe coordinates must stay within the screen bounds. The requested scroll distance (500px) exceeds the maximum single swipe distance (100px) from the current start point, so it will be clamped. If you want to scroll to the bottom, use scrollToBottom instead.', ); }); it('scrollDown with startPoint should not warn for default distance clamp', async () => { const startPoint = { left: 100, top: 100 }; await device.scrollDown(undefined, startPoint); expect(console.warn).not.toHaveBeenCalled(); }); }); }); describe('displayId', () => { let deviceWithDisplay: AndroidDevice; const setupMockAdb = (adbInstance: any) => { adbInstance.shell.mockImplementation((cmd: string) => { if (cmd.includes('wm size')) { return Promise.resolve('Physical size: 1080x1920'); } if (cmd.includes('dumpsys') && cmd.includes('input')) { return Promise.resolve('SurfaceOrientation: 0'); } if (cmd.includes('dumpsys SurfaceFlinger --display-id')) { return Promise.resolve( 'Display 4630946423637606531 (HWC display 1): valid=true\n', ); } if (cmd.includes('dumpsys display')) { return Promise.resolve( 'DisplayInfo{real 1080 x 1920, rotation 0, density 420, uniqueId "local:4630946423637606531"}\n', ); } if (cmd.includes('screencap')) { return Promise.resolve(''); } if (cmd.includes('rm')) { return Promise.resolve(''); } return Promise.resolve(''); }); adbInstance.getScreenDensity.mockResolvedValue(420); adbInstance.pull.mockResolvedValue(undefined); }; beforeEach(() => { rs.spyOn( AndroidDevice.prototype as any, 'getScreenSize', ).mockResolvedValue({ physical: '1080x1920', override: '', orientation: 0, }); }); afterEach(() => { if (deviceWithDisplay) { deviceWithDisplay.destroy(); } rs.restoreAllMocks(); }); describe('displayId', () => { let deviceWithDisplay: AndroidDevice; const setupMockAdb = (adbInstance: any) => { adbInstance.shell.mockImplementation((cmd: string) => { if (cmd.includes('wm size')) { return Promise.resolve('Physical size: 1080x1920'); } if (cmd.includes('dumpsys') && cmd.includes('input')) { return Promise.resolve('SurfaceOrientation: 0'); } if (cmd.includes('dumpsys SurfaceFlinger --display-id')) { return Promise.resolve( 'Display 4630946423637606531 (HWC display 1): valid=true\n', ); } if (cmd.includes('dumpsys display')) { return Promise.resolve( 'DisplayInfo{real 1080 x 1920, rotation 0, density 420, uniqueId "local:4630946423637606531"}\n', ); } if (cmd.includes('screencap')) { return Promise.resolve(''); } if (cmd.includes('rm')) { return Promise.resolve(''); } return Promise.resolve(''); }); adbInstance.getScreenDensity.mockResolvedValue(420); adbInstance.pull.mockResolvedValue(undefined); }; beforeEach(() => { rs.spyOn( AndroidDevice.prototype as any, 'getScreenSize', ).mockResolvedValue({ physical: '1080x1920', override: '', orientation: 0, }); }); afterEach(() => { if (deviceWithDisplay) { deviceWithDisplay.destroy(); } rs.restoreAllMocks(); }); it('should include display argument in shell commands when displayId is set', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 2, }); // Setup mock using global mockAdbInstance setupMockAdb(mockAdbInstance); rs.spyOn(deviceWithDisplay, 'getAdb').mockResolvedValue( mockAdbInstance as any, ); // Set device pixel ratio for coordinate adjustment (deviceWithDisplay as any).devicePixelRatio = 1; // Test mouse click command await deviceWithDisplay.inputPrimitives.pointer.tap({ x: 100, y: 200, }); expect(mockAdbInstance.shell).toHaveBeenCalledWith( expect.stringContaining('input -d 2 swipe'), ); }); it('should NOT pass the display argument to app_process (yadb) pinch even when displayId is set', async () => { // `app_process` is the ART runtime launcher and does not accept the // `-d ` flag the way `input`/`dumpsys` do. Passing it makes // the VM fail to start and breaks aiPinch. See getDisplayArg(). deviceWithDisplay = new AndroidDevice('test-device', { displayId: 0, }); setupMockAdb(mockAdbInstance); rs.spyOn(deviceWithDisplay, 'getAdb').mockResolvedValue( mockAdbInstance as any, ); rs.spyOn(deviceWithDisplay as any, 'ensureYadb').mockResolvedValue( undefined, ); (deviceWithDisplay as any).devicePixelRatio = 1; await deviceWithDisplay.inputPrimitives.touch.pinch!( { x: 1280, y: 720 }, { startDistance: 600, endDistance: 200, duration: 1200 }, ); const pinchCall = mockAdbInstance.shell.mock.calls.find( (call: unknown[]) => typeof call[0] === 'string' && call[0].includes('-pinch'), ); expect(pinchCall).toBeDefined(); expect(pinchCall![0]).toContain('app_process -Djava.class.path'); expect(pinchCall![0]).not.toContain('app_process -d'); }); it('should throw when pinch is called on a non-default display (displayId > 0)', async () => { // yadb only injects into the default display, so a non-default display // would silently land the pinch on the main screen. Fail fast instead. deviceWithDisplay = new AndroidDevice('test-device', { displayId: 2, }); setupMockAdb(mockAdbInstance); rs.spyOn(deviceWithDisplay, 'getAdb').mockResolvedValue( mockAdbInstance as any, ); rs.spyOn(deviceWithDisplay as any, 'ensureYadb').mockResolvedValue( undefined, ); (deviceWithDisplay as any).devicePixelRatio = 1; await expect( deviceWithDisplay.inputPrimitives.touch.pinch!( { x: 1280, y: 720 }, { startDistance: 600, endDistance: 200, duration: 1200 }, ), ).rejects.toThrow(/non-default display/); // No yadb command should have been issued. const pinchCall = mockAdbInstance.shell.mock.calls.find( (call: unknown[]) => typeof call[0] === 'string' && call[0].includes('-pinch'), ); expect(pinchCall).toBeUndefined(); }); it('should throw when typeText needs yadb on a non-default display', async () => { // yadb (app_process) cannot target non-default displays. When text // requires yadb (always-yadb strategy or auto-detected incompatible // chars), we must throw rather than silently corrupt the input. deviceWithDisplay = new AndroidDevice('test-device', { displayId: 2, imeStrategy: 'always-yadb', }); setupMockAdb(mockAdbInstance); rs.spyOn(deviceWithDisplay, 'getAdb').mockResolvedValue( mockAdbInstance as any, ); rs.spyOn(deviceWithDisplay as any, 'ensureYadb').mockResolvedValue( undefined, ); (deviceWithDisplay as any).devicePixelRatio = 1; await expect( deviceWithDisplay.inputPrimitives.keyboard.typeText('hello'), ).rejects.toThrow(/cannot target non-default display/); // No input or yadb command should have been issued. const textCalls = mockAdbInstance.shell.mock.calls.filter( (call: unknown[]) => typeof call[0] === 'string' && (call[0].includes('input text') || call[0].includes('yadb')), ); expect(textCalls).toHaveLength(0); }); it('should throw when typeText auto-detects yadb need on non-default display', async () => { // Even without always-yadb, non-ASCII text auto-detects yadb. On a // non-default display this must throw, not silently fall back. deviceWithDisplay = new AndroidDevice('test-device', { displayId: 2, imeStrategy: 'yadb-for-non-ascii', }); setupMockAdb(mockAdbInstance); rs.spyOn(deviceWithDisplay, 'getAdb').mockResolvedValue( mockAdbInstance as any, ); (deviceWithDisplay as any).devicePixelRatio = 1; await expect( deviceWithDisplay.inputPrimitives.keyboard.typeText('你好'), ).rejects.toThrow(/cannot target non-default display/); }); }); it('should not include display argument in shell commands when displayId is not set', async () => { deviceWithDisplay = new AndroidDevice('test-device'); // Setup mock using global mockAdbInstance setupMockAdb(mockAdbInstance); // Manually assign the mocked adb instance to bypass initialization (deviceWithDisplay as any).adb = mockAdbInstance; (deviceWithDisplay as any).connectingAdb = Promise.resolve(mockAdbInstance); // Set device pixel ratio for coordinate adjustment (deviceWithDisplay as any).devicePixelRatio = 1; // Test mouse click command await deviceWithDisplay.inputPrimitives.pointer.tap({ x: 100, y: 200 }); expect(mockAdbInstance.shell).toHaveBeenCalledWith( expect.stringContaining('input swipe'), ); expect(mockAdbInstance.shell).not.toHaveBeenCalledWith( expect.stringContaining('input -d'), ); }); it('should call dumpsys SurfaceFlinger with correct display ID for getPhysicalDisplayId', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 1, }); setupMockAdb(mockAdbInstance); await deviceWithDisplay.getAdb(); // Call a method that would trigger getPhysicalDisplayId const physicalDisplayIdMethod = ( deviceWithDisplay as any ).getPhysicalDisplayId.bind(deviceWithDisplay); const result = await physicalDisplayIdMethod(); expect(mockAdbInstance.shell).toHaveBeenCalledWith( 'dumpsys SurfaceFlinger --display-id 1', ); expect(result).toBe('4630946423637606531'); }); it('maps a logical display ID to its physical unique ID', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 0, }); setupMockAdb(mockAdbInstance); mockAdbInstance.shell.mockImplementation(async (command) => { const value = String(command); if (value === 'dumpsys display') { return `mDisplayId=0 mBaseDisplayInfo=DisplayInfo{"Outer", displayId 0, uniqueId "local:222"} mDisplayId=2 mBaseDisplayInfo=DisplayInfo{"Inner", displayId 2, uniqueId "local:111"}`; } return ''; }); await expect(deviceWithDisplay.getPhysicalDisplayId()).resolves.toBe( '222', ); expect(mockAdbInstance.shell).not.toHaveBeenCalledWith( 'dumpsys SurfaceFlinger --display-id 0', ); }); it('should use display-specific size when displayId is set', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 1, }); setupMockAdb(mockAdbInstance); await deviceWithDisplay.getAdb(); const size = await deviceWithDisplay.size(); expect(mockAdbInstance.shell).toHaveBeenCalledWith('dumpsys display'); expect(size.width).toBe(411); // 1080 / (420/160) ≈ 411 expect(size.height).toBe(731); // 1920 / (420/160) ≈ 731 // dpr is no longer returned in size() }); it('should use display ID for screenshots by default when displayId is set', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 1, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); setupMockAdb(mockAdbInstance); // Mock the scenario where takeScreenshot fails and we fall back to shell screencap mockAdbInstance.takeScreenshot.mockRejectedValue( new Error('Display 1 requires shell screencap'), ); await deviceWithDisplay.getAdb(); // Mock fs.promises.readFile to return a valid PNG buffer const mockBuffer = createValidPngBuffer(); (fs.promises.readFile as any).mockResolvedValue(mockBuffer); // Mock image utilities (ImgUtils.resizeAndConvertImgBuffer as any).mockResolvedValue({ buffer: mockBuffer, format: 'png' as const, }); (ImgUtils.createImgBase64ByFormat as any).mockReturnValue( 'data:image/png;base64,fake-data', ); await deviceWithDisplay.screenshotBase64(); // Verify that screencap command uses the display ID by default expect(mockAdbInstance.shell).toHaveBeenCalledWith( expect.stringMatching(/screencap -p -d 1/), ); expect(mockAdbInstance.shell).not.toHaveBeenCalledWith( expect.stringMatching(/screencap -p -d 4630946423637606531/), ); }); it('should use physical display ID for screenshots when usePhysicalDisplayIdForScreenshot is true', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 1, usePhysicalDisplayIdForScreenshot: true, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); setupMockAdb(mockAdbInstance); // Mock the scenario where takeScreenshot fails and we fall back to shell screencap mockAdbInstance.takeScreenshot.mockRejectedValue( new Error('Display 1 requires shell screencap'), ); await deviceWithDisplay.getAdb(); // Mock fs.promises.readFile to return a valid PNG buffer const mockBuffer = createValidPngBuffer(); (fs.promises.readFile as any).mockResolvedValue(mockBuffer); // Mock image utilities (ImgUtils.resizeAndConvertImgBuffer as any).mockResolvedValue({ buffer: mockBuffer, format: 'png' as const, }); (ImgUtils.createImgBase64ByFormat as any).mockReturnValue( 'data:image/png;base64,fake-data', ); await deviceWithDisplay.screenshotBase64(); // Verify that screencap command uses the physical display ID expect(mockAdbInstance.shell).toHaveBeenCalledWith( expect.stringMatching(/screencap -p -d 4630946423637606531/), ); }); it('should use display ID for screenshots when usePhysicalDisplayIdForScreenshot is false', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 2, usePhysicalDisplayIdForScreenshot: false, minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); setupMockAdb(mockAdbInstance); // Mock the scenario where takeScreenshot fails and we fall back to shell screencap mockAdbInstance.takeScreenshot.mockRejectedValue( new Error('Display 2 requires shell screencap'), ); // Manually assign the mocked adb instance (deviceWithDisplay as any).adb = mockAdbInstance; (deviceWithDisplay as any).connectingAdb = Promise.resolve(mockAdbInstance); // Mock fs.promises.readFile to return a valid PNG buffer const mockBuffer = createValidPngBuffer(); (fs.promises.readFile as any).mockResolvedValue(mockBuffer); // Mock image utilities (ImgUtils.resizeAndConvertImgBuffer as any).mockResolvedValue({ buffer: mockBuffer, format: 'png' as const, }); (ImgUtils.createImgBase64ByFormat as any).mockReturnValue( 'data:image/png;base64,fake-data', ); // Mock size method rs.spyOn(deviceWithDisplay, 'size').mockResolvedValue({ width: 1080, height: 1920, }); await deviceWithDisplay.screenshotBase64(); // Verify that screencap command uses the display ID (2), not the long one expect(mockAdbInstance.shell).toHaveBeenCalledWith( expect.stringMatching(/screencap -p -d 2/), ); expect(mockAdbInstance.shell).not.toHaveBeenCalledWith( expect.stringMatching(/screencap -p -d 4630946423637606531/), ); }); it('should handle keyboard operations with display argument when displayId is set', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 2, imeStrategy: 'yadb-for-non-ascii', // Use strategy that will call inputText for ASCII }); setupMockAdb(mockAdbInstance); // Manually assign the mocked adb instance (deviceWithDisplay as any).adb = mockAdbInstance; (deviceWithDisplay as any).connectingAdb = Promise.resolve(mockAdbInstance); // Mock ensureYadb method rs.spyOn(deviceWithDisplay as any, 'ensureYadb').mockResolvedValue( undefined, ); // Mock keyboard state management — track keyevents through shell calls let keyboardHidden = false; mockAdbInstance.isSoftKeyboardPresent.mockImplementation(() => { return Promise.resolve({ isKeyboardShown: !keyboardHidden, canCloseKeyboard: true, }); }); // Override shell mock to track keyevents for keyboard state const originalShellImpl = mockAdbInstance.shell.getMockImplementation(); mockAdbInstance.shell.mockImplementation((cmd: string) => { if (typeof cmd === 'string' && cmd.includes('keyevent 111')) { keyboardHidden = true; } return originalShellImpl ? originalShellImpl(cmd) : Promise.resolve(''); }); await deviceWithDisplay.inputPrimitives.keyboard.typeText('test'); expect(mockAdbInstance.shell).toHaveBeenCalledWith( "input -d 2 text 'test'", ); expect(mockAdbInstance.shell).toHaveBeenCalledWith( 'input -d 2 keyevent 111', ); // ESC key for hiding keyboard }); it('should handle back, home, and recentApps operations with display argument', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 1, }); setupMockAdb(mockAdbInstance); await deviceWithDisplay.getAdb(); mockAdbInstance.shell.mockClear(); await deviceWithDisplay.back(); expect(mockAdbInstance.shell).toHaveBeenCalledWith( 'input -d 1 keyevent 4', ); await deviceWithDisplay.home(); expect(mockAdbInstance.shell).toHaveBeenCalledWith( 'input -d 1 keyevent 3', ); await deviceWithDisplay.recentApps(); expect(mockAdbInstance.shell).toHaveBeenCalledWith( 'input -d 1 keyevent 187', ); }); it('should handle long press operations with display argument', async () => { deviceWithDisplay = new AndroidDevice('test-device', { displayId: 2, }); setupMockAdb(mockAdbInstance); // Manually assign the mocked adb instance to bypass initialization (deviceWithDisplay as any).adb = mockAdbInstance; (deviceWithDisplay as any).connectingAdb = Promise.resolve(mockAdbInstance); // Mock adjustCoordinates to pass through (this test focuses on displayId arg) rs.spyOn( deviceWithDisplay as any, 'adjustCoordinates', ).mockImplementation(async (...args: unknown[]) => { const [x, y] = args as [number, number]; return { x, y }; }); await deviceWithDisplay.inputPrimitives.pointer.longPress( { x: 100, y: 200 }, { duration: 1500 }, ); expect(mockAdbInstance.shell).toHaveBeenCalledWith( 'input -d 2 swipe 100 200 100 200 1500', ); }); it('should not use display ID for screenshots when displayId is not set', async () => { deviceWithDisplay = new AndroidDevice('test-device', { usePhysicalDisplayIdForScreenshot: true, // This should be ignored when no displayId minScreenshotBufferSize: 0, scrcpyConfig: { enabled: false }, }); setupMockAdb(mockAdbInstance); // Mock the scenario where takeScreenshot fails and we fall back to shell screencap mockAdbInstance.takeScreenshot.mockRejectedValue( new Error('takeScreenshot failed'), ); // Manually assign the mocked adb instance (deviceWithDisplay as any).adb = mockAdbInstance; (deviceWithDisplay as any).connectingAdb = Promise.resolve(mockAdbInstance); // Mock fs.promises.readFile to return a valid PNG buffer const mockBuffer = createValidPngBuffer(); (fs.promises.readFile as any).mockResolvedValue(mockBuffer); // Mock image utilities (ImgUtils.resizeAndConvertImgBuffer as any).mockResolvedValue({ buffer: mockBuffer, format: 'png' as const, }); (ImgUtils.createImgBase64ByFormat as any).mockReturnValue( 'data:image/png;base64,fake-data', ); // Mock size method rs.spyOn(deviceWithDisplay, 'size').mockResolvedValue({ width: 1080, height: 1920, }); await deviceWithDisplay.screenshotBase64(); // Verify that screencap command does not use any display ID (note the extra space) expect(mockAdbInstance.shell).toHaveBeenCalledWith( expect.stringMatching(/screencap -p {2}\/data\/local\/tmp\/ms_/), ); expect(mockAdbInstance.shell).not.toHaveBeenCalledWith( expect.stringMatching(/screencap -p -d/), ); }); }); describe('destroy', () => { it('should clean up resources', async () => { await device.destroy(); expect((device as any).adb).toBeNull(); expect((device as any).destroyed).toBe(true); }); }); describe('getDeviceLocalTimeString', () => { it('should return device-local time with the default format', async () => { mockAdb.shell.mockResolvedValueOnce('2023-10-15T15:37:02\n'); const result = await device.getDeviceLocalTimeString(); expect(mockAdb.shell).toHaveBeenCalledWith('date +%Y-%m-%dT%H:%M:%S'); expect(result).toBe('2023-10-15 15:37:02 (YYYY-MM-DD HH:mm:ss)'); }); it('should apply custom format tokens to device-local time', async () => { mockAdb.shell.mockResolvedValueOnce('2023-10-15T15:37:02'); const result = await device.getDeviceLocalTimeString('HH:mm'); expect(result).toBe('15:37 (HH:mm)'); }); it('should throw error for invalid device-local time format', async () => { mockAdb.shell.mockResolvedValueOnce('invalid-time'); await expect(device.getDeviceLocalTimeString()).rejects.toThrow( 'Invalid device time format', ); }); }); });