From 5f2abf79bb3586e8d5e7806a89dd88c500a4d6e4 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 29 Oct 2026 19:20:54 +0000 Subject: [PATCH 01/33] perf: one snapshot per tap; cache idb describe per connection - `tapElement(query, { element })`: tap an element the caller already resolved (core resolves it with `waitForElement`), so a click takes one snapshot instead of two. The viewport check still runs on iOS. - iOS: cache `idb describe --json` (OS version for the describe-all API order, window size) per companion connection. It was read before every snapshot, tap and swipe (~0.25 s each). Cleared on (re)connect; a failed read is not cached; `getDeviceInfo()` still reads fresh. --- CHANGELOG.md | 8 ++ src/backends/adb-backend.test.ts | 47 ++++++++ src/backends/adb-backend.ts | 22 ++-- src/backends/appium-backend.test.ts | 35 ++++++ src/backends/appium-backend.ts | 22 ++-- src/backends/idb-backend.test.ts | 181 +++++++++++++++++++++++++++- src/backends/idb-backend.ts | 122 ++++++++++++++----- src/backends/index.ts | 18 +-- src/backends/types.ts | 18 ++- src/index.ts | 1 + 10 files changed, 416 insertions(+), 58 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15f8256..70048f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `tapElement(query, { element })` taps an element the caller already resolved (for example from `waitForElement`) without taking a second snapshot + +### Changed + +- iOS (idb): read `idb describe --json` once per companion connection for the OS version and window size, instead of before every snapshot, tap and swipe. `getDeviceInfo()` still reads it fresh + ## [0.7.0] ### Added diff --git a/src/backends/adb-backend.test.ts b/src/backends/adb-backend.test.ts index dd5ea7c..f47a51f 100644 --- a/src/backends/adb-backend.test.ts +++ b/src/backends/adb-backend.test.ts @@ -621,6 +621,53 @@ describe('AdbBackend.getElementText', () => { }); }); +describe('AdbBackend.tapElement', () => { + let backend: AdbBackend; + const element: UIElement = { + type: 'android.widget.Button', + identifier: 'submit', + frame: { x: 100, y: 200, width: 400, height: 60 }, + enabled: true, + }; + + beforeEach(() => { + vi.clearAllMocks(); + mockExecStrict.mockResolvedValue(''); + backend = new AdbBackend('emulator-5554'); + }); + + it('taps a caller-resolved element without a new snapshot', async () => { + const result = await backend.tapElement( + { identifier: 'submit' }, + { element }, + ); + + expect(result).toMatchObject({ success: true, x: 300, y: 230 }); + expect(mockExecStrict).toHaveBeenCalledTimes(1); + expect(mockExecStrict).toHaveBeenCalledWith('adb', [ + '-s', + 'emulator-5554', + 'shell', + 'input', + 'tap', + '300', + '230', + ]); + }); + + it('snapshots to find the element when none is passed', async () => { + mockExecStrict.mockImplementation(async (_cmd, args) => + args?.includes('cat') || args?.includes('dump') + ? SAMPLE_UIAUTOMATOR_XML + : '', + ); + + await expect( + backend.tapElement({ identifier: 'not-on-screen' }), + ).rejects.toThrow('Element not found'); + }); +}); + describe('AdbBackend.screenshot', () => { let backend: AdbBackend; diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index 3c8f53a..dc176a6 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -34,21 +34,22 @@ import { reassembleInstrumentationXml, } from './android-instrumentation/snapshot.js'; import type { + AppStateResult, DeviceBackend, DeviceButton, DeviceInfo, - SnapshotResult, - ScreenshotResult, + ElementQuery, + LogsResult, ScreenshotFileResult, ScreenshotOptions, - LogsResult, + ScreenshotResult, + SnapshotResult, + TapElementOptions, TapResult, - AppStateResult, - ElementQuery, UIElement, - WindowSize, WebViewCdpInput, WebViewCdpOutcome, + WindowSize, } from './types.js'; import { runWebViewCdp } from './webview-cdp.js'; import { ACCEPT_LABELS, DENY_LABELS } from '../utils/alert-labels.js'; @@ -296,9 +297,12 @@ export class AdbBackend implements DeviceBackend { }; } - async tapElement(query: ElementQuery): Promise { - const snapshot = await this.snapshot(); - const element = findElement(snapshot.hierarchy, query); + async tapElement( + query: ElementQuery, + options?: TapElementOptions, + ): Promise { + const element = + options?.element ?? findElement((await this.snapshot()).hierarchy, query); if (!element) { throw new Error( `Element not found: ${JSON.stringify(query)}\n` + diff --git a/src/backends/appium-backend.test.ts b/src/backends/appium-backend.test.ts index 41a384d..abe2b13 100644 --- a/src/backends/appium-backend.test.ts +++ b/src/backends/appium-backend.test.ts @@ -13,6 +13,8 @@ const mockGetStatus = vi.fn(); const mockExecute = vi.fn(); const mockGetPageSource = vi.fn(); const mockUpdateSettings = vi.fn(); +const mockPerformActions = vi.fn(); +const mockReleaseActions = vi.fn(); vi.mock('./webdriver-client.js', () => ({ WebDriverClient: vi.fn().mockImplementation(function mockWebDriverClient() { @@ -21,6 +23,8 @@ vi.mock('./webdriver-client.js', () => ({ execute: mockExecute, getPageSource: mockGetPageSource, updateSettings: mockUpdateSettings, + performActions: mockPerformActions, + releaseActions: mockReleaseActions, }; }), createSession: vi.fn(), @@ -233,6 +237,37 @@ describe('AppiumBackend.screenshot', () => { }); }); +describe('AppiumBackend.tapElement', () => { + it('taps a caller-resolved element without reading the page source', async () => { + vi.clearAllMocks(); + mockGetStatus.mockResolvedValue({}); + mockPerformActions.mockResolvedValue(undefined); + const backend = new AppiumBackend({ + mode: 'attach', + appiumUrl: 'http://localhost:4723', + sessionId: 'session-1', + platform: 'ios', + }); + await backend.ensureConnected(); + + const result = await backend.tapElement( + { identifier: 'submit-btn' }, + { + element: { + type: 'Button', + identifier: 'submit-btn', + frame: { x: 20, y: 700, width: 350, height: 44 }, + enabled: true, + }, + }, + ); + + expect(result).toMatchObject({ success: true, x: 195, y: 722 }); + expect(mockGetPageSource).not.toHaveBeenCalled(); + expect(mockPerformActions).toHaveBeenCalledOnce(); + }); +}); + describe('AppiumBackend.snapshot (Android idle bypass)', () => { const config: AttachSessionConfig = { mode: 'attach', diff --git a/src/backends/appium-backend.ts b/src/backends/appium-backend.ts index b93f464..eec2700 100644 --- a/src/backends/appium-backend.ts +++ b/src/backends/appium-backend.ts @@ -1,18 +1,19 @@ import type { SessionConfig } from './session-file.js'; import type { + AppStateResult, DeviceBackend, DeviceButton, DeviceInfo, - SnapshotResult, - ScreenshotResult, + ElementQuery, + LogsResult, + Platform, ScreenshotFileResult, ScreenshotOptions, - LogsResult, + ScreenshotResult, + SnapshotResult, + TapElementOptions, TapResult, - AppStateResult, - ElementQuery, UIElement, - Platform, WindowSize, } from './types.js'; import { WebDriverClient, createSession } from './webdriver-client.js'; @@ -96,9 +97,12 @@ export class AppiumBackend implements DeviceBackend { }; } - async tapElement(query: ElementQuery): Promise { - const snapshot = await this.snapshot(); - const element = findElement(snapshot.hierarchy, query); + async tapElement( + query: ElementQuery, + options?: TapElementOptions, + ): Promise { + const element = + options?.element ?? findElement((await this.snapshot()).hierarchy, query); if (!element) { throw new Error( `Element not found: ${JSON.stringify(query)}\n` + diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index 3c08c5a..a1f6d7d 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -3,7 +3,7 @@ import { EventEmitter } from 'node:events'; import { readFileSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { parseIdbHierarchy, mapIdbElement, IdbBackend } from './idb-backend.js'; import { IdbUnavailableError } from './idb-errors.js'; @@ -824,6 +824,185 @@ describe('IdbBackend.tapElement and longPress viewport handling', () => { backend.longPress({ identifier: 'hidden-btn' }), ).rejects.toThrow('outside the 402x874 viewport'); }); + + it('taps a caller-resolved element without a new snapshot', async () => { + mockScreen([]); + + const result = await backend.tapElement( + { identifier: 'submit-btn' }, + { + element: { + type: 'Button', + identifier: 'submit-btn', + frame: { x: 10, y: 20, width: 100, height: 44 }, + enabled: true, + }, + }, + ); + + expect(result).toMatchObject({ success: true, x: 60, y: 42 }); + expect(mockExecStrict).not.toHaveBeenCalledWith( + '/usr/local/bin/idb', + expect.arrayContaining(['describe-all']), + connectionOptions, + ); + }); + + it('keeps the viewport check for a caller-resolved element', async () => { + mockScreen([]); + + await expect( + backend.tapElement( + { identifier: 'hidden-btn' }, + { + element: { + type: 'Button', + identifier: 'hidden-btn', + frame: { x: 0, y: 1000, width: 402, height: 100 }, + enabled: true, + }, + }, + ), + ).rejects.toThrow('outside the 402x874 viewport'); + }); +}); + +describe('IdbBackend device description cache', () => { + const udid = 'AAAA1111-BBBB-CCCC-DDDD-EEEE2222FFFF'; + let backend: IdbBackend; + + const screenInfo = { + name: 'iPhone 17 Pro', + os_version: '26.5', + state: 'Booted', + screen_dimensions: { width_points: 402, height_points: 874 }, + }; + const button = { + type: 'Button', + AXLabel: 'Submit', + AXUniqueId: 'submit-btn', + frame: { x: 10, y: 20, width: 100, height: 44 }, + enabled: true, + }; + + const describeJsonCalls = (): number => + mockExecStrict.mock.calls.filter( + ([, args]) => args?.includes('describe') && args?.includes('--json'), + ).length; + const describeAllCalls = (): number => + mockExecStrict.mock.calls.filter(([, args]) => + args?.includes('describe-all'), + ).length; + + beforeEach(() => { + vi.clearAllMocks(); + mockSupportsApi.mockResolvedValue(true); + mockChooseAxApi.mockReturnValue('axbridge'); + mockExec.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('describe') && args?.includes('--json')) { + return JSON.stringify(screenInfo); + } + if (args?.includes('describe-all')) { + return JSON.stringify([button]); + } + return ''; + }); + backend = new IdbBackend(udid); + }); + + afterEach(() => { + mockSupportsApi.mockResolvedValue(false); + mockChooseAxApi.mockReturnValue(null); + }); + + it('reads idb describe once per connection for snapshots and taps', async () => { + const element = await backend.waitForElement({ identifier: 'submit-btn' }); + await backend.tapElement({ identifier: 'submit-btn' }, { element }); + await backend.snapshot(); + await backend.tapElement({ identifier: 'submit-btn' }); + await backend.swipe('up'); + + expect(describeJsonCalls()).toBe(1); + // waitForElement, snapshot, and the second (unresolved) tap. + expect(describeAllCalls()).toBe(3); + }); + + it('shares one describe read between concurrent first calls', async () => { + await Promise.all([backend.snapshot(), backend.getWindowSize()]); + + expect(describeJsonCalls()).toBe(1); + }); + + it('reads the description again after a reconnect', async () => { + await backend.snapshot(); + await backend.reconnect(); + await backend.snapshot(); + + expect(describeJsonCalls()).toBe(2); + }); + + it('does not cache a failed read', async () => { + let failures = 1; + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('describe') && args?.includes('--json')) { + if (failures > 0) { + failures -= 1; + throw new Error('companion busy'); + } + return JSON.stringify(screenInfo); + } + return JSON.stringify([button]); + }); + + await expect(backend.getWindowSize()).rejects.toThrow('companion busy'); + expect(await backend.getWindowSize()).toStrictEqual({ + width: 402, + height: 874, + }); + expect(describeJsonCalls()).toBe(2); + }); + + it('getDeviceInfo reads fresh and refreshes the cache', async () => { + await backend.getWindowSize(); + const info = await backend.getDeviceInfo(); + await backend.getWindowSize(); + + expect(info).toStrictEqual({ + platform: 'ios', + deviceId: udid, + name: 'iPhone 17 Pro', + osVersion: '26.5', + state: 'Booted', + }); + expect(describeJsonCalls()).toBe(2); + }); + + it('falls back to the snapshot root when describe is not JSON', async () => { + // Without --api support the snapshot does not need the OS version. + mockSupportsApi.mockResolvedValue(false); + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('describe') && args?.includes('--json')) { + return 'not json'; + } + return JSON.stringify([ + { type: 'Application', frame: { x: 0, y: 0, width: 390, height: 844 } }, + ]); + }); + + expect(await backend.getWindowSize()).toStrictEqual({ + width: 390, + height: 844, + }); + }); + + it('getDeviceInfo rejects a non-JSON description', async () => { + mockExecStrict.mockResolvedValue('not json'); + + await expect(backend.getDeviceInfo()).rejects.toThrow( + `idb describe returned invalid JSON for device ${udid}: not json`, + ); + }); }); describe('IdbBackend.ensureConnected', () => { diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index 3cbb9e6..46c1ce0 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -5,17 +5,18 @@ import { readFile } from 'node:fs/promises'; import { IdbConnection } from './idb-connection.js'; import { classifyIdbFailure, IdbUnavailableError } from './idb-errors.js'; import type { + AppStateResult, DeviceBackend, DeviceButton, DeviceInfo, - SnapshotResult, - ScreenshotResult, + ElementQuery, + LogsResult, ScreenshotFileResult, ScreenshotOptions, - LogsResult, + ScreenshotResult, + SnapshotResult, + TapElementOptions, TapResult, - AppStateResult, - ElementQuery, UIElement, WindowSize, } from './types.js'; @@ -39,6 +40,16 @@ import { } from '../utils/platform.js'; import { stopChildProcess } from '../utils/stop-child-process.js'; +/** `idb describe --json` printed something that is not JSON. */ +class InvalidDescribeJsonError extends Error { + constructor(udid: string, raw: string) { + super( + `idb describe returned invalid JSON for device ${udid}: ${raw.slice(0, 200)}`, + ); + this.name = 'InvalidDescribeJsonError'; + } +} + export class IdbBackend implements DeviceBackend { readonly kind = 'idb' as const; @@ -75,6 +86,15 @@ export class IdbBackend implements DeviceBackend { #stoppingRecording: Promise | undefined; + /** + * `idb describe --json` of the current connection: OS version (for the + * describe-all API order) and screen size. Read once per connection, because + * every read is an idb process (~0.25 s) and both values are fixed while the + * simulator stays booted. Cleared on every (re)connect. A rotation while + * connected is not detected; reconnect after rotating. + */ + #describeCache: Promise> | undefined; + constructor(udid: string) { this.#udid = udid; this.#connection = new IdbConnection(udid); @@ -143,6 +163,7 @@ export class IdbBackend implements DeviceBackend { } await this.#connection.connect(this.#idbPath); await this.#enableSimulatorAccessibility(); + this.#describeCache = undefined; this.#generation += 1; this.#connected = true; } catch (error) { @@ -322,22 +343,56 @@ export class IdbBackend implements DeviceBackend { } } + /** + * Runs `idb describe --json` and stores the result as the cached + * description of the current connection (see `#describeCache`). Concurrent + * callers of `#cachedDescribe()` share one read; a failed read is dropped + * from the cache so the next call retries. + * + * @returns The parsed device description. + */ + async #describe(): Promise> { + const pending = (async (): Promise> => { + const raw = await this.#execStrict(this.#idbPath, [ + 'describe', + '--udid', + this.#udid, + '--json', + ]); + try { + return JSON.parse(raw) as Record; + } catch { + throw new InvalidDescribeJsonError(this.#udid, raw); + } + })(); + this.#describeCache = pending; + pending.catch(() => { + if (this.#describeCache === pending) { + this.#describeCache = undefined; + } + }); + return pending; + } + + /** + * The cached `idb describe --json` of the current connection; reads it on + * first use. + * + * @returns The parsed device description. + */ + async #cachedDescribe(): Promise> { + return this.#describeCache ?? this.#describe(); + } + + /** + * Reads the device description fresh (and refreshes the cache that + * snapshots and taps use). + * + * @returns The device info. + */ async getDeviceInfo(): Promise { await this.ensureConnected(); - const raw = await this.#execStrict(this.#idbPath, [ - 'describe', - '--udid', - this.#udid, - '--json', - ]); - let info: Record; - try { - info = JSON.parse(raw) as Record; - } catch { - throw new Error( - `idb describe returned invalid JSON for device ${this.#udid}: ${raw.slice(0, 200)}`, - ); - } + const info = await this.#describe(); return { platform: 'ios', deviceId: this.#udid, @@ -403,16 +458,20 @@ export class IdbBackend implements DeviceBackend { if (!this.#idbSupportsApi) { return [null]; } - const { osVersion } = await this.getDeviceInfo(); + const info = await this.#cachedDescribe(); + const osVersion = (info.os_version as string) ?? 'Unknown'; const preferred = chooseAxApi(osVersion, true); const complement = preferred === 'axbridge' ? 'ax' : 'axbridge'; return [preferred, complement]; } - async tapElement(query: ElementQuery): Promise { + async tapElement( + query: ElementQuery, + options?: TapElementOptions, + ): Promise { await this.ensureConnected(); - const snapshot = await this.snapshot(); - const element = findElement(snapshot.hierarchy, query); + const element = + options?.element ?? findElement((await this.snapshot()).hierarchy, query); if (!element) { throw new Error( `Element not found: ${JSON.stringify(query)}\n` + @@ -856,15 +915,16 @@ export class IdbBackend implements DeviceBackend { async getWindowSize(): Promise { await this.ensureConnected(); - const raw = await this.#execStrict(this.#idbPath, [ - 'describe', - '--udid', - this.#udid, - '--json', - ]); + // A transport failure still throws, as before; only parse problems fall + // back to the snapshot. + const info = await this.#cachedDescribe().catch((error: unknown) => { + if (error instanceof InvalidDescribeJsonError) { + return undefined; + } + throw error; + }); try { - const info = JSON.parse(raw) as Record; - const dims = info.screen_dimensions as + const dims = info?.screen_dimensions as | { width?: number; height?: number; diff --git a/src/backends/index.ts b/src/backends/index.ts index bdeb6d5..8d4e98a 100644 --- a/src/backends/index.ts +++ b/src/backends/index.ts @@ -4,23 +4,24 @@ import { AppiumBackend } from './appium-backend.js'; import { IdbBackend } from './idb-backend.js'; import { readSessionFile } from './session-file.js'; import type { + AppStateResult, BackendKind, DeviceBackend, DeviceButton, DeviceInfo, + ElementQuery, LogsResult, - ScreenshotResult, + Platform, ScreenshotFileResult, ScreenshotOptions, + ScreenshotResult, SnapshotResult, + TapElementOptions, TapResult, - AppStateResult, - ElementQuery, UIElement, - Platform, - WindowSize, WebViewCdpInput, WebViewCdpOutcome, + WindowSize, } from './types.js'; import { detectPlatform, @@ -229,8 +230,11 @@ export function createLazyBackend( return (await resolve()).snapshot(); }, - async tapElement(query: ElementQuery): Promise { - return (await resolve()).tapElement(query); + async tapElement( + query: ElementQuery, + options?: TapElementOptions, + ): Promise { + return (await resolve()).tapElement(query, options); }, async tapCoordinates(x: number, y: number): Promise { diff --git a/src/backends/types.ts b/src/backends/types.ts index b27403d..4fb3452 100644 --- a/src/backends/types.ts +++ b/src/backends/types.ts @@ -46,6 +46,14 @@ export type TapResult = { targetDescription: string; }; +export type TapElementOptions = { + /** + * The element to tap, already resolved by the caller. Its frame is used as + * is; the backend does not check that it still matches `query`. + */ + element?: UIElement; +}; + export type AppStateResult = { bundleId: string; state: string; @@ -127,7 +135,15 @@ export type DeviceBackend = { snapshot(): Promise; - tapElement(query: ElementQuery): Promise; + /** + * Taps the element that matches `query`. Pass `options.element` (an element + * the caller already resolved, for example from `waitForElement`) to tap it + * without taking a new snapshot. + */ + tapElement( + query: ElementQuery, + options?: TapElementOptions, + ): Promise; tapCoordinates(x: number, y: number): Promise; diff --git a/src/index.ts b/src/index.ts index a2a4aba..b3f4a90 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,6 +24,7 @@ export type { ScreenshotFileResult, ScreenshotOptions, LogsResult, + TapElementOptions, TapResult, AppStateResult, Platform, From c7552608a03874784abc1c001927b7d396ff5252 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 6 Nov 2026 09:39:47 -0600 Subject: [PATCH 02/33] refactor: drop dead try/catch in idb getWindowSize --- src/backends/idb-backend.ts | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index 46c1ce0..5f3f60f 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -915,32 +915,28 @@ export class IdbBackend implements DeviceBackend { async getWindowSize(): Promise { await this.ensureConnected(); - // A transport failure still throws, as before; only parse problems fall - // back to the snapshot. + // Transport errors throw; only a non-JSON description falls back to the + // snapshot. const info = await this.#cachedDescribe().catch((error: unknown) => { if (error instanceof InvalidDescribeJsonError) { return undefined; } throw error; }); - try { - const dims = info?.screen_dimensions as - | { - width?: number; - height?: number; - // eslint-disable-next-line @typescript-eslint/naming-convention -- idb wire field - width_points?: number; - // eslint-disable-next-line @typescript-eslint/naming-convention -- idb wire field - height_points?: number; - } - | undefined; - // Gestures and accessibility frames are in logical points, while - // `width`/`height` are hardware pixels; prefer the point dimensions. - if (dims?.width_points && dims?.height_points) { - return { width: dims.width_points, height: dims.height_points }; - } - } catch { - // fall through to snapshot-based approach + const dims = info?.screen_dimensions as + | { + width?: number; + height?: number; + // eslint-disable-next-line @typescript-eslint/naming-convention -- idb wire field + width_points?: number; + // eslint-disable-next-line @typescript-eslint/naming-convention -- idb wire field + height_points?: number; + } + | undefined; + // Gestures and accessibility frames are in logical points, while + // `width`/`height` are hardware pixels; prefer the point dimensions. + if (dims?.width_points && dims?.height_points) { + return { width: dims.width_points, height: dims.height_points }; } const snap = await this.snapshot(); if (snap.hierarchy.length > 0) { From 4d07f40d6cf9ecb1b0276c5a968255182ff969f8 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Tue, 10 Nov 2026 13:34:08 +0000 Subject: [PATCH 03/33] chore: drop manual CHANGELOG entries The release PR generates them from the commit history. --- CHANGELOG.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70048f4..15f8256 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,14 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Added - -- `tapElement(query, { element })` taps an element the caller already resolved (for example from `waitForElement`) without taking a second snapshot - -### Changed - -- iOS (idb): read `idb describe --json` once per companion connection for the OS version and window size, instead of before every snapshot, tap and swipe. `getDeviceInfo()` still reads it fresh - ## [0.7.0] ### Added From bb01e6275eb3b02c895673c5e119fc0590e591fe Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Tue, 10 Nov 2026 13:34:08 +0000 Subject: [PATCH 04/33] fix: keep the cached idb description while getDeviceInfo reads getDeviceInfo replaced the cache with its pending read, so snapshots and taps waited for it and failed with it, and a failed read emptied the cache. Now a successful read replaces the cache (unless a reconnect happened meanwhile); until then, and after a failure, the cached description is used. --- src/backends/idb-backend.test.ts | 62 +++++++++++++++++++++++++++++ src/backends/idb-backend.ts | 67 +++++++++++++++++--------------- 2 files changed, 98 insertions(+), 31 deletions(-) diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index a1f6d7d..fa576e8 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -978,6 +978,68 @@ describe('IdbBackend device description cache', () => { expect(describeJsonCalls()).toBe(2); }); + it('keeps the cached description when a getDeviceInfo read fails', async () => { + await backend.getWindowSize(); + mockExecStrict.mockImplementationOnce(async () => { + throw new Error('companion busy'); + }); + + await expect(backend.getDeviceInfo()).rejects.toThrow('companion busy'); + expect(await backend.getWindowSize()).toStrictEqual({ + width: 402, + height: 874, + }); + expect(describeJsonCalls()).toBe(2); + }); + + it('serves the cached description while getDeviceInfo reads', async () => { + await backend.getWindowSize(); + let finishRead: (raw: string) => void = () => undefined; + mockExecStrict.mockImplementationOnce( + async () => + new Promise((resolve) => { + finishRead = resolve; + }), + ); + const refreshing = backend.getDeviceInfo(); + + expect(await backend.getWindowSize()).toStrictEqual({ + width: 402, + height: 874, + }); + + finishRead( + JSON.stringify({ + ...screenInfo, + screen_dimensions: { width_points: 874, height_points: 402 }, + }), + ); + await refreshing; + expect(await backend.getWindowSize()).toStrictEqual({ + width: 874, + height: 402, + }); + expect(describeJsonCalls()).toBe(2); + }); + + it('does not cache a getDeviceInfo read that a reconnect overtook', async () => { + let finishRead: (raw: string) => void = () => undefined; + await backend.ensureConnected(); + mockExecStrict.mockImplementationOnce( + async () => + new Promise((resolve) => { + finishRead = resolve; + }), + ); + const refreshing = backend.getDeviceInfo(); + await backend.reconnect(); + finishRead(JSON.stringify(screenInfo)); + await refreshing; + + await backend.getWindowSize(); + expect(describeJsonCalls()).toBe(2); + }); + it('falls back to the snapshot root when describe is not JSON', async () => { // Without --api support the snapshot does not need the OS version. mockSupportsApi.mockResolvedValue(false); diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index 5f3f60f..44c6a6b 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -344,55 +344,60 @@ export class IdbBackend implements DeviceBackend { } /** - * Runs `idb describe --json` and stores the result as the cached - * description of the current connection (see `#describeCache`). Concurrent - * callers of `#cachedDescribe()` share one read; a failed read is dropped - * from the cache so the next call retries. + * Runs `idb describe --json`. * * @returns The parsed device description. */ - async #describe(): Promise> { - const pending = (async (): Promise> => { - const raw = await this.#execStrict(this.#idbPath, [ - 'describe', - '--udid', - this.#udid, - '--json', - ]); - try { - return JSON.parse(raw) as Record; - } catch { - throw new InvalidDescribeJsonError(this.#udid, raw); - } - })(); - this.#describeCache = pending; - pending.catch(() => { - if (this.#describeCache === pending) { - this.#describeCache = undefined; - } - }); - return pending; + async #readDescribe(): Promise> { + const raw = await this.#execStrict(this.#idbPath, [ + 'describe', + '--udid', + this.#udid, + '--json', + ]); + try { + return JSON.parse(raw) as Record; + } catch { + throw new InvalidDescribeJsonError(this.#udid, raw); + } } /** - * The cached `idb describe --json` of the current connection; reads it on - * first use. + * The cached `idb describe --json` of the current connection (see + * `#describeCache`); reads it on first use. Concurrent first callers share + * one read; a failed read is dropped from the cache so the next call + * retries. * * @returns The parsed device description. */ async #cachedDescribe(): Promise> { - return this.#describeCache ?? this.#describe(); + if (this.#describeCache) { + return this.#describeCache; + } + const pending = this.#readDescribe(); + this.#describeCache = pending; + pending.catch(() => { + if (this.#describeCache === pending) { + this.#describeCache = undefined; + } + }); + return pending; } /** - * Reads the device description fresh (and refreshes the cache that - * snapshots and taps use). + * Reads the device description fresh. A successful read replaces the cache + * that snapshots and taps use, unless the connection changed meanwhile; + * until then, and after a failed read, they keep the cached description. * * @returns The device info. */ async getDeviceInfo(): Promise { await this.ensureConnected(); - const info = await this.#describe(); + const generation = this.#generation; + const info = await this.#readDescribe(); + if (this.#generation === generation) { + this.#describeCache = Promise.resolve(info); + } return { platform: 'ios', deviceId: this.#udid, From 693e87c6316075504a3c1c27c4bfe95251a25219 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Tue, 10 Nov 2026 13:34:08 +0000 Subject: [PATCH 05/33] fix: waitForElement returns an element that appeared once it stops moving Callers tap the returned frame without a new snapshot. An element that appears during the wait can still be animating in (a sheet sliding up), so it is read again until its frame is the same in two reads in a row (at most 3 extra reads, within the timeout). An element already on screen at the first read is returned at once, as before. Shared by the idb, adb and Appium backends. --- SKILL.md | 2 +- src/backends/adb-backend.ts | 17 ++-- src/backends/appium-backend.ts | 17 ++-- src/backends/idb-backend.ts | 17 ++-- src/backends/types.ts | 6 ++ src/tools/wait-for.ts | 3 +- src/utils/element.test.ts | 21 +++++ src/utils/element.ts | 16 ++++ src/utils/wait-for-element.test.ts | 127 +++++++++++++++++++++++++++++ src/utils/wait-for-element.ts | 77 +++++++++++++++++ 10 files changed, 268 insertions(+), 35 deletions(-) create mode 100644 src/utils/wait-for-element.test.ts create mode 100644 src/utils/wait-for-element.ts diff --git a/SKILL.md b/SKILL.md index c6e56d1..d7745b7 100644 --- a/SKILL.md +++ b/SKILL.md @@ -147,7 +147,7 @@ Swipe on screen. Uses **natural scrolling**: swipe `"up"` to scroll content **do ### device_wait_for -Poll the hierarchy until an element appears. Use after navigation or when waiting for async content. +Poll the hierarchy until an element appears. An element that appears during the wait is returned once it stops moving (for example a sheet sliding in). Use after navigation or when waiting for async content. ```json { "label": "Welcome", "timeoutMs": 15000 } diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index dc176a6..04ac7d4 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -63,6 +63,7 @@ import { hardenArtifactFile, resolveArtifactPath, } from '../utils/output-path.js'; +import { pollForElement } from '../utils/wait-for-element.js'; // `uiautomator dump` exits 0 and prints its success banner even when it fails, so // the XML payload is the only trustworthy signal. @@ -384,17 +385,11 @@ export class AdbBackend implements DeviceBackend { timeoutMs = 10_000, intervalMs = 500, ): Promise { - const start = Date.now(); - while (Date.now() - start < timeoutMs) { - const snapshot = await this.snapshot(); - const element = findElement(snapshot.hierarchy, query); - if (element) { - return element; - } - await new Promise((resolve) => setTimeout(resolve, intervalMs)); - } - throw new Error( - `Timed out waiting for element: ${JSON.stringify(query)} (${timeoutMs}ms)`, + return pollForElement( + async () => this.snapshot(), + query, + timeoutMs, + intervalMs, ); } diff --git a/src/backends/appium-backend.ts b/src/backends/appium-backend.ts index eec2700..3a8bc3d 100644 --- a/src/backends/appium-backend.ts +++ b/src/backends/appium-backend.ts @@ -26,6 +26,7 @@ import { resolveArtifactPath, writeArtifactFile, } from '../utils/output-path.js'; +import { pollForElement } from '../utils/wait-for-element.js'; export class AppiumBackend implements DeviceBackend { readonly kind = 'appium' as const; @@ -196,17 +197,11 @@ export class AppiumBackend implements DeviceBackend { timeoutMs = 10_000, intervalMs = 500, ): Promise { - const start = Date.now(); - while (Date.now() - start < timeoutMs) { - const snap = await this.snapshot(); - const element = findElement(snap.hierarchy, query); - if (element) { - return element; - } - await new Promise((resolve) => setTimeout(resolve, intervalMs)); - } - throw new Error( - `Timed out waiting for element: ${JSON.stringify(query)} (${timeoutMs}ms)`, + return pollForElement( + async () => this.snapshot(), + query, + timeoutMs, + intervalMs, ); } diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index 44c6a6b..2fbb16d 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -39,6 +39,7 @@ import { resolveIdbPath, } from '../utils/platform.js'; import { stopChildProcess } from '../utils/stop-child-process.js'; +import { pollForElement } from '../utils/wait-for-element.js'; /** `idb describe --json` printed something that is not JSON. */ class InvalidDescribeJsonError extends Error { @@ -641,17 +642,11 @@ export class IdbBackend implements DeviceBackend { timeoutMs = 10_000, intervalMs = 500, ): Promise { - const start = Date.now(); - while (Date.now() - start < timeoutMs) { - const snapshot = await this.snapshot(); - const element = findElement(snapshot.hierarchy, query); - if (element) { - return element; - } - await new Promise((resolve) => setTimeout(resolve, intervalMs)); - } - throw new Error( - `Timed out waiting for element: ${JSON.stringify(query)} (${timeoutMs}ms)`, + return pollForElement( + async () => this.snapshot(), + query, + timeoutMs, + intervalMs, ); } diff --git a/src/backends/types.ts b/src/backends/types.ts index 4fb3452..0eea721 100644 --- a/src/backends/types.ts +++ b/src/backends/types.ts @@ -156,6 +156,12 @@ export type DeviceBackend = { distance?: number, ): Promise; + /** + * Polls snapshots until an element matches `query`. An element that appears + * during the wait is returned once its frame stops changing (a sheet that + * is still sliding in), so a tap on the returned frame lands where the + * element stops. + */ waitForElement( query: ElementQuery, timeoutMs?: number, diff --git a/src/tools/wait-for.ts b/src/tools/wait-for.ts index b400250..dfcd948 100644 --- a/src/tools/wait-for.ts +++ b/src/tools/wait-for.ts @@ -13,7 +13,8 @@ export function registerWaitForTool( { title: 'Wait For Element', description: - 'Poll the UI hierarchy until an element matching the query appears. ' + + 'Poll the UI hierarchy until an element matching the query appears ' + + '(and, when it appears during the wait, stops moving). ' + 'Useful for waiting on transitions, loading states, or navigation.', inputSchema: { label: z.string().optional().describe('Accessibility label to match'), diff --git a/src/utils/element.test.ts b/src/utils/element.test.ts index 3abd1e6..11a4d77 100644 --- a/src/utils/element.test.ts +++ b/src/utils/element.test.ts @@ -8,6 +8,7 @@ import { formatHierarchy, generateLocators, formatLocators, + sameFrame, } from './element.js'; import type { UIElement } from '../backends/types.js'; @@ -100,6 +101,26 @@ describe('findElement', () => { }); }); +describe('sameFrame', () => { + it('compares position and size', () => { + const a = makeElement({ label: 'a' }); + + expect(sameFrame(a, makeElement({ label: 'b' }))).toBe(true); + expect( + sameFrame( + a, + makeElement({ frame: { x: 0, y: 1, width: 100, height: 44 } }), + ), + ).toBe(false); + expect( + sameFrame( + a, + makeElement({ frame: { x: 0, y: 0, width: 100, height: 40 } }), + ), + ).toBe(false); + }); +}); + describe('describeElement', () => { it('includes all available fields', () => { const el = makeElement({ diff --git a/src/utils/element.ts b/src/utils/element.ts index 8c5c571..ecfce40 100644 --- a/src/utils/element.ts +++ b/src/utils/element.ts @@ -54,6 +54,22 @@ function fuzzyMatch(actual: string | undefined, expected: string): boolean { return actual.toLowerCase().includes(expected.toLowerCase()); } +/** + * Whether two elements have the same frame. + * + * @param a - One element. + * @param b - The other element. + * @returns True when the frames are equal. + */ +export function sameFrame(a: UIElement, b: UIElement): boolean { + return ( + a.frame.x === b.frame.x && + a.frame.y === b.frame.y && + a.frame.width === b.frame.width && + a.frame.height === b.frame.height + ); +} + export function describeElement(element: UIElement): string { const parts: string[] = [element.type]; if (element.label) { diff --git a/src/utils/wait-for-element.test.ts b/src/utils/wait-for-element.test.ts new file mode 100644 index 0000000..d592a35 --- /dev/null +++ b/src/utils/wait-for-element.test.ts @@ -0,0 +1,127 @@ +import { describe, it, expect, vi } from 'vitest'; + +import { pollForElement } from './wait-for-element.js'; +import type { SnapshotResult, UIElement } from '../backends/types.js'; + +const sheetButton = (y: number): UIElement => ({ + type: 'Button', + identifier: 'confirm', + frame: { x: 20, y, width: 200, height: 44 }, + enabled: true, +}); + +const screen = (...hierarchy: UIElement[]): SnapshotResult => ({ + platform: 'ios', + hierarchy, + raw: JSON.stringify(hierarchy), + timestamp: 0, +}); + +/** + * A snapshot reader that returns the given screens in order, then repeats the + * last one. + * + * @param screens - The screens to return. + * @returns The mock reader. + */ +function reads(...screens: SnapshotResult[]): ReturnType { + let i = 0; + return vi.fn(async () => { + const next = screens[Math.min(i, screens.length - 1)]; + i += 1; + return next; + }); +} + +describe('pollForElement', () => { + const query = { identifier: 'confirm' }; + + it('returns an element that is on screen at the first read at once', async () => { + const snapshot = reads(screen(sheetButton(700)), screen(sheetButton(500))); + + expect(await pollForElement(snapshot, query, 1_000, 0)).toStrictEqual( + sheetButton(700), + ); + expect(snapshot).toHaveBeenCalledTimes(1); + }); + + it('waits for an element that appears during the wait to stop moving', async () => { + const snapshot = reads( + screen(), + screen(sheetButton(800)), + screen(sheetButton(600)), + screen(sheetButton(500)), + screen(sheetButton(500)), + ); + + expect(await pollForElement(snapshot, query, 1_000, 0)).toStrictEqual( + sheetButton(500), + ); + expect(snapshot).toHaveBeenCalledTimes(5); + }); + + it('returns an element that appeared already settled after one more read', async () => { + const snapshot = reads(screen(), screen(sheetButton(500))); + + expect(await pollForElement(snapshot, query, 1_000, 0)).toStrictEqual( + sheetButton(500), + ); + expect(snapshot).toHaveBeenCalledTimes(3); + }); + + it('returns the last frame when the element is still moving after the extra reads', async () => { + const snapshot = reads( + screen(), + screen(sheetButton(800)), + screen(sheetButton(700)), + screen(sheetButton(600)), + screen(sheetButton(500)), + screen(sheetButton(400)), + ); + + expect(await pollForElement(snapshot, query, 1_000, 0)).toStrictEqual( + sheetButton(500), + ); + expect(snapshot).toHaveBeenCalledTimes(5); + }); + + it('keeps polling when the element disappears while settling', async () => { + const snapshot = reads( + screen(), + screen(sheetButton(800)), + screen(), + screen(sheetButton(500)), + screen(sheetButton(500)), + ); + + expect(await pollForElement(snapshot, query, 1_000, 0)).toStrictEqual( + sheetButton(500), + ); + expect(snapshot).toHaveBeenCalledTimes(5); + }); + + it('does not read again to settle once the timeout has passed', async () => { + const now = vi.spyOn(Date, 'now'); + // start, first poll, second poll, then the timeout has passed. + now + .mockReturnValueOnce(0) + .mockReturnValueOnce(0) + .mockReturnValueOnce(0) + .mockReturnValue(2_000); + const snapshot = reads(screen(), screen(sheetButton(800))); + + expect(await pollForElement(snapshot, query, 1_000, 0)).toStrictEqual( + sheetButton(800), + ); + expect(snapshot).toHaveBeenCalledTimes(2); + now.mockRestore(); + }); + + it('throws when the element does not appear before the timeout', async () => { + const snapshot = reads(screen()); + + await expect(pollForElement(snapshot, query, 30, 5)).rejects.toThrow( + 'Timed out waiting for element: {"identifier":"confirm"} (30ms)', + ); + }); +}); diff --git a/src/utils/wait-for-element.ts b/src/utils/wait-for-element.ts new file mode 100644 index 0000000..f48f684 --- /dev/null +++ b/src/utils/wait-for-element.ts @@ -0,0 +1,77 @@ +import { findElement, sameFrame } from './element.js'; +import type { + ElementQuery, + SnapshotResult, + UIElement, +} from '../backends/types.js'; + +/** Extra reads that wait for an element that just appeared to stop moving. */ +const MAX_SETTLE_READS = 3; + +/** + * Poll snapshots until an element matches `query`. + * + * An element that is on screen at the first read is returned at once. An + * element that appears later can still be animating in (a sheet sliding up), + * so the screen is read again until its frame is the same in two reads in a + * row (at most `MAX_SETTLE_READS` extra reads). Callers tap the returned + * frame, so it must be where the element stops. + * + * @param snapshot - Reads the screen. + * @param query - The element to wait for. + * @param timeoutMs - Maximum time to wait for the element to appear. + * @param intervalMs - Delay between reads while the element is missing. + * @returns The element, at its settled frame when it appeared during the wait. + */ +export async function pollForElement( + snapshot: () => Promise, + query: ElementQuery, + timeoutMs: number, + intervalMs: number, +): Promise { + const start = Date.now(); + const timeLeft = (): boolean => Date.now() - start < timeoutMs; + for (let poll = 0; timeLeft(); poll++) { + const element = findElement((await snapshot()).hierarchy, query); + if (element) { + if (poll === 0) { + return element; + } + const settled = await settle(snapshot, query, element, timeLeft); + if (settled) { + return settled; + } + } + await new Promise((resolve) => setTimeout(resolve, intervalMs)); + } + throw new Error( + `Timed out waiting for element: ${JSON.stringify(query)} (${timeoutMs}ms)`, + ); +} + +/** + * Read the screen until the element's frame stops changing. + * + * @param snapshot - Reads the screen. + * @param query - The element. + * @param first - The element as first found. + * @param timeLeft - Whether the wait's timeout has not passed yet. + * @returns The element at its last frame (still moving when the reads or the + * timeout run out), or null when it disappeared. + */ +async function settle( + snapshot: () => Promise, + query: ElementQuery, + first: UIElement, + timeLeft: () => boolean, +): Promise { + let previous = first; + for (let i = 0; i < MAX_SETTLE_READS && timeLeft(); i++) { + const next = findElement((await snapshot()).hierarchy, query); + if (!next || sameFrame(next, previous)) { + return next; + } + previous = next; + } + return previous; +} From f7d09f7bdad20cad5fd4d4a07e39f1d9e326dd86 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 29 Oct 2026 19:58:00 +0000 Subject: [PATCH 06/33] fix: iOS key presses, back and text clearing idb ui key takes integer HID codes only, so RETURN/HOME/LOCK/DELETE and key-sequence cmd+a all failed. pressButton and dismissKeyboard always threw on iOS, and typeText's clear failed silently (non-strict exec) so retyping appended to the old value. - enter -> ui key 40; home/lock -> ui button HOME|LOCK - back -> throw UNSUPPORTED_ON_IOS (was HOME, which backgrounded the app) - dismissKeyboard presses Return only when a Keyboard element is shown - typeText clears with ui key 4 --command + ui key 42, strict - drop the now-unused non-strict idb path from #idb BREAKING CHANGE: iOS pressButton('back') throws UNSUPPORTED_ON_IOS. --- README.md | 8 +- src/backends/idb-backend.test.ts | 272 ++++++++++++++++--------------- src/backends/idb-backend.ts | 161 +++++++++--------- src/tools/dismiss-keyboard.ts | 4 +- src/tools/press-button.ts | 5 +- 5 files changed, 238 insertions(+), 212 deletions(-) diff --git a/README.md b/README.md index c3a5e9d..10ffa0e 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ The `.device-session` file is typically written by the test runner when it creat | `device_swipe` | Swipe in a direction with optional start coordinates and distance. | | `device_long_press` | Long press an element for context menus or drag initiation. | | `device_wait_for` | Poll until an element matching a query appears. | -| `device_press_button` | Press a device button (home/back/enter/lock). | +| `device_press_button` | Press a device button (home/back/enter/lock; no back on iOS). | ### App & Device Control @@ -228,11 +228,13 @@ Elements are identified by accessibility attributes — not internal refs. Match | `device_app_state` | `idb list-apps` / `simctl listapps` | `dumpsys activity` | `mobile: queryAppState` | | `device_open_app` | `idb launch` / `simctl launch` | `monkey -p` | `mobile: activateApp` | | `device_close_app` | `idb terminate` / `simctl terminate` | `am force-stop` | `mobile: terminateApp` | -| `device_press_button` | `idb ui key` | `input keyevent` | `mobile: pressButton/Key` | -| `device_dismiss_keyboard` | `idb ui key RETURN` | `input keyevent 111` | `mobile: hideKeyboard` | +| `device_press_button` | `idb ui key 40` / `idb ui button`¹ | `input keyevent` | `mobile: pressButton/Key` | +| `device_dismiss_keyboard` | `idb ui key 40` if keyboard shown | `input keyevent 111` | `mobile: hideKeyboard` | | `device_dismiss_alert` | find button + tap | find button + tap | `mobile: accept/dismissAlert` | | `device_logs` | `idb log` | `logcat` | `mobile: getLog` | +¹ `enter` sends HID key 40 (Return); `home` and `lock` use `idb ui button HOME|LOCK`. iOS has no back button, so `back` fails with `UNSUPPORTED_ON_IOS`. `device_type` clears the focused field first with Command+A (`idb ui key 4 --command`) and Backspace (`idb ui key 42`). + #### Android snapshot on continuously-redrawing screens `uiautomator dump` calls `UiAutomation.waitForIdle` internally, which never diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index fa576e8..c3a8f1d 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -1428,6 +1428,100 @@ describe('IdbBackend.snapshot accessibility backend selection', () => { }); }); +describe('IdbBackend keys and buttons', () => { + const udid = 'AAAA1111-BBBB-CCCC-DDDD-EEEE2222FFFF'; + const idb = '/usr/local/bin/idb'; + let backend: IdbBackend; + + const idbCalls = (): unknown[][] => + mockExecStrict.mock.calls + .filter(([cmd, args]) => cmd === idb && args?.[0] === 'ui') + .filter(([, args]) => args?.[1] !== 'describe-all') + .map(([, args]) => args as unknown[]); + + const hierarchyWith = (types: string[]): string => + JSON.stringify([ + { + type: 'Application', + AXLabel: 'MetaMask', + frame: { x: 0, y: 0, width: 402, height: 874 }, + children: types.map((type) => ({ + type, + frame: { x: 0, y: 590, width: 402, height: 284 }, + })), + }, + ]); + + beforeEach(() => { + vi.clearAllMocks(); + connectionState.alive = true; + mockSupportsApi.mockResolvedValue(false); + mockSupportsNested.mockResolvedValue(true); + mockExec.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); + mockExecStrict.mockResolvedValue(''); + backend = new IdbBackend(udid); + }); + + it.each([ + ['enter', ['ui', 'key', '40', '--udid', udid]], + ['home', ['ui', 'button', 'HOME', '--udid', udid]], + ['lock', ['ui', 'button', 'LOCK', '--udid', udid]], + ] as const)('pressButton(%s) sends %j', async (button, args) => { + await backend.pressButton(button); + + expect(mockExecStrict).toHaveBeenCalledWith(idb, args, connectionOptions); + expect(idbCalls()).toStrictEqual([args]); + }); + + it('rejects pressButton(back) without touching the device', async () => { + await expect(backend.pressButton('back')).rejects.toMatchObject({ + code: 'UNSUPPORTED_ON_IOS', + message: expect.stringContaining('iOS has no back button'), + }); + expect(mockExecStrict).not.toHaveBeenCalled(); + expect(connectionMocks.connect).not.toHaveBeenCalled(); + }); + + it('clears with Command+A and Backspace before typing, all strict', async () => { + await backend.typeText('hello world'); + + expect(idbCalls()).toStrictEqual([ + ['ui', 'key', '4', '--command', '--udid', udid], + ['ui', 'key', '42', '--udid', udid], + ['ui', 'text', 'hello world', '--udid', udid], + ]); + expect(mockExec).not.toHaveBeenCalledWith( + idb, + expect.anything(), + expect.anything(), + ); + }); + + it('presses Return to dismiss a visible keyboard', async () => { + mockExecStrict.mockImplementation(async (_cmd, args) => + args?.[1] === 'describe-all' ? hierarchyWith(['Keyboard']) : '', + ); + + await backend.dismissKeyboard(); + + expect(idbCalls()).toStrictEqual([['ui', 'key', '40', '--udid', udid]]); + }); + + it('does nothing when no keyboard is shown', async () => { + // React Native's full-screen KeyboardControllerView is always present + // and must not count as a keyboard. + mockExecStrict.mockImplementation(async (_cmd, args) => + args?.[1] === 'describe-all' + ? hierarchyWith(['KeyboardControllerView']) + : '', + ); + + await backend.dismissKeyboard(); + + expect(idbCalls()).toStrictEqual([]); + }); +}); + describe('IdbBackend companion recovery', () => { const udid = 'AAAA1111-BBBB-CCCC-DDDD-EEEE2222FFFF'; const hidInvalidated = @@ -1643,152 +1737,74 @@ describe('IdbBackend companion recovery', () => { expect(connectionMocks.connect).toHaveBeenCalledTimes(1); }); - it('returns the first non-strict failure when disposed during a command', async () => { - await backend.ensureConnected(); - let finish!: (result: execModule.ExecResult) => void; - mockExec.mockImplementation(async (cmd, args) => - cmd !== 'xcrun' && args?.[1] === 'key-sequence' - ? new Promise((resolve) => { - finish = resolve; - }) - : { exitCode: 0, stdout: '', stderr: '' }, + const keyCalls = (key: string): unknown[][] => + mockExecStrict.mock.calls.filter( + ([, args]) => args?.[1] === 'key' && args?.[2] === key, ); - const typing = backend.typeText('abc').catch((e: unknown) => e); - await vi.waitFor(() => expect(finish).toBeDefined()); - - await backend.dispose(); - finish({ exitCode: 1, stdout: '', stderr: hidInvalidated }); - // The failed key-sequence is returned, not resent; the next idb command - // then fails fast because the backend is disposed. - expect(await typing).toMatchObject({ - message: 'IDB backend has been disposed', - }); - expect( - mockExec.mock.calls.filter(([, args]) => args?.[1] === 'key-sequence'), - ).toHaveLength(1); - expect(connectionMocks.connect).toHaveBeenCalledTimes(1); - }); - - it('does not resend when disposed after joining a newer companion', async () => { + it('resends the typeText clear when the HID connection was invalidated', async () => { await backend.ensureConnected(); - let fail!: (error: Error) => void; - mockExecStrict.mockReturnValueOnce( - new Promise((_resolve, reject) => { - fail = reject; - }), - ); - const tapping = backend.tapCoordinates(1, 2).catch((e: unknown) => e); - await vi.waitFor(() => expect(tapCalls()).toHaveLength(1)); - // Another caller replaces the companion while the tap is in flight. - await backend.reconnect(); - // Dispose exactly when the failed tap checks the new companion, so - // ensureConnected() itself succeeds. - let disposing: Promise | undefined; - Object.defineProperty(connectionState, 'alive', { - configurable: true, - get: (): boolean => { - disposing ??= backend.dispose(); - return true; - }, + let failures = 1; + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.[1] === 'key' && args?.[2] === '4' && failures > 0) { + failures -= 1; + throw new Error(hidInvalidated); + } + return ''; }); - try { - fail(new Error(hidInvalidated)); - expect(await tapping).toMatchObject({ - message: - 'IDB command interrupted: the backend was disposed during the call', - }); - await disposing; - } finally { - Object.defineProperty(connectionState, 'alive', { - configurable: true, - writable: true, - value: true, - }); - } - expect(disposing).toBeDefined(); - expect(tapCalls()).toHaveLength(1); - }); - it('keeps the connect error when cleanup after a failed connect also fails', async () => { - connectionMocks.connect.mockRejectedValueOnce(new Error('startup failed')); - connectionMocks.dispose.mockRejectedValueOnce(new Error('stop failed')); + await backend.typeText('abc'); - await expect(backend.ensureConnected()).rejects.toThrow('startup failed'); - expect(connectionMocks.dispose).toHaveBeenCalledTimes(1); + // Command+A failed undelivered, was resent once on a fresh companion, + // and the rest of the sequence ran. + expect(keyCalls('4')).toHaveLength(2); + expect(keyCalls('42')).toHaveLength(1); + expect(connectionMocks.connect).toHaveBeenCalledTimes(2); }); - it('reports a failed reconnect as IDB_COMPANION_UNAVAILABLE', async () => { + it('rejects typeText instead of appending when the clear cannot be delivered', async () => { await backend.ensureConnected(); - mockExecStrict.mockRejectedValue(new Error(hidInvalidated)); - connectionMocks.connect.mockRejectedValueOnce( - new Error('Private IDB companion exited before readiness (1)'), - ); - - await expect(backend.tapCoordinates(1, 1)).rejects.toMatchObject({ - code: 'IDB_COMPANION_UNAVAILABLE', - message: expect.stringContaining('exited before readiness'), - }); - expect(tapCalls()).toHaveLength(1); - }); - - it('passes other failures through unchanged', async () => { - mockExecStrict.mockRejectedValue(new Error('No such app io.metamask')); - - await expect(backend.tapCoordinates(1, 1)).rejects.toThrow( - 'No such app io.metamask', - ); - expect(connectionMocks.connect).toHaveBeenCalledTimes(1); - }); - - it('keeps non-strict commands non-throwing and retries them once', async () => { - mockExecStrict.mockResolvedValue(''); - mockExec.mockImplementation(async (cmd, args) => { - if (cmd !== 'xcrun' && args?.[1] === 'key-sequence') { - return { exitCode: 1, stdout: '', stderr: hidInvalidated }; + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.[1] === 'key' && args?.[2] === '42') { + throw new Error('StatusCode.UNAVAILABLE'); } - return { exitCode: 0, stdout: '', stderr: '' }; + return ''; }); - expect(await backend.typeText('abc')).toBeUndefined(); - const keySequence = mockExec.mock.calls.filter( - ([, args]) => args?.[1] === 'key-sequence', - ); - expect(keySequence).toHaveLength(2); - }); - - it('returns the first non-strict failure when the reconnect fails', async () => { - await backend.ensureConnected(); - mockExecStrict.mockResolvedValue(''); - mockExec.mockImplementation(async (cmd, args) => - cmd !== 'xcrun' && args?.[1] === 'key-sequence' - ? { exitCode: 1, stdout: '', stderr: hidInvalidated } - : { exitCode: 0, stdout: '', stderr: '' }, - ); - connectionMocks.connect.mockRejectedValueOnce(new Error('no companion')); - - // The failed key-sequence result is returned (not resent); the next - // command starts a fresh companion first, and the strict `ui text` succeeds. - expect(await backend.typeText('abc')).toBeUndefined(); + await expect(backend.typeText('abc')).rejects.toMatchObject({ + code: 'IDB_COMPANION_UNAVAILABLE', + message: expect.stringContaining('may have run'), + }); + // Backspace is mutating with uncertain delivery: not resent, and the + // text is never typed onto the old value. + expect(keyCalls('42')).toHaveLength(1); expect( - mockExec.mock.calls.filter(([, args]) => args?.[1] === 'key-sequence'), - ).toHaveLength(1); - expect(connectionMocks.connect).toHaveBeenCalledTimes(3); + mockExecStrict.mock.calls.filter(([, args]) => args?.[1] === 'text'), + ).toHaveLength(0); }); - it('returns a non-strict failure without resending when delivery is uncertain', async () => { - mockExecStrict.mockResolvedValue(''); - mockExec.mockImplementation(async (cmd, args) => - cmd !== 'xcrun' && args?.[1] === 'key' - ? { exitCode: 1, stdout: '', stderr: 'StatusCode.UNAVAILABLE' } - : { exitCode: 0, stdout: '', stderr: '' }, + it('reports disposal during the typeText clear as an interruption', async () => { + await backend.ensureConnected(); + let fail!: (error: Error) => void; + mockExecStrict.mockImplementation(async (_cmd, args) => + args?.[1] === 'key' + ? new Promise((_resolve, reject) => { + fail = reject; + }) + : '', ); + const typing = backend.typeText('abc').catch((e: unknown) => e); + await vi.waitFor(() => expect(fail).toBeDefined()); - await backend.typeText('abc'); + await backend.dispose(); + fail(new Error(hidInvalidated)); - expect( - mockExec.mock.calls.filter(([, args]) => args?.[1] === 'key'), - ).toHaveLength(1); + expect(await typing).toMatchObject({ + message: + 'IDB command interrupted: the backend was disposed during the call', + }); + expect(keyCalls('4')).toHaveLength(1); + expect(connectionMocks.connect).toHaveBeenCalledTimes(1); }); it('shares one reconnect between concurrent failing calls', async () => { diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index 2fbb16d..1c7d542 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -27,7 +27,6 @@ import { computeSwipeEnd, } from '../utils/element.js'; import { execStrict, exec } from '../utils/exec.js'; -import type { ExecResult } from '../utils/exec.js'; import { hardenArtifactFile, resolveArtifactPath, @@ -41,6 +40,33 @@ import { import { stopChildProcess } from '../utils/stop-child-process.js'; import { pollForElement } from '../utils/wait-for-element.js'; +/** + * USB HID keyboard usage IDs. `idb ui key` takes these integers, not key + * names (idb 1.7: "argument key: invalid int value: 'RETURN'"). + */ +const HID_KEY = { + a: 4, + return: 40, + backspace: 42, +} as const; + +/** + * Whether the software keyboard is on screen: an element whose type is + * exactly `Keyboard`. (React Native's `KeyboardControllerView` is a + * full-screen container that is always present, so a substring match on the + * type is wrong.) + * + * @param elements - The snapshot hierarchy. + * @returns True when a keyboard element is present. + */ +function hasKeyboard(elements: UIElement[]): boolean { + return elements.some( + (element) => + element.type === 'Keyboard' || + (element.children !== undefined && hasKeyboard(element.children)), + ); +} + /** `idb describe --json` printed something that is not JSON. */ class InvalidDescribeJsonError extends Error { constructor(udid: string, raw: string) { @@ -203,25 +229,8 @@ export class IdbBackend implements DeviceBackend { if (command !== this.#idbPath) { return execStrict(command, args); } - return this.#idb( - args, - async () => execStrict(command, args, { env: this.#connection.env }), - () => undefined, - true, - ); - } - - async #exec(command: string, args: string[]): Promise { - if (command !== this.#idbPath) { - return exec(command, args); - } - // Non-strict callers keep their semantics: a failure that survives the - // retry is returned, not thrown. - return this.#idb( - args, - async () => exec(command, args, { env: this.#connection.env }), - (result) => (result.exitCode === 0 ? undefined : result.stderr), - false, + return this.#idb(args, async () => + execStrict(command, args, { env: this.#connection.env }), ); } @@ -241,24 +250,17 @@ export class IdbBackend implements DeviceBackend { * is never resent after the backend is disposed. * * @param args - The idb arguments (used to decide whether a resend is safe). - * @param run - Sends the command once. - * @param failureOf - Failure text of a resolved run, if it failed. - * @param strict - Throw a typed error when recovery does not help. - * @returns The result of the first successful (or unrecoverable) run. + * @param run - Sends the command once; rejects when it fails. + * @returns The output of the first successful run. */ - async #idb( - args: string[], - run: () => Promise, - failureOf: (value: Result) => string | undefined, - strict: boolean, - ): Promise { + async #idb(args: string[], run: () => Promise): Promise { if (!this.#connected || !this.#connection.alive) { // The companion died (or a reconnect failed) since this method's own // ensureConnected(); start a fresh one before sending. await this.ensureConnected(); } const generation = this.#generation; - const first = await attempt(run, failureOf); + const first = await attempt(run); const failure = first.text === undefined ? undefined : classifyIdbFailure(first.text); if (!failure) { @@ -274,10 +276,7 @@ export class IdbBackend implements DeviceBackend { } } catch (error) { if (this.#disposed) { - return interrupted(first, strict); - } - if (!strict) { - return first.settle(); + throw interrupted(first); } throw new IdbUnavailableError( 'IDB_COMPANION_UNAVAILABLE', @@ -288,12 +287,9 @@ export class IdbBackend implements DeviceBackend { } if (this.#disposed) { // Disposal started while another call's reconnect was finishing. - return interrupted(first, strict); + throw interrupted(first); } if (!resend) { - if (!strict) { - return first.settle(); - } throw new IdbUnavailableError( failure.code, this.#udid, @@ -304,10 +300,10 @@ export class IdbBackend implements DeviceBackend { }, ); } - const second = await attempt(run, failureOf); + const second = await attempt(run); const again = second.text === undefined ? undefined : classifyIdbFailure(second.text); - if (!again || !strict) { + if (!again) { return second.settle(); } throw new IdbUnavailableError(again.code, this.#udid, second.text ?? '', { @@ -327,7 +323,7 @@ export class IdbBackend implements DeviceBackend { */ async #enableSimulatorAccessibility(): Promise { try { - await this.#exec('xcrun', [ + await exec('xcrun', [ 'simctl', 'spawn', this.#udid, @@ -554,20 +550,29 @@ export class IdbBackend implements DeviceBackend { ]); } + /** + * Replaces the content of the focused text field with `text`. + * + * Clears first with select-all (Command+A) and Backspace, both through + * strict execution so a failed clear rejects instead of appending to the + * old value. On an empty field the two keys do nothing. + * + * @param text - The text to type. + */ async typeText(text: string): Promise { await this.ensureConnected(); - await this.#exec(this.#idbPath, [ + await this.#execStrict(this.#idbPath, [ 'ui', - 'key-sequence', - '--', - 'cmd+a', + 'key', + String(HID_KEY.a), + '--command', '--udid', this.#udid, ]); - await this.#exec(this.#idbPath, [ + await this.#execStrict(this.#idbPath, [ 'ui', 'key', - 'DELETE', + String(HID_KEY.backspace), '--udid', this.#udid, ]); @@ -686,11 +691,7 @@ export class IdbBackend implements DeviceBackend { } async #getAppStateViaSimctl(bundleId: string): Promise { - const result = await this.#exec('xcrun', [ - 'simctl', - 'listapps', - this.#udid, - ]); + const result = await exec('xcrun', ['simctl', 'listapps', this.#udid]); if (result.exitCode === 0 && result.stdout.includes(bundleId)) { return { bundleId, state: 'Running' }; } @@ -771,28 +772,37 @@ export class IdbBackend implements DeviceBackend { } async pressButton(button: DeviceButton): Promise { + if (button === 'back') { + throw Object.assign( + new Error( + "UNSUPPORTED_ON_IOS: iOS has no back button. Tap the screen's own " + + 'back control (usually top left) instead.', + ), + { code: 'UNSUPPORTED_ON_IOS' }, + ); + } await this.ensureConnected(); - const keyMap: Record = { - home: 'HOME', - lock: 'LOCK', - back: 'HOME', - enter: 'RETURN', - }; - await this.#execStrict(this.#idbPath, [ - 'ui', - 'key', - keyMap[button], - '--udid', - this.#udid, - ]); + const args = + button === 'enter' + ? ['ui', 'key', String(HID_KEY.return)] + : ['ui', 'button', button === 'home' ? 'HOME' : 'LOCK']; + await this.#execStrict(this.#idbPath, [...args, '--udid', this.#udid]); } + /** + * Hides the software keyboard by pressing Return, and does nothing when no + * keyboard is shown. Return can also submit a single-field form. + */ async dismissKeyboard(): Promise { await this.ensureConnected(); + const { hierarchy } = await this.snapshot(); + if (!hasKeyboard(hierarchy)) { + return; + } await this.#execStrict(this.#idbPath, [ 'ui', 'key', - 'RETURN', + String(HID_KEY.return), '--udid', this.#udid, ]); @@ -1031,11 +1041,10 @@ type Attempt = { async function attempt( run: () => Promise, - failureOf: (value: Result) => string | undefined, ): Promise> { try { const value = await run(); - return { text: failureOf(value), error: undefined, settle: () => value }; + return { text: undefined, error: undefined, settle: () => value }; } catch (error) { return { text: error instanceof Error ? error.message : String(error), @@ -1048,19 +1057,15 @@ async function attempt( } /** - * Settle a failed first attempt when the backend was disposed before the - * recovery could run. Disposal is a teardown, not a device fault, so the + * The error for a failed first attempt when the backend was disposed before + * the recovery could run. Disposal is a teardown, not a device fault, so the * command is not resent and no device remediation is given. * * @param first - The failed first attempt. - * @param strict - Throw instead of returning the failed result. - * @returns The first result, for non-strict callers. + * @returns The error to throw. */ -function interrupted(first: Attempt, strict: boolean): Result { - if (!strict) { - return first.settle(); - } - throw new Error( +function interrupted(first: Attempt): Error { + return new Error( 'IDB command interrupted: the backend was disposed during the call', { cause: first.error }, ); diff --git a/src/tools/dismiss-keyboard.ts b/src/tools/dismiss-keyboard.ts index 25adbae..a39fe10 100644 --- a/src/tools/dismiss-keyboard.ts +++ b/src/tools/dismiss-keyboard.ts @@ -13,7 +13,9 @@ export function registerDismissKeyboardTool( title: 'Dismiss Keyboard', description: 'Hide the on-screen keyboard. Call after typing to reveal elements ' + - 'that may be obscured by the keyboard.', + 'that may be obscured by the keyboard. On iOS this presses Return ' + + 'when a keyboard is shown (which can submit a single-field form) ' + + 'and does nothing otherwise.', inputSchema: {}, }, async () => { diff --git a/src/tools/press-button.ts b/src/tools/press-button.ts index 077462a..2d67a7f 100644 --- a/src/tools/press-button.ts +++ b/src/tools/press-button.ts @@ -13,8 +13,9 @@ export function registerPressButtonTool( { title: 'Press Button', description: - 'Press a physical device button. ' + - 'Note: iOS has no back button — "back" maps to home.', + 'Press a device button. "enter" sends the Return key and can ' + + 'submit a form. iOS has no back button: "back" fails with ' + + "UNSUPPORTED_ON_IOS; tap the screen's back control instead.", inputSchema: { button: z .enum(['home', 'back', 'enter', 'lock']) From f317c8f297048af3ac6a3db9683fe7fcdb32428b Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 6 Nov 2026 09:39:47 -0600 Subject: [PATCH 07/33] refactor: drop pass-through #exec and restore dropped recovery tests - inline the now pass-through #exec wrapper (simctl calls use exec directly) - drop pressButton JSDoc that restates the code and tool description - restore four companion-recovery tests unrelated to non-strict exec that were removed with the non-strict ones - drop the typeText disposal test, which repeats the existing disposal-during-a-command test --- src/backends/idb-backend.test.ts | 95 ++++++++++++++++++++++++-------- 1 file changed, 71 insertions(+), 24 deletions(-) diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index c3a8f1d..49c1e14 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -1737,6 +1737,77 @@ describe('IdbBackend companion recovery', () => { expect(connectionMocks.connect).toHaveBeenCalledTimes(1); }); + it('does not resend when disposed after joining a newer companion', async () => { + await backend.ensureConnected(); + let fail!: (error: Error) => void; + mockExecStrict.mockReturnValueOnce( + new Promise((_resolve, reject) => { + fail = reject; + }), + ); + const tapping = backend.tapCoordinates(1, 2).catch((e: unknown) => e); + await vi.waitFor(() => expect(tapCalls()).toHaveLength(1)); + // Another caller replaces the companion while the tap is in flight. + await backend.reconnect(); + // Dispose exactly when the failed tap checks the new companion, so + // ensureConnected() itself succeeds. + let disposing: Promise | undefined; + Object.defineProperty(connectionState, 'alive', { + configurable: true, + get: (): boolean => { + disposing ??= backend.dispose(); + return true; + }, + }); + try { + fail(new Error(hidInvalidated)); + expect(await tapping).toMatchObject({ + message: + 'IDB command interrupted: the backend was disposed during the call', + }); + await disposing; + } finally { + Object.defineProperty(connectionState, 'alive', { + configurable: true, + writable: true, + value: true, + }); + } + expect(disposing).toBeDefined(); + expect(tapCalls()).toHaveLength(1); + }); + + it('keeps the connect error when cleanup after a failed connect also fails', async () => { + connectionMocks.connect.mockRejectedValueOnce(new Error('startup failed')); + connectionMocks.dispose.mockRejectedValueOnce(new Error('stop failed')); + + await expect(backend.ensureConnected()).rejects.toThrow('startup failed'); + expect(connectionMocks.dispose).toHaveBeenCalledTimes(1); + }); + + it('reports a failed reconnect as IDB_COMPANION_UNAVAILABLE', async () => { + await backend.ensureConnected(); + mockExecStrict.mockRejectedValue(new Error(hidInvalidated)); + connectionMocks.connect.mockRejectedValueOnce( + new Error('Private IDB companion exited before readiness (1)'), + ); + + await expect(backend.tapCoordinates(1, 1)).rejects.toMatchObject({ + code: 'IDB_COMPANION_UNAVAILABLE', + message: expect.stringContaining('exited before readiness'), + }); + expect(tapCalls()).toHaveLength(1); + }); + + it('passes other failures through unchanged', async () => { + mockExecStrict.mockRejectedValue(new Error('No such app io.metamask')); + + await expect(backend.tapCoordinates(1, 1)).rejects.toThrow( + 'No such app io.metamask', + ); + expect(connectionMocks.connect).toHaveBeenCalledTimes(1); + }); + const keyCalls = (key: string): unknown[][] => mockExecStrict.mock.calls.filter( ([, args]) => args?.[1] === 'key' && args?.[2] === key, @@ -1783,30 +1854,6 @@ describe('IdbBackend companion recovery', () => { ).toHaveLength(0); }); - it('reports disposal during the typeText clear as an interruption', async () => { - await backend.ensureConnected(); - let fail!: (error: Error) => void; - mockExecStrict.mockImplementation(async (_cmd, args) => - args?.[1] === 'key' - ? new Promise((_resolve, reject) => { - fail = reject; - }) - : '', - ); - const typing = backend.typeText('abc').catch((e: unknown) => e); - await vi.waitFor(() => expect(fail).toBeDefined()); - - await backend.dispose(); - fail(new Error(hidInvalidated)); - - expect(await typing).toMatchObject({ - message: - 'IDB command interrupted: the backend was disposed during the call', - }); - expect(keyCalls('4')).toHaveLength(1); - expect(connectionMocks.connect).toHaveBeenCalledTimes(1); - }); - it('shares one reconnect between concurrent failing calls', async () => { await backend.ensureConnected(); let failures = 2; From 0ebd7a696971b988a8e875d35063ae1c68bc95d9 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 29 Oct 2026 23:55:50 +0000 Subject: [PATCH 08/33] fix!: scrollToElement succeeds only when the element is in the viewport React Native keeps off-screen rows in the accessibility tree, so scrollToElement returned as soon as findElement matched, often after zero swipes with the element below the fold, and the next tap failed with 'Element is outside the viewport'. - success = enough of the frame inside the viewport (4% top/bottom inset; half the height, or 44 pt for tall elements); a fixed element that a swipe did not move is accepted when it intersects the viewport - read the screen until it settles after a swipe (momentum) - return { element, swipes, inViewport: true }; throw ScrollToElementError ELEMENT_NOT_FOUND / ELEMENT_NOT_IN_VIEWPORT (swipes + last frame) - direction 'auto' (default): finger direction from the element's position; searches toward content below first, turns once at the end - Android/Appium: scroll swipes from the real screen middle BREAKING CHANGE: scrollToElement returns ScrollToElementResult instead of UIElement; the default direction is 'auto' instead of 'down'. --- README.md | 19 +- src/backends/adb-backend.ts | 53 ++++-- src/backends/appium-backend.ts | 53 ++++-- src/backends/idb-backend.test.ts | 6 +- src/backends/idb-backend.ts | 33 ++-- src/backends/index.ts | 6 +- src/backends/types.ts | 27 ++- src/index.ts | 4 + src/tools/scroll-to-element.ts | 20 +- src/utils/scroll.test.ts | 302 +++++++++++++++++++++++++++++++ src/utils/scroll.ts | 253 ++++++++++++++++++++++++++ 11 files changed, 698 insertions(+), 78 deletions(-) create mode 100644 src/utils/scroll.test.ts create mode 100644 src/utils/scroll.ts diff --git a/README.md b/README.md index 10ffa0e..c2950d1 100644 --- a/README.md +++ b/README.md @@ -176,15 +176,16 @@ The `.device-session` file is typically written by the test runner when it creat ### Interaction -| Tool | Description | -| ------------------------ | ------------------------------------------------------------------ | -| `device_tap_element` | Find an element by label/identifier/text/type and tap its center. | -| `device_tap_coordinates` | Tap at exact screen coordinates. Last resort when queries fail. | -| `device_type` | Type text into the currently focused input field. | -| `device_swipe` | Swipe in a direction with optional start coordinates and distance. | -| `device_long_press` | Long press an element for context menus or drag initiation. | -| `device_wait_for` | Poll until an element matching a query appears. | -| `device_press_button` | Press a device button (home/back/enter/lock; no back on iOS). | +| Tool | Description | +| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `device_tap_element` | Find an element by label/identifier/text/type and tap its center. | +| `device_tap_coordinates` | Tap at exact screen coordinates. Last resort when queries fail. | +| `device_type` | Type text into the currently focused input field. | +| `device_swipe` | Swipe in a direction with optional start coordinates and distance. | +| `device_long_press` | Long press an element for context menus or drag initiation. | +| `device_scroll_to_element` | Swipe until an element is inside the viewport (not only in the UI tree); reports the swipe count. `direction` is the finger direction (`up` reveals content below); default `auto` picks it from the element's position. | +| `device_wait_for` | Poll until an element matching a query appears. | +| `device_press_button` | Press a device button (home/back/enter/lock; no back on iOS). | ### App & Device Control diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index 04ac7d4..357f5f1 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -43,6 +43,8 @@ import type { ScreenshotFileResult, ScreenshotOptions, ScreenshotResult, + ScrollDirection, + ScrollToElementResult, SnapshotResult, TapElementOptions, TapResult, @@ -63,6 +65,7 @@ import { hardenArtifactFile, resolveArtifactPath, } from '../utils/output-path.js'; +import { scrollUntilInViewport } from '../utils/scroll.js'; import { pollForElement } from '../utils/wait-for-element.js'; // `uiautomator dump` exits 0 and prints its success banner even when it fails, so @@ -895,26 +898,40 @@ export class AdbBackend implements DeviceBackend { async scrollToElement( query: ElementQuery, - direction: 'up' | 'down' = 'down', + direction: ScrollDirection = 'auto', maxAttempts = 10, - ): Promise { - let previousRaw = ''; + ): Promise { + const windowSize = await this.getWindowSize(); + return scrollUntilInViewport( + { + snapshot: async () => this.snapshot(), + windowSize, + swipe: async (finger) => this.#scrollSwipe(finger, windowSize), + }, + query, + direction, + maxAttempts, + ); + } - for (let i = 0; i < maxAttempts; i++) { - const snap = await this.snapshot(); - const element = findElement(snap.hierarchy, query); - if (element) { - return element; - } - if (snap.raw === previousRaw) { - break; - } - previousRaw = snap.raw; - await this.swipe(direction); - } - throw new Error( - `Element not found after scrolling: ${JSON.stringify(query)}\n` + - 'Use device_snapshot to inspect the current UI hierarchy.', + /** + * One scroll gesture from the middle of the screen over 40% of its height + * (the iOS backend's default), so the swipe matches the real screen size. + * + * @param finger - Finger direction. + * @param windowSize - The screen size, in the frame units. + * @param windowSize.width - Viewport width. + * @param windowSize.height - Viewport height. + */ + async #scrollSwipe( + finger: 'up' | 'down', + { width, height }: WindowSize, + ): Promise { + await this.swipe( + finger, + Math.round(width / 2), + Math.round(height / 2), + Math.round(height * 0.4), ); } diff --git a/src/backends/appium-backend.ts b/src/backends/appium-backend.ts index 3a8bc3d..78710c0 100644 --- a/src/backends/appium-backend.ts +++ b/src/backends/appium-backend.ts @@ -10,6 +10,8 @@ import type { ScreenshotFileResult, ScreenshotOptions, ScreenshotResult, + ScrollDirection, + ScrollToElementResult, SnapshotResult, TapElementOptions, TapResult, @@ -26,6 +28,7 @@ import { resolveArtifactPath, writeArtifactFile, } from '../utils/output-path.js'; +import { scrollUntilInViewport } from '../utils/scroll.js'; import { pollForElement } from '../utils/wait-for-element.js'; export class AppiumBackend implements DeviceBackend { @@ -420,26 +423,40 @@ export class AppiumBackend implements DeviceBackend { async scrollToElement( query: ElementQuery, - direction: 'up' | 'down' = 'down', + direction: ScrollDirection = 'auto', maxAttempts = 10, - ): Promise { - let previousRaw = ''; + ): Promise { + const windowSize = await this.getWindowSize(); + return scrollUntilInViewport( + { + snapshot: async () => this.snapshot(), + windowSize, + swipe: async (finger) => this.#scrollSwipe(finger, windowSize), + }, + query, + direction, + maxAttempts, + ); + } - for (let i = 0; i < maxAttempts; i++) { - const snap = await this.snapshot(); - const element = findElement(snap.hierarchy, query); - if (element) { - return element; - } - if (snap.raw === previousRaw) { - break; - } - previousRaw = snap.raw; - await this.swipe(direction); - } - throw new Error( - `Element not found after scrolling: ${JSON.stringify(query)}\n` + - 'Use device_snapshot to inspect the current UI hierarchy.', + /** + * One scroll gesture from the middle of the screen over 40% of its height + * (the iOS backend's default), so the swipe matches the real screen size. + * + * @param finger - Finger direction. + * @param windowSize - The screen size, in the frame units. + * @param windowSize.width - Viewport width. + * @param windowSize.height - Viewport height. + */ + async #scrollSwipe( + finger: 'up' | 'down', + { width, height }: WindowSize, + ): Promise { + await this.swipe( + finger, + Math.round(width / 2), + Math.round(height / 2), + Math.round(height * 0.4), ); } diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index 49c1e14..97e94ff 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -701,9 +701,9 @@ describe('IdbBackend.swipe and getWindowSize', () => { snapshotCount += 1; return JSON.stringify([ { - type: snapshotCount === 3 ? 'Button' : 'StaticText', - AXLabel: snapshotCount === 3 ? 'Settings' : `Page ${snapshotCount}`, - frame: { x: 10, y: 20, width: 100, height: 44 }, + type: snapshotCount >= 3 ? 'Button' : 'StaticText', + AXLabel: snapshotCount >= 3 ? 'Settings' : `Page ${snapshotCount}`, + frame: { x: 10, y: 200, width: 100, height: 44 }, enabled: true, }, ]); diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index 1c7d542..8ce6093 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -14,6 +14,8 @@ import type { ScreenshotFileResult, ScreenshotOptions, ScreenshotResult, + ScrollDirection, + ScrollToElementResult, SnapshotResult, TapElementOptions, TapResult, @@ -37,6 +39,7 @@ import { idbSupportsNestedDescribe, resolveIdbPath, } from '../utils/platform.js'; +import { scrollUntilInViewport } from '../utils/scroll.js'; import { stopChildProcess } from '../utils/stop-child-process.js'; import { pollForElement } from '../utils/wait-for-element.js'; @@ -885,28 +888,20 @@ export class IdbBackend implements DeviceBackend { async scrollToElement( query: ElementQuery, - direction: 'up' | 'down' = 'down', + direction: ScrollDirection = 'auto', maxAttempts = 10, - ): Promise { + ): Promise { await this.ensureConnected(); const windowSize = await this.getWindowSize(); - let previousRaw = ''; - - for (let i = 0; i < maxAttempts; i++) { - const snap = await this.snapshot(); - const element = findElement(snap.hierarchy, query); - if (element) { - return element; - } - if (snap.raw === previousRaw) { - break; - } - previousRaw = snap.raw; - await this.#swipe(direction, windowSize); - } - throw new Error( - `Element not found after scrolling: ${JSON.stringify(query)}\n` + - 'Use device_snapshot to inspect the current UI hierarchy.', + return scrollUntilInViewport( + { + snapshot: async () => this.snapshot(), + windowSize, + swipe: async (finger) => this.#swipe(finger, windowSize), + }, + query, + direction, + maxAttempts, ); } diff --git a/src/backends/index.ts b/src/backends/index.ts index 8d4e98a..562e6b0 100644 --- a/src/backends/index.ts +++ b/src/backends/index.ts @@ -15,6 +15,8 @@ import type { ScreenshotFileResult, ScreenshotOptions, ScreenshotResult, + ScrollDirection, + ScrollToElementResult, SnapshotResult, TapElementOptions, TapResult, @@ -304,9 +306,9 @@ export function createLazyBackend( async scrollToElement( query: ElementQuery, - direction?: 'up' | 'down', + direction?: ScrollDirection, maxAttempts?: number, - ): Promise { + ): Promise { return (await resolve()).scrollToElement(query, direction, maxAttempts); }, diff --git a/src/backends/types.ts b/src/backends/types.ts index 0eea721..d1d7c49 100644 --- a/src/backends/types.ts +++ b/src/backends/types.ts @@ -100,6 +100,17 @@ export type ElementQuery = { export type DeviceButton = 'home' | 'back' | 'enter' | 'lock'; +/** Finger direction of a scroll gesture, or `auto` (from the target's position). */ +export type ScrollDirection = 'up' | 'down' | 'auto'; + +export type ScrollToElementResult = { + /** The element as last read, with its in-view frame. */ + element: UIElement; + /** Swipes performed (0 when the element was already in view). */ + swipes: number; + inViewport: true; +}; + export type WindowSize = { width: number; height: number; @@ -197,11 +208,23 @@ export type DeviceBackend = { longPress(query: ElementQuery, durationMs?: number): Promise; + /** + * Swipe until the element is in the viewport (not only in the UI tree). + * + * @param query - The element to bring into view. + * @param direction - Finger direction (`up` reveals content below), or + * `auto` (default): from the element's position, searching downward first + * when it is not in the tree yet. + * @param maxAttempts - Maximum number of swipes (default 10). + * @returns The element as last read and the number of swipes. + * @throws {ScrollToElementError} `ELEMENT_NOT_FOUND` or + * `ELEMENT_NOT_IN_VIEWPORT` (with the last frame). + */ scrollToElement( query: ElementQuery, - direction?: 'up' | 'down', + direction?: ScrollDirection, maxAttempts?: number, - ): Promise; + ): Promise; getAlertText(): Promise; diff --git a/src/index.ts b/src/index.ts index b3f4a90..21ea0c3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,6 +9,8 @@ export { createMcpServer } from './server.js'; export { detectAllDevices, MultipleDevicesError } from './utils/platform.js'; export { IdbUnavailableError } from './backends/idb-errors.js'; +export { ScrollToElementError } from './utils/scroll.js'; +export type { ScrollToElementErrorCode } from './utils/scroll.js'; export type { IdbErrorCode } from './backends/idb-errors.js'; export type { DetectedDevice } from './utils/platform.js'; @@ -23,6 +25,8 @@ export type { ScreenshotResult, ScreenshotFileResult, ScreenshotOptions, + ScrollDirection, + ScrollToElementResult, LogsResult, TapElementOptions, TapResult, diff --git a/src/tools/scroll-to-element.ts b/src/tools/scroll-to-element.ts index 0046db1..a8726f9 100644 --- a/src/tools/scroll-to-element.ts +++ b/src/tools/scroll-to-element.ts @@ -13,8 +13,10 @@ export function registerScrollToElementTool( { title: 'Scroll To Element', description: - 'Scroll the screen until an element matching the query becomes visible. ' + - 'Combines scrolling and element search into one atomic operation. ' + + 'Swipe until an element matching the query is inside the viewport ' + + '(being in the UI tree is not enough), and report how many swipes ' + + 'it took. Fails when the element is not in view after maxAttempts ' + + 'swipes or the screen stops moving. ' + 'Specify at least one of: label, identifier, text, type.', inputSchema: { label: z.string().optional().describe('Accessibility label to match'), @@ -25,18 +27,22 @@ export function registerScrollToElementTool( text: z.string().optional().describe('Text content to match'), type: z.string().optional().describe('Element type to match'), direction: z - .enum(['up', 'down']) + .enum(['auto', 'up', 'down']) .optional() - .describe('Scroll direction (default: down)'), + .describe( + 'Finger direction: "up" reveals content below, "down" content ' + + 'above. Default "auto": from where the element is, searching ' + + 'downward first when it is not in the UI tree yet.', + ), maxAttempts: z .number() .optional() - .describe('Maximum scroll attempts (default: 10)'), + .describe('Maximum number of swipes (default: 10)'), }, }, async ({ label, identifier, text, type, direction, maxAttempts }) => { try { - const element = await backend.scrollToElement( + const { element, swipes } = await backend.scrollToElement( { label, identifier, text, type }, direction, maxAttempts, @@ -46,7 +52,7 @@ export function registerScrollToElementTool( { type: 'text' as const, text: [ - `Found element after scrolling:`, + `Element in viewport after ${swipes} swipe(s):`, ` type: ${element.type}`, element.label ? ` label: "${element.label}"` : null, element.identifier ? ` id: "${element.identifier}"` : null, diff --git a/src/utils/scroll.test.ts b/src/utils/scroll.test.ts new file mode 100644 index 0000000..20c5b59 --- /dev/null +++ b/src/utils/scroll.test.ts @@ -0,0 +1,302 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + isInViewport, + scrollUntilInViewport, + ScrollToElementError, + swipeToward, +} from './scroll.js'; +import type { SnapshotResult, UIElement } from '../backends/types.js'; + +const windowSize = { width: 402, height: 874 }; + +const node = (label: string, y: number, height = 24): UIElement => ({ + type: 'StaticText', + label, + frame: { x: 16, y, width: 370, height }, + enabled: true, +}); + +const snap = (elements: UIElement[]): SnapshotResult => ({ + hierarchy: elements, + raw: JSON.stringify(elements), +}); + +/** + * A scrolling list: rows at fixed content offsets, and a scroll offset that a + * finger-up swipe increases by `step` (clamped to [0, maxOffset]). + * + * @param rows - Content rows: label and content y. + * @param options - Scroll step, end of the list, fixed (non-scrolling) rows. + * @param options.step - Points moved per swipe. + * @param options.maxOffset - Largest scroll offset (end of the list). + * @param options.fixed - Rows that do not scroll (e.g. a footer button). + * @returns Backend stubs and the swipe log. + */ +function list( + rows: [string, number][], + { + step = 350, + maxOffset = 2000, + fixed = [] as UIElement[], + }: { step?: number; maxOffset?: number; fixed?: UIElement[] } = {}, +): { + deps: Parameters[0]; + swipes: string[]; +} { + let offset = 0; + const swipes: string[] = []; + return { + swipes, + deps: { + windowSize, + snapshot: vi.fn(async () => + snap([...rows.map(([label, y]) => node(label, y - offset)), ...fixed]), + ), + swipe: vi.fn(async (finger: 'up' | 'down') => { + swipes.push(finger); + offset = Math.min( + maxOffset, + Math.max(0, offset + (finger === 'up' ? step : -step)), + ); + }), + }, + }; +} + +describe('isInViewport', () => { + it('rejects an element that is in the tree but below the fold', () => { + expect(isInViewport(node('Account icon', 996), windowSize)).toBe(false); + }); + + it('rejects an element hidden under the bottom inset', () => { + // 874 * 0.96 = 839: only 9 of 24 pt are above the inset. + expect(isInViewport(node('Row', 830), windowSize)).toBe(false); + }); + + it('accepts an element that is fully in view', () => { + expect(isInViewport(node('Row', 400), windowSize)).toBe(true); + }); + + it('accepts a tall element once 44 pt of it are in view', () => { + expect(isInViewport(node('Card', 780, 600), windowSize)).toBe(true); + expect(isInViewport(node('Card', 800, 600), windowSize)).toBe(false); + }); + + it('rejects an element outside the viewport horizontally', () => { + const element = { + ...node('Row', 400), + frame: { x: 500, y: 400, width: 100, height: 24 }, + }; + expect(isInViewport(element, windowSize)).toBe(false); + }); +}); + +describe('swipeToward', () => { + it('swipes up (reveals content below) for an element below the middle', () => { + expect(swipeToward(node('Row', 996), windowSize)).toBe('up'); + }); + + it('swipes down (reveals content above) for an element above the middle', () => { + expect(swipeToward(node('Row', -300), windowSize)).toBe('down'); + }); +}); + +describe('scrollUntilInViewport', () => { + it('does not swipe when the element is already in view', async () => { + const { deps, swipes } = list([['Account icon', 400]]); + + const result = await scrollUntilInViewport( + deps, + { label: 'Account icon' }, + 'auto', + 10, + ); + + expect(result).toMatchObject({ swipes: 0, inViewport: true }); + expect(swipes).toStrictEqual([]); + }); + + it('swipes when the element is in the tree but off-screen, and returns it in view', async () => { + // The 2026-10-28 bug: found in the tree at y=996, returned after 0 swipes. + const { deps, swipes } = list([['Account icon', 996]]); + + const result = await scrollUntilInViewport( + deps, + { label: 'Account icon' }, + 'auto', + 10, + ); + + expect(swipes).toStrictEqual(['up']); + expect(result.swipes).toBe(1); + expect(result.inViewport).toBe(true); + expect(result.element.frame.y).toBe(646); + expect(isInViewport(result.element, windowSize)).toBe(true); + }); + + it('auto swipes down for an element above the viewport', async () => { + const { deps, swipes } = list([['Header', 400]]); + // Start scrolled down by 700 pt: Header is at y=-300, above the viewport. + await deps.swipe('up'); + await deps.swipe('up'); + swipes.length = 0; + + const result = await scrollUntilInViewport( + deps, + { label: 'Header' }, + 'auto', + 10, + ); + + expect(swipes[0]).toBe('down'); + expect(result.inViewport).toBe(true); + }); + + it('auto searches below first, then turns around when the list ends', async () => { + // The element is not in the tree until scrolled back to the top. + let offset = 700; + const swipes: string[] = []; + const deps = { + windowSize, + snapshot: vi.fn(async () => + snap(offset === 0 ? [node('Top', 200)] : [node(`at ${offset}`, 400)]), + ), + swipe: vi.fn(async (finger: 'up' | 'down') => { + swipes.push(finger); + offset = Math.min( + 700, + Math.max(0, offset + (finger === 'up' ? 350 : -350)), + ); + }), + }; + + const result = await scrollUntilInViewport( + deps, + { label: 'Top' }, + 'auto', + 10, + ); + + // up (already at the end: no change) -> turn -> down, down. + expect(swipes).toStrictEqual(['up', 'down', 'down']); + expect(result).toMatchObject({ swipes: 3, inViewport: true }); + }); + + it('honours an explicit finger direction', async () => { + const { deps, swipes } = list([['Account icon', 996]]); + + await expect( + scrollUntilInViewport(deps, { label: 'Account icon' }, 'down', 3), + ).rejects.toMatchObject({ + code: 'ELEMENT_NOT_IN_VIEWPORT', + frame: { y: 996 }, + }); + // Finger down at the top of the list moves nothing: stop after one swipe. + expect(swipes).toStrictEqual(['down']); + }); + + it('fails with the last frame when the list ends before the element is in view', async () => { + const { deps, swipes } = list([['Footer note', 2000]], { maxOffset: 500 }); + + const error = await scrollUntilInViewport( + deps, + { label: 'Footer note' }, + 'auto', + 10, + ).catch((e: unknown) => e); + + expect(error).toBeInstanceOf(ScrollToElementError); + expect(error).toMatchObject({ + code: 'ELEMENT_NOT_IN_VIEWPORT', + frame: { y: 1500 }, + }); + expect((error as Error).message).toContain('after 3 swipe(s)'); + expect(swipes).toStrictEqual(['up', 'up', 'up']); + }); + + it('fails with ELEMENT_NOT_FOUND when the element never appears', async () => { + const { deps } = list([['Row', 400]], { maxOffset: 0 }); + + await expect( + scrollUntilInViewport(deps, { label: 'Missing' }, 'auto', 10), + ).rejects.toMatchObject({ code: 'ELEMENT_NOT_FOUND', swipes: 2 }); + }); + + it('stops after maxAttempts swipes', async () => { + const { deps, swipes } = list([['Far', 20000]], { maxOffset: 100000 }); + + await expect( + scrollUntilInViewport(deps, { label: 'Far' }, 'auto', 4), + ).rejects.toMatchObject({ code: 'ELEMENT_NOT_IN_VIEWPORT', swipes: 4 }); + expect(swipes).toHaveLength(4); + }); + + it('accepts a fixed element that the swipe does not move', async () => { + // A footer button under the bottom inset never scrolls into the inset area. + const footer = node('Continue', 840, 30); + const { deps, swipes } = list([['Row', 400]], { fixed: [footer] }); + + const result = await scrollUntilInViewport( + deps, + { label: 'Continue' }, + 'auto', + 10, + ); + + expect(swipes).toStrictEqual(['up']); + expect(result).toMatchObject({ swipes: 1, inViewport: true }); + }); + + it('waits for the scroll to settle before returning', async () => { + // After the swipe, momentum moves the row 100 pt more over two reads. + const ys = [996, 646, 546, 546]; + let read = 0; + const deps = { + windowSize, + snapshot: vi.fn(async () => + snap([ + node('Account icon', ys[Math.min((read += 1) - 1, ys.length - 1)]), + ]), + ), + swipe: vi.fn(async () => undefined), + }; + + const result = await scrollUntilInViewport( + deps, + { label: 'Account icon' }, + 'auto', + 10, + ); + + expect(result.element.frame.y).toBe(546); + expect(deps.snapshot).toHaveBeenCalledTimes(4); + }); + + it('keeps scrolling when momentum carries the element out of view', async () => { + // In view right after the swipe, but the scroll keeps going past it. + const ys = [996, 400, -200, -200, 400, 400]; + let read = 0; + const swipes: string[] = []; + const deps = { + windowSize, + snapshot: vi.fn(async () => + snap([node('Row', ys[Math.min((read += 1) - 1, ys.length - 1)])]), + ), + swipe: vi.fn(async (finger: 'up' | 'down') => { + swipes.push(finger); + }), + }; + + const result = await scrollUntilInViewport( + deps, + { label: 'Row' }, + 'auto', + 10, + ); + + expect(swipes).toStrictEqual(['up', 'down']); + expect(result).toMatchObject({ swipes: 2, inViewport: true }); + expect(result.element.frame.y).toBe(400); + }); +}); diff --git a/src/utils/scroll.ts b/src/utils/scroll.ts new file mode 100644 index 0000000..dc3e17c --- /dev/null +++ b/src/utils/scroll.ts @@ -0,0 +1,253 @@ +import { describeElement, findElement, sameFrame } from './element.js'; +import type { + ElementQuery, + ScrollDirection, + ScrollToElementResult, + SnapshotResult, + UIElement, + WindowSize, +} from '../backends/types.js'; + +/** + * Part of the viewport height kept clear at the top and at the bottom when + * deciding whether an element is in view (about 35 pt on an 874 pt iPhone): + * the status bar and the iOS home indicator overlay the scrolled content. + */ +const VIEWPORT_INSET = 0.04; + +/** A tall element counts as in view once this many points of it are. */ +const MIN_VISIBLE = 44; + +/** Extra reads, after the target is in view, to let the scroll momentum stop. */ +const MAX_SETTLE_READS = 3; + +export type ScrollToElementErrorCode = + | 'ELEMENT_NOT_FOUND' + | 'ELEMENT_NOT_IN_VIEWPORT'; + +/** + * `scrollToElement` could not bring the element into view. `code` tells + * whether the element was never in the UI tree (`ELEMENT_NOT_FOUND`) or was + * found but stayed outside the viewport (`ELEMENT_NOT_IN_VIEWPORT`, with its + * last `frame`). + */ +export class ScrollToElementError extends Error { + readonly code: ScrollToElementErrorCode; + + readonly swipes: number; + + readonly frame: UIElement['frame'] | undefined; + + constructor( + code: ScrollToElementErrorCode, + message: string, + details: { swipes: number; frame?: UIElement['frame'] }, + ) { + super(message); + this.name = 'ScrollToElementError'; + this.code = code; + this.swipes = details.swipes; + this.frame = details.frame; + } +} + +/** + * Whether enough of the element is inside the viewport, after removing + * {@link VIEWPORT_INSET} at the top and bottom, to see and tap it: half of + * its height, or {@link MIN_VISIBLE} points for a tall element. + * + * @param element - The element. + * @param windowSize - The viewport size, in the same units as the frame. + * @param windowSize.width - Viewport width. + * @param windowSize.height - Viewport height. + * @returns True when the element is in view. + */ +export function isInViewport( + element: UIElement, + { width, height }: WindowSize, +): boolean { + const { x, y, width: w, height: h } = element.frame; + const top = Math.max(y, height * VIEWPORT_INSET); + const bottom = Math.min(y + h, height * (1 - VIEWPORT_INSET)); + const visibleWidth = Math.min(x + w, width) - Math.max(x, 0); + return visibleWidth > 0 && bottom - top >= Math.min(h / 2, MIN_VISIBLE); +} + +/** + * Whether any part of the element is inside the viewport (the rule a tap + * uses). + * + * @param element - The element. + * @param windowSize - The viewport size. + * @param windowSize.width - Viewport width. + * @param windowSize.height - Viewport height. + * @returns True when the frame intersects the viewport. + */ +function intersectsViewport( + element: UIElement, + { width, height }: WindowSize, +): boolean { + const { x, y, width: w, height: h } = element.frame; + return ( + Math.min(x + w, width) > Math.max(x, 0) && + Math.min(y + h, height) > Math.max(y, 0) + ); +} + +/** + * The finger direction that brings an off-screen element toward the middle + * of the viewport: up for an element below it (reveals content below), down + * for one above it. + * + * @param element - The element. + * @param windowSize - The viewport size. + * @returns The swipe direction. + */ +export function swipeToward( + element: UIElement, + windowSize: WindowSize, +): 'up' | 'down' { + const centerY = element.frame.y + element.frame.height / 2; + return centerY > windowSize.height / 2 ? 'up' : 'down'; +} + +export type ScrollDeps = { + snapshot: () => Promise; + windowSize: WindowSize; + /** One scroll gesture; `direction` is the finger direction. */ + swipe: (direction: 'up' | 'down') => Promise; +}; + +/** + * Swipe until the element matching `query` is in the viewport. + * + * Finding the element in the UI tree is not enough: React Native keeps + * off-screen rows in the accessibility tree, so the element must also pass + * {@link isInViewport}. An element that a swipe did not move while the screen + * changed is fixed (for example a footer button) and is accepted when it + * intersects the viewport. After a swipe, the screen is read again until it + * stops changing (scroll momentum) before the result is returned. + * + * `direction` is the finger direction. With `auto`, the direction comes from + * the element's position; while the element is not in the tree, the search + * goes toward content below (finger up) and turns around once when the + * screen stops changing. + * + * @param deps - Backend operations. + * @param query - The element to bring into view. + * @param direction - Finger direction, or `auto`. + * @param maxSwipes - Maximum number of swipes. + * @returns The element as last read, the number of swipes, `inViewport: true`. + * @throws {ScrollToElementError} When the element is not in view after + * `maxSwipes`, or the screen stops changing first. + */ +export async function scrollUntilInViewport( + deps: ScrollDeps, + query: ElementQuery, + direction: ScrollDirection, + maxSwipes: number, +): Promise { + const { windowSize } = deps; + let search: 'up' | 'down' = direction === 'down' ? 'down' : 'up'; + let turned = direction !== 'auto'; + let swipes = 0; + let snap = await deps.snapshot(); + let previousRaw: string | undefined; + let last: UIElement | null = null; + + for (;;) { + const element = findElement(snap.hierarchy, query); + const before = last; + if (element) { + last = element; + } + const fixed = + element !== null && + before !== null && + swipes > 0 && + snap.raw !== previousRaw && + sameFrame(element, before) && + intersectsViewport(element, windowSize); + if (element && fixed) { + // Does not scroll with the content, so momentum cannot move it. + return { element, swipes, inViewport: true }; + } + if (element && isInViewport(element, windowSize)) { + const settled = swipes === 0 ? null : await settle(deps, snap, query); + if (!settled) { + return { element, swipes, inViewport: true }; + } + if (settled.element && isInViewport(settled.element, windowSize)) { + return { element: settled.element, swipes, inViewport: true }; + } + // Momentum carried it out of view: judge again from the settled screen. + snap = settled.snap; + continue; + } + if (snap.raw === previousRaw) { + // The last swipe moved nothing: the end of the list in this direction. + if (direction === 'auto' && !element && !turned) { + turned = true; + search = search === 'up' ? 'down' : 'up'; + } else { + break; + } + } + if (swipes >= maxSwipes) { + break; + } + const next = + direction === 'auto' && element + ? swipeToward(element, windowSize) + : search; + previousRaw = snap.raw; + await deps.swipe(next); + swipes += 1; + snap = await deps.snapshot(); + } + + if (!last) { + throw new ScrollToElementError( + 'ELEMENT_NOT_FOUND', + `Element not found after ${swipes} swipe(s): ${JSON.stringify(query)}\n` + + 'Use device_snapshot to inspect the current UI hierarchy.', + { swipes }, + ); + } + const { frame } = last; + throw new ScrollToElementError( + 'ELEMENT_NOT_IN_VIEWPORT', + `Element is outside the ${windowSize.width}x${windowSize.height} viewport ` + + `after ${swipes} swipe(s): ${describeElement(last)} at ` + + `(${frame.x}, ${frame.y} ${frame.width}x${frame.height}).`, + { swipes, frame }, + ); +} + +/** + * Read the screen until two reads are equal, so a scroll that is still moving + * is not judged mid-flight. + * + * @param deps - Backend operations. + * @param first - The read that found the element in view. + * @param query - The element. + * @returns The settled read and the element in it, or null when the first + * read was already settled. + */ +async function settle( + deps: ScrollDeps, + first: SnapshotResult, + query: ElementQuery, +): Promise<{ snap: SnapshotResult; element: UIElement | null } | null> { + let previous = first; + for (let i = 0; i < MAX_SETTLE_READS; i++) { + const snap = await deps.snapshot(); + if (snap.raw === previous.raw) { + return i === 0 + ? null + : { snap, element: findElement(snap.hierarchy, query) }; + } + previous = snap; + } + return { snap: previous, element: findElement(previous.hierarchy, query) }; +} From 60b6d2f9d58639287338194b28dc40662760844c Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 30 Oct 2026 00:07:52 +0000 Subject: [PATCH 09/33] fix: round the frame in the scroll error message --- src/utils/scroll.test.ts | 1 + src/utils/scroll.ts | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/utils/scroll.test.ts b/src/utils/scroll.test.ts index 20c5b59..a3b8782 100644 --- a/src/utils/scroll.test.ts +++ b/src/utils/scroll.test.ts @@ -212,6 +212,7 @@ describe('scrollUntilInViewport', () => { frame: { y: 1500 }, }); expect((error as Error).message).toContain('after 3 swipe(s)'); + expect((error as Error).message).toContain('at (16, 1500 370x24)'); expect(swipes).toStrictEqual(['up', 'up', 'up']); }); diff --git a/src/utils/scroll.ts b/src/utils/scroll.ts index dc3e17c..95f91cd 100644 --- a/src/utils/scroll.ts +++ b/src/utils/scroll.ts @@ -215,11 +215,14 @@ export async function scrollUntilInViewport( ); } const { frame } = last; + const [x, y, w, h] = [frame.x, frame.y, frame.width, frame.height].map( + Math.round, + ); throw new ScrollToElementError( 'ELEMENT_NOT_IN_VIEWPORT', `Element is outside the ${windowSize.width}x${windowSize.height} viewport ` + `after ${swipes} swipe(s): ${describeElement(last)} at ` + - `(${frame.x}, ${frame.y} ${frame.width}x${frame.height}).`, + `(${x}, ${y} ${w}x${h}).`, { swipes, frame }, ); } From 02bd986d70b207cab947dd10bb55cbd77605a71f Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 30 Oct 2026 00:11:06 +0000 Subject: [PATCH 10/33] fix: a zero-height frame is not in the viewport (Android clipped bounds) --- src/utils/scroll.test.ts | 4 ++++ src/utils/scroll.ts | 12 ++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/utils/scroll.test.ts b/src/utils/scroll.test.ts index a3b8782..91753ea 100644 --- a/src/utils/scroll.test.ts +++ b/src/utils/scroll.test.ts @@ -83,6 +83,10 @@ describe('isInViewport', () => { expect(isInViewport(node('Card', 800, 600), windowSize)).toBe(false); }); + it('rejects a zero-height frame (Android clips hidden rows to the list edge)', () => { + expect(isInViewport(node('Currency', 210, 0), windowSize)).toBe(false); + }); + it('rejects an element outside the viewport horizontally', () => { const element = { ...node('Row', 400), diff --git a/src/utils/scroll.ts b/src/utils/scroll.ts index 95f91cd..3764c5c 100644 --- a/src/utils/scroll.ts +++ b/src/utils/scroll.ts @@ -54,7 +54,8 @@ export class ScrollToElementError extends Error { /** * Whether enough of the element is inside the viewport, after removing * {@link VIEWPORT_INSET} at the top and bottom, to see and tap it: half of - * its height, or {@link MIN_VISIBLE} points for a tall element. + * its height, or {@link MIN_VISIBLE} points for a tall element. A zero-size + * frame is never in view. * * @param element - The element. * @param windowSize - The viewport size, in the same units as the frame. @@ -70,7 +71,14 @@ export function isInViewport( const top = Math.max(y, height * VIEWPORT_INSET); const bottom = Math.min(y + h, height * (1 - VIEWPORT_INSET)); const visibleWidth = Math.min(x + w, width) - Math.max(x, 0); - return visibleWidth > 0 && bottom - top >= Math.min(h / 2, MIN_VISIBLE); + const visibleHeight = bottom - top; + // Android clips an off-screen node's bounds to the edge of its scroll + // container, so a hidden row can be reported with zero height. + return ( + visibleWidth > 0 && + visibleHeight > 0 && + visibleHeight >= Math.min(h / 2, MIN_VISIBLE) + ); } /** From c86dc73dc7db5a3012dcbaef9d58f5fb86260632 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 30 Oct 2026 00:28:33 +0000 Subject: [PATCH 11/33] test: complete the SnapshotResult fixture in the scroll tests --- src/utils/scroll.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/utils/scroll.test.ts b/src/utils/scroll.test.ts index 91753ea..b886b0c 100644 --- a/src/utils/scroll.test.ts +++ b/src/utils/scroll.test.ts @@ -18,8 +18,10 @@ const node = (label: string, y: number, height = 24): UIElement => ({ }); const snap = (elements: UIElement[]): SnapshotResult => ({ + platform: 'ios', hierarchy: elements, raw: JSON.stringify(elements), + timestamp: 0, }); /** From 03d9f10f0bfe2fb6dc06bba33cf62c768adefae1 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 6 Nov 2026 09:37:48 -0600 Subject: [PATCH 12/33] refactor: simplify scrollUntilInViewport and inline the Android scroll swipe --- src/backends/adb-backend.ts | 30 +++++------------- src/backends/appium-backend.ts | 30 +++++------------- src/utils/scroll.ts | 56 +++++++++++++++------------------- 3 files changed, 41 insertions(+), 75 deletions(-) diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index 357f5f1..af50ade 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -906,7 +906,14 @@ export class AdbBackend implements DeviceBackend { { snapshot: async () => this.snapshot(), windowSize, - swipe: async (finger) => this.#scrollSwipe(finger, windowSize), + // The iOS backend's default: from the middle, over 40% of the height. + swipe: async (finger) => + this.swipe( + finger, + Math.round(windowSize.width / 2), + Math.round(windowSize.height / 2), + Math.round(windowSize.height * 0.4), + ), }, query, direction, @@ -914,27 +921,6 @@ export class AdbBackend implements DeviceBackend { ); } - /** - * One scroll gesture from the middle of the screen over 40% of its height - * (the iOS backend's default), so the swipe matches the real screen size. - * - * @param finger - Finger direction. - * @param windowSize - The screen size, in the frame units. - * @param windowSize.width - Viewport width. - * @param windowSize.height - Viewport height. - */ - async #scrollSwipe( - finger: 'up' | 'down', - { width, height }: WindowSize, - ): Promise { - await this.swipe( - finger, - Math.round(width / 2), - Math.round(height / 2), - Math.round(height * 0.4), - ); - } - async getAlertText(): Promise { const snap = await this.snapshot(); const texts = collectAndroidAlertTexts(snap.hierarchy); diff --git a/src/backends/appium-backend.ts b/src/backends/appium-backend.ts index 78710c0..2ccd33a 100644 --- a/src/backends/appium-backend.ts +++ b/src/backends/appium-backend.ts @@ -431,7 +431,14 @@ export class AppiumBackend implements DeviceBackend { { snapshot: async () => this.snapshot(), windowSize, - swipe: async (finger) => this.#scrollSwipe(finger, windowSize), + // The iOS backend's default: from the middle, over 40% of the height. + swipe: async (finger) => + this.swipe( + finger, + Math.round(windowSize.width / 2), + Math.round(windowSize.height / 2), + Math.round(windowSize.height * 0.4), + ), }, query, direction, @@ -439,27 +446,6 @@ export class AppiumBackend implements DeviceBackend { ); } - /** - * One scroll gesture from the middle of the screen over 40% of its height - * (the iOS backend's default), so the swipe matches the real screen size. - * - * @param finger - Finger direction. - * @param windowSize - The screen size, in the frame units. - * @param windowSize.width - Viewport width. - * @param windowSize.height - Viewport height. - */ - async #scrollSwipe( - finger: 'up' | 'down', - { width, height }: WindowSize, - ): Promise { - await this.swipe( - finger, - Math.round(width / 2), - Math.round(height / 2), - Math.round(height * 0.4), - ); - } - async getAlertText(): Promise { const client = this.#requireClient(); try { diff --git a/src/utils/scroll.ts b/src/utils/scroll.ts index 3764c5c..d1b39b3 100644 --- a/src/utils/scroll.ts +++ b/src/utils/scroll.ts @@ -165,36 +165,35 @@ export async function scrollUntilInViewport( for (;;) { const element = findElement(snap.hierarchy, query); - const before = last; if (element) { + const fixed = + last !== null && + swipes > 0 && + snap.raw !== previousRaw && + sameFrame(element, last) && + intersectsViewport(element, windowSize); last = element; - } - const fixed = - element !== null && - before !== null && - swipes > 0 && - snap.raw !== previousRaw && - sameFrame(element, before) && - intersectsViewport(element, windowSize); - if (element && fixed) { - // Does not scroll with the content, so momentum cannot move it. - return { element, swipes, inViewport: true }; - } - if (element && isInViewport(element, windowSize)) { - const settled = swipes === 0 ? null : await settle(deps, snap, query); - if (!settled) { + if (fixed) { + // Does not scroll with the content, so momentum cannot move it. return { element, swipes, inViewport: true }; } - if (settled.element && isInViewport(settled.element, windowSize)) { - return { element: settled.element, swipes, inViewport: true }; + if (isInViewport(element, windowSize)) { + const settled = swipes === 0 ? null : await settle(deps, snap); + if (!settled) { + return { element, swipes, inViewport: true }; + } + const settledElement = findElement(settled.hierarchy, query); + if (settledElement && isInViewport(settledElement, windowSize)) { + return { element: settledElement, swipes, inViewport: true }; + } + // Momentum carried it out of view: judge again from the settled screen. + snap = settled; + continue; } - // Momentum carried it out of view: judge again from the settled screen. - snap = settled.snap; - continue; } if (snap.raw === previousRaw) { // The last swipe moved nothing: the end of the list in this direction. - if (direction === 'auto' && !element && !turned) { + if (!element && !turned) { turned = true; search = search === 'up' ? 'down' : 'up'; } else { @@ -241,24 +240,19 @@ export async function scrollUntilInViewport( * * @param deps - Backend operations. * @param first - The read that found the element in view. - * @param query - The element. - * @returns The settled read and the element in it, or null when the first - * read was already settled. + * @returns The settled read, or null when the first read was already settled. */ async function settle( deps: ScrollDeps, first: SnapshotResult, - query: ElementQuery, -): Promise<{ snap: SnapshotResult; element: UIElement | null } | null> { +): Promise { let previous = first; for (let i = 0; i < MAX_SETTLE_READS; i++) { const snap = await deps.snapshot(); if (snap.raw === previous.raw) { - return i === 0 - ? null - : { snap, element: findElement(snap.hierarchy, query) }; + return i === 0 ? null : snap; } previous = snap; } - return { snap: previous, element: findElement(previous.hierarchy, query) }; + return previous; } From c1e8d243f1de13381693382fa4315bf343fc7aaa Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 30 Oct 2026 00:31:05 +0000 Subject: [PATCH 13/33] fix: hit-test iOS taps; refuse off-screen Android taps B2: a click on log-in-button reported success while the keyboard covered it, and nothing happened. - iOS tapElement/longPress run idb ui describe-point --api axbridge at the tap point; when the element there is not the target (or inside it), throw TargetObscuredError (TARGET_OBSCURED, obscuredBy, keyboard) and do not tap. No element at the point / no --api support: tap. - Android tapElement/longPress use the shared visibleCenter rule (frame clipped to the screen; refuse when outside, incl. zero-height rows); wm size cached per backend - visibleCenter moved to utils/element (shared by idb and adb) --- src/backends/adb-backend.test.ts | 70 ++++++++- src/backends/adb-backend.ts | 26 +++- src/backends/idb-backend.test.ts | 235 +++++++++++++++++++++++++++++++ src/backends/idb-backend.ts | 87 ++++++++---- src/index.ts | 1 + src/utils/element.ts | 36 +++++ src/utils/hit-test.test.ts | 103 ++++++++++++++ src/utils/hit-test.ts | 92 ++++++++++++ 8 files changed, 620 insertions(+), 30 deletions(-) create mode 100644 src/utils/hit-test.test.ts create mode 100644 src/utils/hit-test.ts diff --git a/src/backends/adb-backend.test.ts b/src/backends/adb-backend.test.ts index f47a51f..984fcd8 100644 --- a/src/backends/adb-backend.test.ts +++ b/src/backends/adb-backend.test.ts @@ -630,9 +630,14 @@ describe('AdbBackend.tapElement', () => { enabled: true, }; + const tapCalls = (): unknown[][] => + mockExecStrict.mock.calls.filter(([, args]) => args?.includes('tap')); + beforeEach(() => { vi.clearAllMocks(); - mockExecStrict.mockResolvedValue(''); + mockExecStrict.mockImplementation(async (_cmd, args) => + args?.includes('wm') ? 'Physical size: 1080x2400' : '', + ); backend = new AdbBackend('emulator-5554'); }); @@ -643,7 +648,10 @@ describe('AdbBackend.tapElement', () => { ); expect(result).toMatchObject({ success: true, x: 300, y: 230 }); - expect(mockExecStrict).toHaveBeenCalledTimes(1); + // One `wm size` (cached per backend) and the tap; no uiautomator dump. + expect( + mockExecStrict.mock.calls.map(([, args]) => args?.[3]), + ).toStrictEqual(['wm', 'input']); expect(mockExecStrict).toHaveBeenCalledWith('adb', [ '-s', 'emulator-5554', @@ -655,6 +663,64 @@ describe('AdbBackend.tapElement', () => { ]); }); + it('reads the screen size once per backend', async () => { + await backend.tapElement({ identifier: 'submit' }, { element }); + await backend.tapElement({ identifier: 'submit' }, { element }); + + expect( + mockExecStrict.mock.calls.filter(([, args]) => args?.includes('wm')), + ).toHaveLength(1); + }); + + it('taps the visible part of a partly off-screen element', async () => { + const partly = { + ...element, + frame: { x: 100, y: 2300, width: 400, height: 300 }, + }; + + const result = await backend.tapElement( + { identifier: 'submit' }, + { element: partly }, + ); + + // Visible part: y 2300..2400 -> center 2350. + expect(result).toMatchObject({ x: 300, y: 2350 }); + }); + + it.each([ + ['below the screen', { x: 42, y: 2513, width: 996, height: 63 }], + [ + 'clipped to zero height at the list edge', + { x: 42, y: 2513, width: 996, height: 0 }, + ], + ])('refuses to tap an element %s', async (_name, frame) => { + await expect( + backend.tapElement( + { identifier: 'submit' }, + { element: { ...element, frame } }, + ), + ).rejects.toThrow('Element is outside the 1080x2400 viewport'); + expect(tapCalls()).toHaveLength(0); + }); + + it('refuses to long-press an element outside the screen', async () => { + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('wm')) { + return 'Physical size: 1080x2400'; + } + return args?.includes('cat') || args?.includes('dump') + ? `` + : ''; + }); + + await expect(backend.longPress({ identifier: 'far' })).rejects.toThrow( + 'outside the 1080x2400 viewport', + ); + expect( + mockExecStrict.mock.calls.filter(([, args]) => args?.includes('swipe')), + ).toHaveLength(0); + }); + it('snapshots to find the element when none is passed', async () => { mockExecStrict.mockImplementation(async (_cmd, args) => args?.includes('cat') || args?.includes('dump') diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index af50ade..578f865 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -59,6 +59,7 @@ import { findElement, describeElement, computeSwipeEnd, + visibleCenter, } from '../utils/element.js'; import { exec, execStrict, isCommandAvailable } from '../utils/exec.js'; import { @@ -220,6 +221,8 @@ export class AdbBackend implements DeviceBackend { readonly #recordingRemotePath = '/sdcard/device-mcp-recording.mp4'; + #windowSize: Promise | undefined; + // Installation is cached; trust is still checked before every helper run. #helperInstalled = false; @@ -314,8 +317,7 @@ export class AdbBackend implements DeviceBackend { ); } - const x = Math.round(element.frame.x + element.frame.width / 2); - const y = Math.round(element.frame.y + element.frame.height / 2); + const { x, y } = visibleCenter(element, await this.#cachedWindowSize()); await this.tapCoordinates(x, y); return { @@ -875,8 +877,10 @@ export class AdbBackend implements DeviceBackend { ); } - const cx = Math.round(element.frame.x + element.frame.width / 2); - const cy = Math.round(element.frame.y + element.frame.height / 2); + const { x: cx, y: cy } = visibleCenter( + element, + await this.#cachedWindowSize(), + ); await this.#adb([ 'shell', 'input', @@ -933,6 +937,20 @@ export class AdbBackend implements DeviceBackend { return texts.join('\n'); } + /** + * The screen size, read once per backend (one `adb shell wm size`) for the + * tap viewport check. A failed read is not cached. + * + * @returns The screen size in pixels. + */ + async #cachedWindowSize(): Promise { + this.#windowSize ??= this.getWindowSize().catch((error: unknown) => { + this.#windowSize = undefined; + throw error; + }); + return this.#windowSize; + } + async getWindowSize(): Promise { const raw = await this.#adb(['shell', 'wm', 'size']); const match = raw.match(/(\d+)x(\d+)/u); diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index 97e94ff..1f7837d 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -10,6 +10,7 @@ import { IdbUnavailableError } from './idb-errors.js'; import type { UIElement } from './types.js'; import { findElement, generateLocators } from '../utils/element.js'; import * as execModule from '../utils/exec.js'; +import { TargetObscuredError } from '../utils/hit-test.js'; import * as platformModule from '../utils/platform.js'; const connectionMocks = vi.hoisted(() => ({ @@ -867,6 +868,240 @@ describe('IdbBackend.tapElement and longPress viewport handling', () => { }); }); +describe('IdbBackend tap hit-test', () => { + const udid = 'AAAA1111-BBBB-CCCC-DDDD-EEEE2222FFFF'; + let backend: IdbBackend; + + const loginButton: UIElement = { + type: 'Button', + label: 'Unlock', + identifier: 'log-in-button', + frame: { x: 16.3, y: 532.3, width: 369.3, height: 48 }, + enabled: true, + }; + + /** + * @param hit - What `describe-point` returns: a node, an error, or raw text. + */ + const mockDevice = (hit: Record | Error | string): void => { + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.[0] === 'describe' && args.includes('--json')) { + return JSON.stringify({ + os_version: '26.5', + screen_dimensions: { width_points: 402, height_points: 874 }, + }); + } + if (args?.[1] === 'describe-point') { + if (hit instanceof Error) { + throw hit; + } + return typeof hit === 'string' ? hit : JSON.stringify(hit); + } + return ''; + }); + }; + + const tapCalls = (): unknown[][] => + mockExecStrict.mock.calls.filter(([, args]) => args?.[1] === 'tap'); + + beforeEach(() => { + vi.clearAllMocks(); + connectionState.alive = true; + mockSupportsApi.mockResolvedValue(true); + mockSupportsNested.mockResolvedValue(true); + mockExec.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); + backend = new IdbBackend(udid); + }); + + it('hit-tests the tap point with describe-point before tapping', async () => { + mockDevice({ + type: 'Button', + AXLabel: 'Unlock', + AXUniqueId: 'log-in-button', + frame: loginButton.frame, + }); + + await backend.tapElement( + { identifier: 'log-in-button' }, + { element: loginButton }, + ); + + const calls = mockExecStrict.mock.calls + .map(([, args]) => args) + .filter((args) => args[0] === 'ui'); + expect(calls).toStrictEqual([ + [ + 'ui', + 'describe-point', + '201', + '556', + '--api', + 'axbridge', + '--json', + '--udid', + udid, + ], + ['ui', 'tap', '201', '556', '--udid', udid], + ]); + }); + + it('accepts a child of the target at the point (a label inside the button)', async () => { + mockDevice({ + type: 'StaticText', + AXLabel: 'Unlock', + frame: { x: 170, y: 545, width: 60, height: 22 }, + }); + + await backend.tapElement( + { identifier: 'log-in-button' }, + { element: loginButton }, + ); + + expect(tapCalls()).toHaveLength(1); + }); + + it('refuses the tap when the keyboard covers the target (B2)', async () => { + // Keyboard up on the login screen: the AutoFill bar sits over Unlock. + mockDevice({ + type: 'Button', + AXLabel: 'Passwords', + AXUniqueId: null, + frame: { x: 30, y: 546, width: 342, height: 44 }, + }); + + const error = await backend + .tapElement({ identifier: 'log-in-button' }, { element: loginButton }) + .catch((e: unknown) => e); + + expect(error).toBeInstanceOf(TargetObscuredError); + expect(error).toMatchObject({ + code: 'TARGET_OBSCURED', + keyboard: true, + x: 201, + y: 556, + obscuredBy: { type: 'Button', label: 'Passwords' }, + }); + expect((error as Error).message).toContain('by the keyboard'); + expect(tapCalls()).toHaveLength(0); + }); + + it('refuses the tap when a key is at the point', async () => { + mockDevice({ + type: 'Key', + AXLabel: 'g', + frame: { x: 182, y: 651, width: 39, height: 54 }, + }); + const lowButton = { + ...loginButton, + frame: { x: 16, y: 660, width: 370, height: 48 }, + }; + + await expect( + backend.tapElement( + { identifier: 'log-in-button' }, + { element: lowButton }, + ), + ).rejects.toMatchObject({ code: 'TARGET_OBSCURED', keyboard: true }); + expect(tapCalls()).toHaveLength(0); + }); + + it('refuses the tap when an overlay covers the target', async () => { + mockDevice({ + type: 'Other', + AXLabel: 'Bottom sheet', + AXUniqueId: 'sheet', + frame: { x: 0, y: 400, width: 402, height: 474 }, + }); + + await expect( + backend.tapElement( + { identifier: 'log-in-button' }, + { element: loginButton }, + ), + ).rejects.toMatchObject({ + code: 'TARGET_OBSCURED', + keyboard: false, + message: expect.stringContaining('Close the overlay'), + }); + expect(tapCalls()).toHaveLength(0); + }); + + it('taps when the hit-test finds no element at the point', async () => { + mockDevice( + new Error('The axbridge backend found no element at (201.0, 556.0)'), + ); + + await backend.tapElement( + { identifier: 'log-in-button' }, + { element: loginButton }, + ); + + expect(tapCalls()).toHaveLength(1); + }); + + it('taps when the hit-test output is not JSON', async () => { + mockDevice('not json'); + + await backend.tapElement( + { identifier: 'log-in-button' }, + { element: loginButton }, + ); + + expect(tapCalls()).toHaveLength(1); + }); + + it('skips the hit-test when idb cannot select the accessibility API', async () => { + mockSupportsApi.mockResolvedValue(false); + mockDevice(new Error('must not be called')); + + await backend.tapElement( + { identifier: 'log-in-button' }, + { element: loginButton }, + ); + + expect( + mockExecStrict.mock.calls.filter( + ([, args]) => args?.[1] === 'describe-point', + ), + ).toHaveLength(0); + expect(tapCalls()).toHaveLength(1); + }); + + it('hit-tests long presses too', async () => { + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.[0] === 'describe' && args.includes('--json')) { + return JSON.stringify({ + os_version: '26.5', + screen_dimensions: { width_points: 402, height_points: 874 }, + }); + } + if (args?.[1] === 'describe-all') { + return JSON.stringify([ + { + type: 'Button', + AXLabel: 'Unlock', + AXUniqueId: 'log-in-button', + frame: loginButton.frame, + }, + ]); + } + if (args?.[1] === 'describe-point') { + return JSON.stringify({ + type: 'Key', + AXLabel: 'space', + frame: { x: 100, y: 540, width: 200, height: 40 }, + }); + } + return ''; + }); + + await expect( + backend.longPress({ identifier: 'log-in-button' }), + ).rejects.toMatchObject({ code: 'TARGET_OBSCURED' }); + expect(tapCalls()).toHaveLength(0); + }); +}); + describe('IdbBackend device description cache', () => { const udid = 'AAAA1111-BBBB-CCCC-DDDD-EEEE2222FFFF'; let backend: IdbBackend; diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index 8ce6093..eb404f8 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -27,8 +27,14 @@ import { findElement, describeElement, computeSwipeEnd, + visibleCenter, } from '../utils/element.js'; import { execStrict, exec } from '../utils/exec.js'; +import { + hitsTarget, + isKeyboardElement, + TargetObscuredError, +} from '../utils/hit-test.js'; import { hardenArtifactFile, resolveArtifactPath, @@ -485,6 +491,7 @@ export class IdbBackend implements DeviceBackend { } const { x, y } = await this.#visibleTapPoint(element); + await this.#assertHittable(element, { x, y }); await this.tapCoordinates(x, y); return { @@ -495,37 +502,68 @@ export class IdbBackend implements DeviceBackend { }; } + async #visibleTapPoint( + element: UIElement, + ): Promise<{ x: number; y: number }> { + return visibleCenter(element, await this.getWindowSize()); + } + /** - * Returns the center of the part of the element's frame that lies inside - * the device viewport, in logical points. Tapping there is safer than - * tapping the raw frame center, which can fall outside the screen for - * off-screen or partially scrolled elements and either hit nothing or an - * unrelated on-screen control. + * Check that a tap at the point reaches the element, with one + * `idb ui describe-point` (about 0.25 s). Throws when another element (an + * overlay, a sheet, the keyboard) is on top. When the hit-test finds no + * element, or the idb version cannot run it, the tap goes ahead: the check + * only blocks taps it knows are wrong. * * @param element - The element to tap. - * @returns The tap point in logical points. - * @throws When the element's frame does not intersect the viewport at all. + * @param point - The tap point. + * @param point.x - X in points. + * @param point.y - Y in points. + * @throws {TargetObscuredError} When another element is at the point. */ - async #visibleTapPoint( + async #assertHittable( element: UIElement, - ): Promise<{ x: number; y: number }> { - const { width, height } = await this.getWindowSize(); - const x0 = Math.max(element.frame.x, 0); - const y0 = Math.max(element.frame.y, 0); - const x1 = Math.min(element.frame.x + element.frame.width, width); - const y1 = Math.min(element.frame.y + element.frame.height, height); - if (x1 <= x0 || y1 <= y0) { - throw new Error( - `Element is outside the ${width}x${height} viewport: ` + - `${describeElement(element)} at (${element.frame.x}, ${element.frame.y} ` + - `${element.frame.width}x${element.frame.height}). ` + - 'Scroll it into view first (device_swipe or scroll_to_element).', + point: { x: number; y: number }, + ): Promise { + if (!this.#idbSupportsApi) { + return; + } + const args = [ + 'ui', + 'describe-point', + String(point.x), + String(point.y), + '--api', + 'axbridge', + '--json', + '--udid', + this.#udid, + ]; + let raw: string; + try { + raw = await this.#execStrict(this.#idbPath, args); + } catch (error) { + if (error instanceof IdbUnavailableError) { + throw error; + } + // "found no element at (x, y)" and other hit-test failures: unknown, + // not obscured. + return; + } + let hit: UIElement; + try { + hit = mapIdbElement(JSON.parse(raw) as Record); + } catch { + return; + } + if (!hitsTarget(element, hit)) { + throw new TargetObscuredError( + element, + hit, + point, + isKeyboardElement(hit), ); } - return { - x: Math.round((x0 + x1) / 2), - y: Math.round((y0 + y1) / 2), - }; } async getElementText(query: ElementQuery): Promise { @@ -867,6 +905,7 @@ export class IdbBackend implements DeviceBackend { } const { x: cx, y: cy } = await this.#visibleTapPoint(element); + await this.#assertHittable(element, { x: cx, y: cy }); await this.#execStrict(this.#idbPath, [ 'ui', 'tap', diff --git a/src/index.ts b/src/index.ts index 21ea0c3..fc49fa0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,6 +10,7 @@ export { createMcpServer } from './server.js'; export { detectAllDevices, MultipleDevicesError } from './utils/platform.js'; export { IdbUnavailableError } from './backends/idb-errors.js'; export { ScrollToElementError } from './utils/scroll.js'; +export { TargetObscuredError } from './utils/hit-test.js'; export type { ScrollToElementErrorCode } from './utils/scroll.js'; export type { IdbErrorCode } from './backends/idb-errors.js'; export type { DetectedDevice } from './utils/platform.js'; diff --git a/src/utils/element.ts b/src/utils/element.ts index ecfce40..8e52466 100644 --- a/src/utils/element.ts +++ b/src/utils/element.ts @@ -269,3 +269,39 @@ export function formatHierarchy(elements: UIElement[], depth: number): string { }) .join('\n'); } + +/** + * The center of the part of the element's frame that lies inside the + * viewport. Tapping there is safer than tapping the raw frame center, which + * can fall outside the screen for off-screen or partly scrolled elements and + * hit nothing or an unrelated control. + * + * @param element - The element to tap. + * @param viewport - The viewport size, in the frame's units. + * @param viewport.width - Viewport width. + * @param viewport.height - Viewport height. + * @returns The tap point. + * @throws When the frame does not intersect the viewport (or has no area). + */ +export function visibleCenter( + element: UIElement, + { width, height }: { width: number; height: number }, +): { x: number; y: number } { + const x0 = Math.max(element.frame.x, 0); + const y0 = Math.max(element.frame.y, 0); + const x1 = Math.min(element.frame.x + element.frame.width, width); + const y1 = Math.min(element.frame.y + element.frame.height, height); + if (x1 <= x0 || y1 <= y0) { + throw new Error( + `Element is outside the ${width}x${height} viewport: ` + + `${describeElement(element)} at (${Math.round(element.frame.x)}, ` + + `${Math.round(element.frame.y)} ${Math.round(element.frame.width)}x` + + `${Math.round(element.frame.height)}). ` + + 'Scroll it into view first (device_swipe or scroll_to_element).', + ); + } + return { + x: Math.round((x0 + x1) / 2), + y: Math.round((y0 + y1) / 2), + }; +} diff --git a/src/utils/hit-test.test.ts b/src/utils/hit-test.test.ts new file mode 100644 index 0000000..955242e --- /dev/null +++ b/src/utils/hit-test.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, it } from 'vitest'; + +import { hitsTarget, isKeyboardElement } from './hit-test.js'; +import type { UIElement } from '../backends/types.js'; + +const el = ( + type: string, + frame: UIElement['frame'], + extra: Partial = {}, +): UIElement => ({ type, frame, enabled: true, ...extra }); + +const target = el( + 'Button', + { x: 16, y: 532, width: 370, height: 48 }, + { identifier: 'log-in-button', label: 'Unlock' }, +); + +describe('hitsTarget', () => { + it('accepts the target itself', () => { + expect(hitsTarget(target, { ...target })).toBe(true); + }); + + it('accepts an element with the same identifier, whatever its frame', () => { + expect( + hitsTarget( + target, + el( + 'Other', + { x: 0, y: 0, width: 1, height: 1 }, + { identifier: 'log-in-button' }, + ), + ), + ).toBe(true); + }); + + it('accepts a child inside the target frame (1 pt tolerance)', () => { + expect( + hitsTarget( + target, + el('StaticText', { x: 15.5, y: 540, width: 100, height: 20 }), + ), + ).toBe(true); + }); + + it('rejects a larger element around the target (a sheet or container)', () => { + expect( + hitsTarget( + target, + el('Other', { x: 0, y: 400, width: 402, height: 474 }), + ), + ).toBe(false); + }); + + it('rejects an overlapping sibling that sticks out of the target', () => { + expect( + hitsTarget( + target, + el( + 'Button', + { x: 30, y: 560, width: 342, height: 44 }, + { label: 'Close' }, + ), + ), + ).toBe(false); + }); + + it('rejects keyboard elements even inside the target frame', () => { + expect( + hitsTarget( + target, + el( + 'Button', + { x: 30, y: 546, width: 342, height: 44 }, + { label: 'Passwords' }, + ), + ), + ).toBe(false); + expect( + hitsTarget(target, el('Key', { x: 100, y: 540, width: 30, height: 30 })), + ).toBe(false); + }); +}); + +describe('isKeyboardElement', () => { + it.each([ + [el('Keyboard', { x: 0, y: 590, width: 402, height: 226 }), true], + [el('Key', { x: 0, y: 0, width: 1, height: 1 }, { label: 'g' }), true], + [ + el('Button', { x: 0, y: 0, width: 1, height: 1 }, { label: 'Passwords' }), + true, + ], + [ + el('Button', { x: 0, y: 0, width: 1, height: 1 }, { label: 'Unlock' }), + false, + ], + [ + el('KeyboardControllerView', { x: 0, y: 0, width: 402, height: 874 }), + false, + ], + ])('%#: %j -> %s', (element, expected) => { + expect(isKeyboardElement(element)).toBe(expected); + }); +}); diff --git a/src/utils/hit-test.ts b/src/utils/hit-test.ts new file mode 100644 index 0000000..cff414d --- /dev/null +++ b/src/utils/hit-test.ts @@ -0,0 +1,92 @@ +import { describeElement } from './element.js'; +import type { UIElement } from '../backends/types.js'; + +/** Element types of the iOS software keyboard and its accessory bar. */ +const KEYBOARD_TYPES = new Set(['Keyboard', 'Key']); + +/** Labels of the keyboard's input-assistant bar (AutoFill / Passwords). */ +const KEYBOARD_ASSISTANT_LABELS = new Set(['Passwords']); + +/** + * A tap would land on another element than the target: an overlay, a sheet, + * or the software keyboard. Nothing was tapped. + */ +export class TargetObscuredError extends Error { + readonly code = 'TARGET_OBSCURED' as const; + + /** The element at the tap point. */ + readonly obscuredBy: UIElement; + + /** True when the obscuring element belongs to the software keyboard. */ + readonly keyboard: boolean; + + readonly x: number; + + readonly y: number; + + constructor( + target: UIElement, + obscuredBy: UIElement, + point: { x: number; y: number }, + keyboard: boolean, + ) { + const advice = keyboard + ? 'Dismiss the keyboard (device_dismiss_keyboard) and retry.' + : 'Close the overlay, or scroll the target into a free area.'; + super( + `TARGET_OBSCURED: ${describeElement(target)} is covered at ` + + `(${point.x}, ${point.y}) by ${keyboard ? 'the keyboard: ' : ''}` + + `${describeElement(obscuredBy)}. Nothing was tapped. ${advice}`, + ); + this.name = 'TargetObscuredError'; + this.obscuredBy = obscuredBy; + this.keyboard = keyboard; + this.x = point.x; + this.y = point.y; + } +} + +/** + * Whether `hit` (the element at the tap point) is the target or part of it. + * + * The hit-test returns the deepest accessible element, which can be a child + * of the target (a label inside a button), so "part of" means: same + * identifier, or a frame inside the target's frame (1 pt tolerance) that is + * not the keyboard. A larger element than the target is never accepted. + * + * @param target - The element the caller wants to tap. + * @param hit - The element at the tap point. + * @returns True when the tap reaches the target. + */ +export function hitsTarget(target: UIElement, hit: UIElement): boolean { + if (isKeyboardElement(hit)) { + return false; + } + if (target.identifier && hit.identifier === target.identifier) { + return true; + } + const tol = 1; + const t = target.frame; + const h = hit.frame; + return ( + h.x >= t.x - tol && + h.y >= t.y - tol && + h.x + h.width <= t.x + t.width + tol && + h.y + h.height <= t.y + t.height + tol + ); +} + +/** + * Whether the element is part of the software keyboard: a key, the keyboard + * itself, or its AutoFill bar ("Passwords"). + * + * @param element - The element. + * @returns True for keyboard elements. + */ +export function isKeyboardElement(element: UIElement): boolean { + return ( + KEYBOARD_TYPES.has(element.type) || + (element.type === 'Button' && + KEYBOARD_ASSISTANT_LABELS.has(element.label ?? '')) + ); +} From 90def7bddded1ab7d4224e27a3a0c2b6be2bf908 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 30 Oct 2026 00:32:35 +0000 Subject: [PATCH 14/33] fix: give the viewport tap error code ELEMENT_NOT_IN_VIEWPORT --- src/backends/adb-backend.test.ts | 5 ++++- src/utils/element.ts | 18 +++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/backends/adb-backend.test.ts b/src/backends/adb-backend.test.ts index 984fcd8..71749f6 100644 --- a/src/backends/adb-backend.test.ts +++ b/src/backends/adb-backend.test.ts @@ -699,7 +699,10 @@ describe('AdbBackend.tapElement', () => { { identifier: 'submit' }, { element: { ...element, frame } }, ), - ).rejects.toThrow('Element is outside the 1080x2400 viewport'); + ).rejects.toMatchObject({ + code: 'ELEMENT_NOT_IN_VIEWPORT', + message: expect.stringContaining('outside the 1080x2400 viewport'), + }); expect(tapCalls()).toHaveLength(0); }); diff --git a/src/utils/element.ts b/src/utils/element.ts index 8e52466..d7163a8 100644 --- a/src/utils/element.ts +++ b/src/utils/element.ts @@ -281,7 +281,8 @@ export function formatHierarchy(elements: UIElement[], depth: number): string { * @param viewport.width - Viewport width. * @param viewport.height - Viewport height. * @returns The tap point. - * @throws When the frame does not intersect the viewport (or has no area). + * @throws An error with `code: 'ELEMENT_NOT_IN_VIEWPORT'` when the frame + * does not intersect the viewport (or has no area). */ export function visibleCenter( element: UIElement, @@ -292,12 +293,15 @@ export function visibleCenter( const x1 = Math.min(element.frame.x + element.frame.width, width); const y1 = Math.min(element.frame.y + element.frame.height, height); if (x1 <= x0 || y1 <= y0) { - throw new Error( - `Element is outside the ${width}x${height} viewport: ` + - `${describeElement(element)} at (${Math.round(element.frame.x)}, ` + - `${Math.round(element.frame.y)} ${Math.round(element.frame.width)}x` + - `${Math.round(element.frame.height)}). ` + - 'Scroll it into view first (device_swipe or scroll_to_element).', + throw Object.assign( + new Error( + `Element is outside the ${width}x${height} viewport: ` + + `${describeElement(element)} at (${Math.round(element.frame.x)}, ` + + `${Math.round(element.frame.y)} ${Math.round(element.frame.width)}x` + + `${Math.round(element.frame.height)}). ` + + 'Scroll it into view first (device_swipe or scroll_to_element).', + ), + { code: 'ELEMENT_NOT_IN_VIEWPORT' }, ); } return { From 268595e0b131d324592c01df1bb7c21c47bb4162 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Fri, 6 Nov 2026 09:38:51 -0600 Subject: [PATCH 15/33] refactor: simplify iOS tap hit-test plumbing --- src/backends/idb-backend.test.ts | 20 -------------- src/backends/idb-backend.ts | 46 +++++++++++--------------------- src/utils/hit-test.ts | 2 +- 3 files changed, 16 insertions(+), 52 deletions(-) diff --git a/src/backends/idb-backend.test.ts b/src/backends/idb-backend.test.ts index 1f7837d..092ddad 100644 --- a/src/backends/idb-backend.test.ts +++ b/src/backends/idb-backend.test.ts @@ -985,26 +985,6 @@ describe('IdbBackend tap hit-test', () => { expect(tapCalls()).toHaveLength(0); }); - it('refuses the tap when a key is at the point', async () => { - mockDevice({ - type: 'Key', - AXLabel: 'g', - frame: { x: 182, y: 651, width: 39, height: 54 }, - }); - const lowButton = { - ...loginButton, - frame: { x: 16, y: 660, width: 370, height: 48 }, - }; - - await expect( - backend.tapElement( - { identifier: 'log-in-button' }, - { element: lowButton }, - ), - ).rejects.toMatchObject({ code: 'TARGET_OBSCURED', keyboard: true }); - expect(tapCalls()).toHaveLength(0); - }); - it('refuses the tap when an overlay covers the target', async () => { mockDevice({ type: 'Other', diff --git a/src/backends/idb-backend.ts b/src/backends/idb-backend.ts index eb404f8..ae00d5f 100644 --- a/src/backends/idb-backend.ts +++ b/src/backends/idb-backend.ts @@ -30,11 +30,7 @@ import { visibleCenter, } from '../utils/element.js'; import { execStrict, exec } from '../utils/exec.js'; -import { - hitsTarget, - isKeyboardElement, - TargetObscuredError, -} from '../utils/hit-test.js'; +import { hitsTarget, TargetObscuredError } from '../utils/hit-test.js'; import { hardenArtifactFile, resolveArtifactPath, @@ -490,7 +486,7 @@ export class IdbBackend implements DeviceBackend { ); } - const { x, y } = await this.#visibleTapPoint(element); + const { x, y } = visibleCenter(element, await this.getWindowSize()); await this.#assertHittable(element, { x, y }); await this.tapCoordinates(x, y); @@ -502,12 +498,6 @@ export class IdbBackend implements DeviceBackend { }; } - async #visibleTapPoint( - element: UIElement, - ): Promise<{ x: number; y: number }> { - return visibleCenter(element, await this.getWindowSize()); - } - /** * Check that a tap at the point reaches the element, with one * `idb ui describe-point` (about 0.25 s). Throws when another element (an @@ -528,20 +518,19 @@ export class IdbBackend implements DeviceBackend { if (!this.#idbSupportsApi) { return; } - const args = [ - 'ui', - 'describe-point', - String(point.x), - String(point.y), - '--api', - 'axbridge', - '--json', - '--udid', - this.#udid, - ]; let raw: string; try { - raw = await this.#execStrict(this.#idbPath, args); + raw = await this.#execStrict(this.#idbPath, [ + 'ui', + 'describe-point', + String(point.x), + String(point.y), + '--api', + 'axbridge', + '--json', + '--udid', + this.#udid, + ]); } catch (error) { if (error instanceof IdbUnavailableError) { throw error; @@ -557,12 +546,7 @@ export class IdbBackend implements DeviceBackend { return; } if (!hitsTarget(element, hit)) { - throw new TargetObscuredError( - element, - hit, - point, - isKeyboardElement(hit), - ); + throw new TargetObscuredError(element, hit, point); } } @@ -904,7 +888,7 @@ export class IdbBackend implements DeviceBackend { ); } - const { x: cx, y: cy } = await this.#visibleTapPoint(element); + const { x: cx, y: cy } = visibleCenter(element, await this.getWindowSize()); await this.#assertHittable(element, { x: cx, y: cy }); await this.#execStrict(this.#idbPath, [ 'ui', diff --git a/src/utils/hit-test.ts b/src/utils/hit-test.ts index cff414d..09850d9 100644 --- a/src/utils/hit-test.ts +++ b/src/utils/hit-test.ts @@ -28,8 +28,8 @@ export class TargetObscuredError extends Error { target: UIElement, obscuredBy: UIElement, point: { x: number; y: number }, - keyboard: boolean, ) { + const keyboard = isKeyboardElement(obscuredBy); const advice = keyboard ? 'Dismiss the keyboard (device_dismiss_keyboard) and retry.' : 'Close the overlay, or scroll the target into a free area.'; From dbd6963147f31d2f5797dc3ed1c075c94ede9226 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Mon, 9 Nov 2026 09:12:46 +0000 Subject: [PATCH 16/33] feat: add HermesClient, a persistent Hermes CDP connection One verified Hermes socket serves many calls, so the identity probe and handshake are paid once. Responses are matched by CDP id and CDP events are dispatched to on() listeners. When the app reloads the socket closes: pending calls fail with HERMES_CONNECTION_FAILED and are not resent, then the client rediscovers the target and reconnects with exponential backoff, emitting reconnected and contextCreated. The device pin is enforced on every reconnect. runHermesCdp now uses the client (one connect, one send, close) with auto-reconnect disabled, keeping its codes and messages unchanged. --- src/hermes/hermes-cdp.ts | 190 +++--- src/hermes/hermes-client.test.ts | 704 +++++++++++++++++++++ src/hermes/hermes-client.ts | 1011 ++++++++++++++++++++++++++++++ src/index.ts | 17 + 4 files changed, 1836 insertions(+), 86 deletions(-) create mode 100644 src/hermes/hermes-client.test.ts create mode 100644 src/hermes/hermes-client.ts diff --git a/src/hermes/hermes-cdp.ts b/src/hermes/hermes-cdp.ts index 1375547..8015627 100644 --- a/src/hermes/hermes-cdp.ts +++ b/src/hermes/hermes-cdp.ts @@ -1,3 +1,8 @@ +// `hermes-client.ts` imports this module's discovery and socket helpers, so the +// two modules import each other. The cycle is safe: `hermes-client.ts` reads +// those bindings only while connecting, never during module evaluation. +import { HermesClient } from './hermes-client.js'; + /** * Pure Hermes Chrome DevTools Protocol (CDP) core for `@metamask/device-mcp`. * @@ -105,20 +110,33 @@ type CdpSuccessResponse = { result?: unknown; }; +/** + * A CDP-level error payload. + */ +export type HermesCdpErrorInfo = { + /** The CDP error message. */ + message?: string; + /** The CDP error code. */ + code?: number; + /** Optional structured error details. */ + data?: unknown; +}; + type CdpErrorResponse = { id: number; - error: { - message?: string; - code?: number; - data?: unknown; - }; + error: HermesCdpErrorInfo; }; type TargetSelection = | { ok: true; target: HermesTarget } | { ok: false; code: string; message: string }; -type ProbeResult = { ok: true } | { ok: false; code: string; message: string }; +/** + * Result of the Hermes identity probe. + */ +export type HermesIdentityProbeResult = + | { ok: true } + | { ok: false; code: string; message: string }; /** * No Hermes debug target matched the expected appId (after synthetic-title and @@ -174,6 +192,12 @@ export const HERMES_CDP_FAILED = 'HERMES_CDP_FAILED'; */ export const HERMES_WEBSOCKET_UNAVAILABLE = 'HERMES_WEBSOCKET_UNAVAILABLE'; +/** + * A pending CDP call was aborted through its `AbortSignal`. The pending entry is + * removed, so a late response is ignored. + */ +export const HERMES_ABORTED = 'HERMES_ABORTED'; + /** * CDP methods blocked for safety. Ported VERBATIM from the reference — do not * weaken. @@ -216,6 +240,46 @@ export const IDENTITY_PROBE_EXPR = `(function () { } })();`; +/** + * Returns the fail-closed result for a CDP method in the blocked set. + * + * @param method - The requested CDP method. + * @returns The `HERMES_BLOCKED_METHOD` failure, or undefined when not blocked. + */ +export function createBlockedMethodResult( + method: string, +): HermesCdpResult | undefined { + if (!HERMES_BLOCKED_METHODS.has(method)) { + return undefined; + } + return { + ok: false, + code: HERMES_BLOCKED_METHOD, + message: + `CDP method "${method}" is blocked for safety. ` + + `Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`, + }; +} + +/** + * Returns the failure result for a runtime without a global `WebSocket`. + * + * @returns The `HERMES_WEBSOCKET_UNAVAILABLE` failure. + */ +export function websocketUnavailableResult(): { + ok: false; + code: string; + message: string; +} { + return { + ok: false, + code: HERMES_WEBSOCKET_UNAVAILABLE, + message: + 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' + + 'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).', + }; +} + /** * Orchestrates a single verified Hermes CDP command end to end. * @@ -225,6 +289,9 @@ export const IDENTITY_PROBE_EXPR = `(function () { * supplies the resolved port/appId/pin and persists the pin — this function is * pure with respect to session state. * + * Implemented on {@link HermesClient}: one client, one connect, one send, then + * close. Auto-reconnect is disabled because a one-shot call owns the socket. + * * @param input - Method, params, timeout, resolved port/appId/pin, and the pin * persistence callback. See {@link RunHermesCdpInput}. * @returns A discriminated {@link HermesCdpResult}. @@ -232,65 +299,21 @@ export const IDENTITY_PROBE_EXPR = `(function () { export async function runHermesCdp( input: RunHermesCdpInput, ): Promise { - if (HERMES_BLOCKED_METHODS.has(input.method)) { - return { - ok: false, - code: HERMES_BLOCKED_METHOD, - message: - `CDP method "${input.method}" is blocked for safety. ` + - `Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`, - }; - } - - if (typeof WebSocket !== 'function') { - return { - ok: false, - code: HERMES_WEBSOCKET_UNAVAILABLE, - message: - 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' + - 'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).', - }; - } + const client = new HermesClient({ + metroPort: input.metroPort, + appId: input.appId, + origin: input.origin, + pinnedDeviceId: input.pinnedDeviceId, + onPin: input.onPin, + reconnect: { maxAttempts: 0 }, + }); try { - const targets = await fetchDiscoveryTargets( - input.metroPort, - input.timeoutMs, - ); - const selection = selectHermesTarget( - targets, - input.appId, - input.pinnedDeviceId, - ); - if (!selection.ok) { - return { ok: false, code: selection.code, message: selection.message }; - } - - const validation = validateWebSocketUrl( - selection.target.webSocketDebuggerUrl, - input.metroPort, - ); - if (!validation.ok) { - return { - ok: false, - code: HERMES_INVALID_WS_URL, - message: validation.message, - }; - } - - return await executeVerifiedCdpCommand( - selection.target, - input, - input.pinnedDeviceId, - input.onPin, - ); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - return { - ok: false, - code: HERMES_CONNECTION_FAILED, - message: `Hermes CDP connection failed: ${message}`, - }; + return await client.send(input.method, input.params, { + timeoutMs: input.timeoutMs, + }); + } finally { + client.close(); } } @@ -501,8 +524,9 @@ export function validateWebSocketUrl( * @param webSocketUrl - The target's WebSocket URL. * @param override - An explicit HTTP(S) origin, if configured. * @returns The HTTP(S) origin to send in the handshake. + * @throws When the explicit override is not a bare HTTP(S) origin. */ -function resolveWebSocketOrigin( +export function resolveWebSocketOrigin( webSocketUrl: string, override: string | undefined, ): string { @@ -562,13 +586,7 @@ export async function executeVerifiedCdpCommand( }; } if (typeof WebSocket !== 'function') { - return { - ok: false, - code: HERMES_WEBSOCKET_UNAVAILABLE, - message: - 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' + - 'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).', - }; + return websocketUnavailableResult(); } // Node's WebSocket supports this headers overload on Node 20 (with the @@ -616,7 +634,7 @@ export async function executeVerifiedCdpCommand( ok: false, code: HERMES_CDP_FAILED, message: `Hermes CDP "${input.method}" failed: ${formatCdpError( - response, + response.error, )}`, }; } @@ -635,13 +653,13 @@ export async function executeVerifiedCdpCommand( * @param socket - The open target WebSocket. * @param timeoutMs - Round-trip timeout in milliseconds. * @param id - The CDP message id to use for this probe. - * @returns A {@link ProbeResult}. + * @returns A {@link HermesIdentityProbeResult}. */ -async function runIdentityProbe( +export async function runIdentityProbe( socket: WebSocket, timeoutMs: number, id: number, -): Promise { +): Promise { socket.send( JSON.stringify({ id, @@ -673,7 +691,7 @@ async function runIdentityProbe( return { ok: false, code: HERMES_NOT_VERIFIED, - message: `Identity probe failed: ${formatCdpError(response)}`, + message: `Identity probe failed: ${formatCdpError(response.error)}`, }; } @@ -786,7 +804,7 @@ async function sendUserMethod( * @param timeoutMs - Connection timeout in milliseconds. * @returns A promise that resolves when the socket is open. */ -async function waitForSocketOpen( +export async function waitForSocketOpen( socket: WebSocket, timeoutMs: number, ): Promise { @@ -925,18 +943,18 @@ function isCdpErrorResponse( } /** - * Formats a CDP error response into a single human-readable line. + * Formats a CDP error payload into a single human-readable line. * - * @param response - The CDP error response. + * @param error - The CDP error payload. * @returns A combined message including code and data when present. */ -function formatCdpError(response: CdpErrorResponse): string { - const parts = [response.error.message ?? 'Unknown CDP error']; - if (typeof response.error.code === 'number') { - parts.push(`code ${response.error.code}`); +export function formatCdpError(error: HermesCdpErrorInfo): string { + const parts = [error.message ?? 'Unknown CDP error']; + if (typeof error.code === 'number') { + parts.push(`code ${error.code}`); } - if (response.error.data !== undefined) { - parts.push(JSON.stringify(response.error.data)); + if (error.data !== undefined) { + parts.push(JSON.stringify(error.data)); } return parts.join(' - '); } @@ -946,7 +964,7 @@ function formatCdpError(response: CdpErrorResponse): string { * * @param socket - The target WebSocket. */ -function closeSocket(socket: WebSocket): void { +export function closeSocket(socket: WebSocket): void { if ( socket.readyState === WebSocket.CONNECTING || socket.readyState === WebSocket.OPEN diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts new file mode 100644 index 0000000..41ce21e --- /dev/null +++ b/src/hermes/hermes-client.test.ts @@ -0,0 +1,704 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { HermesCdpResult } from './hermes-cdp.js'; +import { + HERMES_ABORTED, + HERMES_BLOCKED_METHOD, + HERMES_CDP_FAILED, + HERMES_CONNECTION_FAILED, + HERMES_TIMEOUT, + HERMES_WEBSOCKET_UNAVAILABLE, + IDENTITY_PROBE_EXPR, +} from './hermes-cdp.js'; +import { HermesClient } from './hermes-client.js'; +import type { HermesCdpEvent, HermesClientOptions } from './hermes-client.js'; + +const APP_ID = 'io.metamask.MetaMask'; +const METRO_PORT = 8085; +const SOCKET_URL = `ws://localhost:${METRO_PORT}/inspector/debug?device=device-1&page=1`; + +type CdpRequest = { + id?: number; + method?: string; + params?: Record; +}; + +type MockResponse = Record | string | undefined; + +class FakeWebSocket extends EventTarget { + static readonly connecting = 0; + + static readonly openState = 1; + + static readonly closing = 2; + + static readonly closed = 3; + + static instances: FakeWebSocket[] = []; + + static autoOpen = true; + + static responseFactory: ((request: CdpRequest) => MockResponse) | undefined; + + readonly url: string; + + readonly options: { headers: { origin: string } } | undefined; + + readonly sent: CdpRequest[] = []; + + readyState = FakeWebSocket.connecting; + + constructor(url: string, options?: { headers: { origin: string } }) { + super(); + this.url = url; + this.options = options; + FakeWebSocket.instances.push(this); + + if (FakeWebSocket.autoOpen) { + queueMicrotask(() => this.open()); + } + } + + send(raw: string): void { + const request = JSON.parse(raw) as CdpRequest; + this.sent.push(request); + const response = FakeWebSocket.responseFactory?.(request); + if (response !== undefined) { + const payload = + typeof response === 'string' ? response : JSON.stringify(response); + queueMicrotask(() => this.receive(payload)); + } + } + + close(): void { + if (this.readyState === FakeWebSocket.closed) { + return; + } + this.readyState = FakeWebSocket.closed; + this.dispatchEvent(new Event('close')); + } + + open(): void { + this.readyState = FakeWebSocket.openState; + this.dispatchEvent(new Event('open')); + } + + receive(data: string): void { + this.dispatchEvent(new MessageEvent('message', { data })); + } + + /** + * Simulates the app reloading or Metro restarting: the remote end drops the + * socket without the client asking for it. + * + * @param reason - The close reason reported by the remote end. + */ + drop(reason = ''): void { + this.readyState = FakeWebSocket.closed; + const event = new Event('close'); + Object.defineProperty(event, 'reason', { value: reason }); + this.dispatchEvent(event); + } +} + +Object.defineProperties(FakeWebSocket, { + CONNECTING: { value: FakeWebSocket.connecting }, + OPEN: { value: FakeWebSocket.openState }, + CLOSING: { value: FakeWebSocket.closing }, + CLOSED: { value: FakeWebSocket.closed }, +}); + +let fetchMock: ReturnType; + +function target( + overrides: Record = {}, +): Record { + return { + id: 'device-page-1', + title: 'io.metamask.MetaMask (iPhone 15)', + appId: APP_ID, + webSocketDebuggerUrl: SOCKET_URL, + reactNative: { + logicalDeviceId: 'logical-device-1', + capabilities: { nativePageReloads: true }, + }, + ...overrides, + }; +} + +function mockDiscovery(targets: unknown[]): void { + fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: vi.fn().mockResolvedValue(targets), + }); + vi.stubGlobal('fetch', fetchMock); +} + +function isIdentityProbe(request: CdpRequest): boolean { + return request.params?.expression === IDENTITY_PROBE_EXPR; +} + +function probeResponse(request: CdpRequest): Record { + return { + id: request.id, + result: { + result: { + type: 'string', + value: '{"isHermes":true,"ossVersion":"0.19.0","debuggerEnabled":true}', + }, + }, + }; +} + +function defaultResponseFactory(request: CdpRequest): Record { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + return { id: request.id, result: { result: { type: 'number', value: 2 } } }; +} + +function probeOnly(request: CdpRequest): MockResponse { + return isIdentityProbe(request) ? probeResponse(request) : undefined; +} + +function socketAt(index: number): FakeWebSocket { + const socket = FakeWebSocket.instances[index]; + if (!socket) { + throw new Error(`Missing FakeWebSocket instance ${index}`); + } + return socket; +} + +function createClient( + overrides: Partial = {}, +): HermesClient { + return new HermesClient({ + metroPort: METRO_PORT, + appId: APP_ID, + ...overrides, + }); +} + +function expectError( + result: HermesCdpResult, + code: string, +): asserts result is { ok: false; code: string; message: string } { + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.code).toBe(code); + } +} + +/** + * Lets every pending microtask (discovery, socket open, probe) settle. + * + * @returns A promise resolved after a macrotask. + */ +async function flush(): Promise { + await new Promise((resolve) => setTimeout(resolve, 0)); +} + +/** + * Waits for a fixed duration. + * + * @param ms - Milliseconds to wait. + * @returns A promise resolved after the delay. + */ +async function delay(ms: number): Promise { + await new Promise((resolve) => setTimeout(resolve, ms)); +} + +describe('HermesClient', () => { + beforeEach(() => { + FakeWebSocket.instances = []; + FakeWebSocket.autoOpen = true; + FakeWebSocket.responseFactory = defaultResponseFactory; + vi.stubGlobal('WebSocket', FakeWebSocket); + mockDiscovery([target()]); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it('connects once and runs the identity probe once across many sends', async () => { + const client = createClient(); + + const first = await client.send( + 'Runtime.evaluate', + { expression: '1+1', returnByValue: true }, + { timeoutMs: 1_000 }, + ); + const second = await client.send( + 'Runtime.evaluate', + { expression: '2+2', returnByValue: true }, + { timeoutMs: 1_000 }, + ); + + expect(first).toStrictEqual({ + ok: true, + result: { result: { type: 'number', value: 2 } }, + }); + expect(second.ok).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + + const socket = socketAt(0); + expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2, 3]); + expect(socket.sent.filter(isIdentityProbe)).toHaveLength(1); + expect(socket.options?.headers.origin).toBe( + `http://127.0.0.1:${METRO_PORT}`, + ); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('shares one in-flight connect and emits contextCreated once', async () => { + const client = createClient(); + const created = vi.fn(); + client.on('contextCreated', created); + + const [first, second] = await Promise.all([ + client.connect({ timeoutMs: 1_000 }), + client.connect({ timeoutMs: 1_000 }), + ]); + + expect(first.ok).toBe(true); + expect(second).toStrictEqual(first); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(created).toHaveBeenCalledTimes(1); + expect(created).toHaveBeenCalledWith({ + target: { + id: 'device-page-1', + logicalDeviceId: 'logical-device-1', + title: 'io.metamask.MetaMask (iPhone 15)', + }, + reconnected: false, + }); + }); + + it('returns the current target when already connected', async () => { + const client = createClient(); + await client.connect({ timeoutMs: 1_000 }); + + const again = await client.connect({ timeoutMs: 1_000 }); + + expect(again.ok).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(1); + }); + + it('matches concurrent responses by id, even out of order', async () => { + FakeWebSocket.responseFactory = probeOnly; + const client = createClient(); + + const first = client.send( + 'Runtime.evaluate', + { expression: 'a' }, + { timeoutMs: 5_000 }, + ); + const second = client.send( + 'Runtime.evaluate', + { expression: 'b' }, + { timeoutMs: 5_000 }, + ); + + await flush(); + const socket = socketAt(0); + expect(socket.sent).toHaveLength(3); + + socket.receive(JSON.stringify({ id: 3, result: 'b' })); + socket.receive(JSON.stringify({ id: 2, result: 'a' })); + + expect(await second).toStrictEqual({ ok: true, result: 'b' }); + expect(await first).toStrictEqual({ ok: true, result: 'a' }); + }); + + it('fails with HERMES_TIMEOUT on a per-call timeout and drops the pending entry', async () => { + FakeWebSocket.responseFactory = probeOnly; + const client = createClient(); + + const result = await client.send( + 'Runtime.evaluate', + { expression: 'never' }, + { timeoutMs: 30 }, + ); + + expectError(result, HERMES_TIMEOUT); + expect(result.message).toBe('Hermes CDP call timed out after 30ms'); + + // The late response must be ignored, and the next call gets a fresh id. + const socket = socketAt(0); + socket.receive(JSON.stringify({ id: 2, result: 'late' })); + FakeWebSocket.responseFactory = defaultResponseFactory; + const next = await client.send( + 'Runtime.evaluate', + {}, + { timeoutMs: 1_000 }, + ); + + expect(next.ok).toBe(true); + expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2, 3]); + }); + + it('fails with HERMES_ABORTED when the signal aborts and drops the pending entry', async () => { + FakeWebSocket.responseFactory = probeOnly; + const controller = new AbortController(); + const client = createClient(); + + const pending = client.send( + 'Runtime.evaluate', + { expression: 'slow' }, + { timeoutMs: 5_000, signal: controller.signal }, + ); + await flush(); + controller.abort(); + + const result = await pending; + expectError(result, HERMES_ABORTED); + expect(result.message).toContain('aborted'); + + const socket = socketAt(0); + socket.receive(JSON.stringify({ id: 2, result: 'late' })); + FakeWebSocket.responseFactory = defaultResponseFactory; + const next = await client.send( + 'Runtime.evaluate', + {}, + { timeoutMs: 1_000 }, + ); + + expect(next.ok).toBe(true); + expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2, 3]); + }); + + it('does not connect for an already-aborted signal', async () => { + const controller = new AbortController(); + controller.abort(); + const client = createClient(); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + signal: controller.signal, + }); + + expectError(result, HERMES_ABORTED); + expect(fetchMock).not.toHaveBeenCalled(); + expect(FakeWebSocket.instances).toHaveLength(0); + }); + + it('formats a CDP error into HERMES_CDP_FAILED', async () => { + FakeWebSocket.responseFactory = (request) => + isIdentityProbe(request) + ? probeResponse(request) + : { + id: request.id, + error: { + message: 'Bad params', + code: -32602, + data: { reason: 'invalid' }, + }, + }; + const client = createClient(); + + const result = await client.send('Missing.method', undefined, { + timeoutMs: 1_000, + }); + + expectError(result, HERMES_CDP_FAILED); + expect(result.message).toContain('"Missing.method"'); + expect(result.message).toContain('Bad params'); + expect(result.message).toContain('{"reason":"invalid"}'); + }); + + it('dispatches CDP events to on() listeners and stops after off()', async () => { + const client = createClient(); + const received: HermesCdpEvent[] = []; + const listener = (event: HermesCdpEvent): void => { + received.push(event); + }; + client.on('Runtime.consoleAPICalled', listener); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + + socket.receive( + JSON.stringify({ + method: 'Runtime.consoleAPICalled', + params: { type: 'log', args: [] }, + }), + ); + expect(received).toStrictEqual([ + { + method: 'Runtime.consoleAPICalled', + params: { type: 'log', args: [] }, + }, + ]); + + client.off('Runtime.consoleAPICalled', listener); + socket.receive( + JSON.stringify({ method: 'Runtime.consoleAPICalled', params: {} }), + ); + expect(received).toHaveLength(1); + }); + + it('ignores malformed and unknown-id frames', async () => { + const client = createClient(); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + + socket.receive('not json'); + socket.receive('42'); + socket.receive(JSON.stringify({ result: { ignored: true } })); + socket.receive(JSON.stringify({ id: 999, result: 'unknown' })); + + const next = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expect(next.ok).toBe(true); + }); + + it('pins the device on first connect and does not call onPin again', async () => { + const onPin = vi.fn(); + const client = createClient({ onPin }); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + expect(onPin).toHaveBeenCalledTimes(1); + expect(onPin).toHaveBeenCalledWith('logical-device-1'); + }); + + it('does not call onPin when a pin already exists', async () => { + const onPin = vi.fn(); + const client = createClient({ pinnedDeviceId: 'logical-device-1', onPin }); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + expect(onPin).not.toHaveBeenCalled(); + }); + + it('fails with HERMES_BLOCKED_METHOD without discovering or connecting', async () => { + const client = createClient(); + + const result = await client.send('Runtime.terminateExecution', undefined, { + timeoutMs: 1_000, + }); + + expectError(result, HERMES_BLOCKED_METHOD); + expect(result.message).toContain('Inspector.detached'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(FakeWebSocket.instances).toHaveLength(0); + }); + + it('fails with HERMES_WEBSOCKET_UNAVAILABLE without discovering', async () => { + vi.stubGlobal('WebSocket', undefined); + const client = createClient(); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result).toMatchObject({ + ok: false, + code: HERMES_WEBSOCKET_UNAVAILABLE, + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('propagates a discovery failure as HERMES_CONNECTION_FAILED', async () => { + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + const client = createClient(); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('ECONNREFUSED'), + }); + expect(client.isConnected).toBe(false); + }); + + it('closing fails pending calls and closes the socket', async () => { + FakeWebSocket.responseFactory = probeOnly; + const client = createClient(); + + const pending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 5_000, + }); + await flush(); + client.close(); + client.close(); + + const result = await pending; + expectError(result, HERMES_CONNECTION_FAILED); + expect(result.message).toContain('HermesClient is closed'); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + expect(client.isConnected).toBe(false); + }); + + it('reports the configured port and app id', () => { + const client = createClient({ appId: 'io.metamask', metroPort: 9000 }); + + expect(client.metroPort).toBe(9000); + expect(client.appId).toBe('io.metamask'); + }); + + it('reconnects after an unexpected close, rediscovers the target and emits contextCreated again', async () => { + const client = createClient({ + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const disconnected: { reason: string }[] = []; + const reconnected: unknown[] = []; + const created: unknown[] = []; + client.on('disconnected', (event) => disconnected.push(event)); + client.on('reconnected', (event) => reconnected.push(event)); + client.on('contextCreated', (event) => created.push(event)); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + expect(created).toHaveLength(1); + expect(FakeWebSocket.instances).toHaveLength(1); + + FakeWebSocket.responseFactory = probeOnly; + const pending = client.send('Network.enable', undefined, { + timeoutMs: 5_000, + }); + await flush(); + expect(socketAt(0).sent).toHaveLength(3); + + // The app reloads: the target id and URL change behind the same Metro port. + mockDiscovery([ + target({ + id: 'device-page-2', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-1&page=2`, + }), + ]); + socketAt(0).drop('app reload'); + + const pendingResult = await pending; + expectError(pendingResult, HERMES_CONNECTION_FAILED); + expect(pendingResult.message).toContain('app reload'); + expect(disconnected).toStrictEqual([{ reason: 'app reload' }]); + expect(client.isConnected).toBe(false); + + await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(2)); + await vi.waitFor(() => expect(created).toHaveLength(2)); + + expect(socketAt(1).url).toContain('page=2'); + // The reconnect re-ran discovery through the second fetch stub. + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(reconnected).toStrictEqual([ + { + target: { + id: 'device-page-2', + logicalDeviceId: 'logical-device-1', + title: 'io.metamask.MetaMask (iPhone 15)', + }, + attempts: 1, + }, + ]); + expect(created[1]).toMatchObject({ + reconnected: true, + target: { id: 'device-page-2' }, + }); + expect(client.isConnected).toBe(true); + + // eslint-disable-next-line require-atomic-updates -- test-double state, not shared across async work + FakeWebSocket.responseFactory = defaultResponseFactory; + const after = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expect(after.ok).toBe(true); + expect(socketAt(1).sent.map((request) => request.id)).toStrictEqual([1, 2]); + }); + + it('retries with backoff and gives up after maxAttempts', async () => { + const client = createClient({ + reconnect: { initialDelayMs: 5, maxDelayMs: 10, maxAttempts: 2 }, + }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('app reload'); + + await delay(60); + + // Two attempts, then the client gives up (no socket was ever adopted). + expect(fetchMock).toHaveBeenCalledTimes(4); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(false); + }); + + it('does not reconnect to a different device after a reload (pin mismatch)', async () => { + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const reconnected = vi.fn(); + const created = vi.fn(); + client.on('reconnected', reconnected); + client.on('contextCreated', created); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + expect(FakeWebSocket.instances).toHaveLength(1); + + mockDiscovery([ + target({ + id: 'other-device', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-2&page=1`, + reactNative: { + logicalDeviceId: 'logical-device-2', + capabilities: { nativePageReloads: true }, + }, + }), + ]); + socketAt(0).drop('app reload'); + + await delay(80); + + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(false); + expect(reconnected).not.toHaveBeenCalled(); + expect(created).toHaveBeenCalledTimes(1); + }); + + it('close() stops a scheduled reconnect', async () => { + const client = createClient({ + reconnect: { initialDelayMs: 20, maxDelayMs: 40, maxAttempts: 3 }, + }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + socketAt(0).drop('app reload'); + client.close(); + + await delay(80); + + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('connects again on the next send after the reconnect loop gave up', async () => { + const client = createClient({ + reconnect: { initialDelayMs: 5, maxDelayMs: 10, maxAttempts: 1 }, + }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('app reload'); + await delay(40); + + mockDiscovery([target({ id: 'device-page-3' })]); + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result.ok).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(socketAt(1).url).toBe(SOCKET_URL); + }); +}); diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts new file mode 100644 index 0000000..889f5f6 --- /dev/null +++ b/src/hermes/hermes-client.ts @@ -0,0 +1,1011 @@ +/** + * Persistent Hermes Chrome DevTools Protocol (CDP) client for + * `@metamask/device-mcp`. + * + * `runHermesCdp` opens one WebSocket per call, which costs a `/json` discovery + * fetch and a handshake every time and cannot receive CDP events. This client + * keeps ONE verified socket open for many calls and dispatches the CDP events + * (messages without an `id`, e.g. `Runtime.consoleAPICalled`) to listeners. + * + * It keeps every fail-closed safety check of the one-shot path: strict `appId` + * selection, the Hermes identity probe once per socket, the device pin, the + * WebSocket URL validation, and the blocked-method set. + * + * When the app reloads (or Metro restarts) the socket closes. Pending calls are + * failed with `HERMES_CONNECTION_FAILED` and NOT resent (they may have run), then + * the client rediscovers the target (its id and URL change after a reload) and + * reconnects with exponential backoff. Every successful (re)connect emits + * `contextCreated` so callers can re-apply their scripts (page reloads reset the + * runtime). + */ + +import type { HermesCdpResult } from './hermes-cdp.js'; +import { + closeSocket, + createBlockedMethodResult, + fetchDiscoveryTargets, + formatCdpError, + HERMES_ABORTED, + HERMES_CDP_FAILED, + HERMES_CONNECTION_FAILED, + HERMES_DEVICE_PIN_MISMATCH, + HERMES_INVALID_WS_URL, + HERMES_NOT_VERIFIED, + HERMES_TARGET_NOT_FOUND, + HERMES_TIMEOUT, + HERMES_WEBSOCKET_UNAVAILABLE, + resolveWebSocketOrigin, + runIdentityProbe, + selectHermesTarget, + validateWebSocketUrl, + waitForSocketOpen, + websocketUnavailableResult, +} from './hermes-cdp.js'; + +/** Default first backoff delay after an unexpected disconnect. */ +const DEFAULT_RECONNECT_INITIAL_DELAY_MS = 250; + +/** Default upper bound for the exponential backoff delay. */ +const DEFAULT_RECONNECT_MAX_DELAY_MS = 5_000; + +/** Default number of automatic reconnect attempts before giving up. */ +const DEFAULT_RECONNECT_MAX_ATTEMPTS = 6; + +/** Connect timeout used by the automatic reconnect loop. */ +const DEFAULT_RECONNECT_TIMEOUT_MS = 10_000; + +/** Message used when a call is made after {@link HermesClient.close}. */ +const CLIENT_CLOSED_MESSAGE = 'HermesClient is closed'; + +/** + * Options for the automatic reconnect loop. + */ +export type HermesClientReconnectOptions = { + /** First backoff delay in milliseconds (doubles on every attempt). */ + initialDelayMs?: number; + /** Upper bound for the backoff delay in milliseconds. */ + maxDelayMs?: number; + /** + * Number of attempts before giving up. When the loop gives up the client + * reports itself disconnected and the next {@link HermesClient.send} tries a + * fresh connect. `0` disables auto-reconnect. + */ + maxAttempts?: number; +}; + +/** + * Options for constructing a {@link HermesClient}. + */ +export type HermesClientOptions = { + /** The resolved Metro inspector proxy port. */ + metroPort: number; + /** The expected app bundle identifier (strict-matched against targets). */ + appId: string; + /** Override the HTTP(S) Origin for Metro's debugger WebSocket handshake. */ + origin?: string; + /** The pinned `logicalDeviceId` for this session, if one has been set. */ + pinnedDeviceId?: string; + /** + * Callback invoked with the resolved `logicalDeviceId` on the FIRST + * successful identity probe so the caller can persist the pin. + */ + onPin?: (logicalDeviceId: string) => void; + /** Automatic reconnect tuning. */ + reconnect?: HermesClientReconnectOptions; +}; + +/** + * Options for {@link HermesClient.connect}. + */ +export type HermesConnectOptions = { + /** Timeout in milliseconds for discovery, the socket open and the probe. */ + timeoutMs: number; +}; + +/** + * The verified target the client is (or was last) connected to. + */ +export type HermesConnectedTarget = { + /** Metro's per-target identifier (changes after an app reload). */ + id: string | undefined; + /** The verified `reactNative.logicalDeviceId` of the target. */ + logicalDeviceId: string; + /** Human-readable target title. */ + title: string | undefined; +}; + +/** + * Result of {@link HermesClient.connect}. + */ +export type HermesConnectResult = + | { ok: true; target: HermesConnectedTarget } + | { ok: false; code: string; message: string }; + +/** + * Options for {@link HermesClient.send}. + */ +export type HermesSendOptions = { + /** Per-call timeout in milliseconds. */ + timeoutMs: number; + /** Aborts the call; the pending response is discarded. */ + signal?: AbortSignal; +}; + +/** + * A CDP event: a message without an `id` that carries a `method`. + */ +export type HermesCdpEvent = { + /** The CDP event method, e.g. `Runtime.consoleAPICalled`. */ + method: string; + /** The event payload as sent by Hermes. */ + params: unknown; +}; + +/** + * Payload of the `contextCreated` lifecycle event, emitted after every + * successful connect (including the first one) and after every reconnect. + */ +export type HermesContextCreatedEvent = { + /** The verified target of the new connection. */ + target: HermesConnectedTarget; + /** True for a reconnect, false for the initial connect. */ + reconnected: boolean; +}; + +/** + * Payload of the `disconnected` lifecycle event. + */ +export type HermesDisconnectedEvent = { + /** Why the socket was lost (close reason or `WebSocket error`). */ + reason: string; +}; + +/** + * Payload of the `reconnected` lifecycle event, emitted just before the + * `contextCreated` event of a successful automatic reconnect. + */ +export type HermesReconnectedEvent = { + /** The verified target of the new connection. */ + target: HermesConnectedTarget; + /** How many backoff attempts were needed. */ + attempts: number; +}; + +/** + * Lifecycle events with a typed payload. Any other event name is a CDP event + * and receives a {@link HermesCdpEvent}. + */ +export type HermesClientEventMap = { + contextCreated: HermesContextCreatedEvent; + disconnected: HermesDisconnectedEvent; + reconnected: HermesReconnectedEvent; +}; + +type HermesClientStatus = 'idle' | 'connecting' | 'open' | 'closed'; + +type HermesEventListener = (payload: never) => void; + +type PendingCall = { + /** The CDP method, used in error messages. */ + method: string; + /** Per-call timeout handle. */ + timer: ReturnType; + /** Removes the abort listener, if one was registered. */ + detachAbort: () => void; + /** Resolves the caller exactly once. */ + resolve: (result: HermesCdpResult) => void; +}; + +/** + * Persistent, verified Hermes CDP connection. + * + * Create one per session, call {@link send} for CDP methods (it connects on the + * first call), subscribe with {@link on}, and call {@link close} when done. + */ +export class HermesClient { + readonly #metroPort: number; + + readonly #appId: string; + + readonly #origin: string | undefined; + + readonly #onPin: ((logicalDeviceId: string) => void) | undefined; + + readonly #reconnect: Required; + + readonly #listeners = new Map>(); + + readonly #pending = new Map(); + + #pinnedDeviceId: string | undefined; + + #socket: WebSocket | undefined; + + #target: HermesConnectedTarget | undefined; + + #status: HermesClientStatus = 'idle'; + + #nextId = 1; + + #inFlightConnect: Promise | undefined; + + #reconnectTimer: ReturnType | undefined; + + #reconnectAttempt = 0; + + #connectTimeoutMs = DEFAULT_RECONNECT_TIMEOUT_MS; + + #explicitlyClosed = false; + + constructor(options: HermesClientOptions) { + this.#metroPort = options.metroPort; + this.#appId = options.appId; + this.#origin = options.origin; + this.#pinnedDeviceId = options.pinnedDeviceId; + this.#onPin = options.onPin; + this.#reconnect = { + initialDelayMs: + options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS, + maxDelayMs: + options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS, + maxAttempts: + options.reconnect?.maxAttempts ?? DEFAULT_RECONNECT_MAX_ATTEMPTS, + }; + } + + /** + * The Metro inspector proxy port this client discovers targets on. + * + * @returns The configured port. + */ + get metroPort(): number { + return this.#metroPort; + } + + /** + * The app bundle identifier this client strictly matches targets against. + * + * @returns The configured app id. + */ + get appId(): string { + return this.#appId; + } + + /** + * Whether an adopted, verified socket is currently open. + * + * @returns True while the client can send without connecting. + */ + get isConnected(): boolean { + return this.#status === 'open' && this.#socket !== undefined; + } + + /** + * Discovers, opens, verifies and adopts a Hermes target. + * + * Idempotent: when already connected it resolves with the current target, and + * concurrent callers share one in-flight connect (one discovery fetch, one + * socket, one identity probe). Emits `contextCreated` on success. A client + * closed with {@link close} reopens. + * + * @param options - The connect timeout. + * @returns The verified target or a classified failure. + */ + async connect(options: HermesConnectOptions): Promise { + const { timeoutMs } = options; + this.#explicitlyClosed = false; + this.#clearReconnectTimer(); + this.#reconnectAttempt = 0; + this.#connectTimeoutMs = timeoutMs; + + if (this.isConnected && this.#target) { + return { ok: true, target: this.#target }; + } + + return await this.#connectOnce(timeoutMs); + } + + /** + * Sends one CDP method over the persistent socket and awaits its response. + * + * Connects first when needed. Many calls can be in flight: responses are + * matched by CDP `id`. On timeout the call fails with `HERMES_TIMEOUT`; on + * abort with `HERMES_ABORTED`. Both remove the pending entry, so a late + * response is ignored. A CDP-level error becomes `HERMES_CDP_FAILED`. + * + * @param method - The CDP method, e.g. `Runtime.evaluate`. + * @param params - The CDP parameters. + * @param options - Per-call timeout and optional abort signal. + * @returns The raw CDP `result`, or a classified failure. + */ + async send( + method: string, + params: Record | undefined, + options: HermesSendOptions, + ): Promise { + const { timeoutMs, signal } = options; + + const blocked = createBlockedMethodResult(method); + if (blocked) { + return blocked; + } + if (this.#explicitlyClosed) { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: CLIENT_CLOSED_MESSAGE, + }; + } + if (signal?.aborted) { + return abortedResult(method); + } + + if (!this.isConnected) { + const connected = await this.connect({ timeoutMs }); + if (!connected.ok) { + return connected; + } + } + if (signal?.aborted) { + return abortedResult(method); + } + + const socket = this.#socket; + if (socket === undefined) { + return connectionNotOpenResult(); + } + if (socket.readyState !== WebSocket.OPEN) { + return connectionNotOpenResult(); + } + + const id = this.#nextId; + this.#nextId += 1; + const response = new Promise((resolve) => { + const timer = setTimeout(() => { + this.#settle(id, { + ok: false, + code: HERMES_TIMEOUT, + message: `Hermes CDP call timed out after ${timeoutMs}ms`, + }); + }, timeoutMs); + unrefTimer(timer); + + let detachAbort = (): void => undefined; + if (signal) { + const handleAbort = (): void => { + this.#settle(id, abortedResult(method)); + }; + signal.addEventListener('abort', handleAbort); + detachAbort = (): void => { + signal.removeEventListener('abort', handleAbort); + }; + } + + this.#pending.set(id, { method, timer, detachAbort, resolve }); + }); + + try { + socket.send(JSON.stringify({ id, method, params: params ?? {} })); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + this.#settle(id, { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: `Hermes CDP connection failed: ${message}`, + }); + } + + return await response; + } + + /** + * Subscribes to a lifecycle event or a CDP event. + * + * Lifecycle names are `contextCreated`, `disconnected` and `reconnected`. + * Any other name receives the CDP event messages of that `method` + * (for example `Runtime.consoleAPICalled`). + * + * @param event - The lifecycle event name or CDP method name. + * @param listener - Called with the typed lifecycle payload or the CDP event. + */ + on( + event: EventName, + listener: (payload: HermesClientEventMap[EventName]) => void, + ): void; + + on(event: string, listener: (payload: HermesCdpEvent) => void): void; + + on(event: string, listener: HermesEventListener): void { + let listeners = this.#listeners.get(event); + if (!listeners) { + listeners = new Set(); + this.#listeners.set(event, listeners); + } + listeners.add(listener); + } + + /** + * Removes a listener previously added with {@link on}. + * + * @param event - The event name the listener was registered for. + * @param listener - The listener reference to remove. + */ + off( + event: EventName, + listener: (payload: HermesClientEventMap[EventName]) => void, + ): void; + + off(event: string, listener: (payload: HermesCdpEvent) => void): void; + + off(event: string, listener: HermesEventListener): void { + this.#listeners.get(event)?.delete(listener); + } + + /** + * Stops reconnecting, closes the socket and fails pending calls. + * + * Idempotent. A later {@link connect} reopens the client. + */ + close(): void { + this.#explicitlyClosed = true; + this.#clearReconnectTimer(); + this.#failAllPending( + HERMES_CONNECTION_FAILED, + `${CLIENT_CLOSED_MESSAGE}: the connection was closed`, + ); + + const socket = this.#socket; + this.#socket = undefined; + this.#target = undefined; + this.#status = 'closed'; + + if (socket) { + this.#detachSocket(); + closeSocket(socket); + } + } + + /** + * Shares one in-flight connect between concurrent callers and emits the + * connect lifecycle events once. + * + * @param timeoutMs - The connect timeout. + * @param reconnectAttempts - Set for a reconnect attempt, used for the + * `reconnected` payload and to distinguish the reordered lifecycle events. + * @returns The connect result. + */ + async #connectOnce( + timeoutMs: number, + reconnectAttempts?: number, + ): Promise { + const existing = this.#inFlightConnect; + if (existing) { + return await existing; + } + + const isReconnect = reconnectAttempts !== undefined; + const promise = this.#doConnect(timeoutMs, isReconnect) + .then((result) => { + if (result.ok) { + if (isReconnect) { + this.#emit('reconnected', { + target: result.target, + attempts: reconnectAttempts, + }); + } + this.#emit('contextCreated', { + target: result.target, + reconnected: isReconnect, + }); + } + return result; + }) + .finally(() => { + if (this.#inFlightConnect === promise) { + this.#inFlightConnect = undefined; + } + }); + + this.#inFlightConnect = promise; + return await promise; + } + + /** + * Discovers, opens, probes and adopts a target. Never throws. + * + * @param timeoutMs - The connect timeout. + * @param reconnect - True for an automatic reconnect attempt. + * @returns The verified target or a classified failure. + */ + async #doConnect( + timeoutMs: number, + reconnect: boolean, + ): Promise { + if (typeof WebSocket !== 'function') { + this.#status = 'closed'; + return websocketUnavailableResult(); + } + + this.#status = 'connecting'; + let socket: WebSocket | undefined; + let adopted = false; + + try { + const targets = await fetchDiscoveryTargets(this.#metroPort, timeoutMs); + + const selection = selectHermesTarget( + targets, + this.#appId, + this.#pinnedDeviceId, + ); + if (!selection.ok) { + const pinMismatch = this.#detectReconnectPinMismatch( + targets, + selection.code, + reconnect, + ); + if (pinMismatch) { + return pinMismatch; + } + return { + ok: false, + code: selection.code, + message: selection.message, + }; + } + + const url = selection.target.webSocketDebuggerUrl; + if (!url) { + return { + ok: false, + code: HERMES_INVALID_WS_URL, + message: 'Target is missing webSocketDebuggerUrl', + }; + } + const validation = validateWebSocketUrl(url, this.#metroPort); + if (!validation.ok) { + return { + ok: false, + code: HERMES_INVALID_WS_URL, + message: validation.message, + }; + } + + const origin = resolveWebSocketOrigin(url, this.#origin); + const WebSocketWithHeaders = WebSocket as typeof WebSocket & + (new ( + wsUrl: string, + options: { headers: { origin: string } }, + ) => WebSocket); + const connectingSocket = new WebSocketWithHeaders(url, { + headers: { origin }, + }); + socket = connectingSocket; + + await waitForSocketOpen(connectingSocket, timeoutMs); + + // The probe runs once per socket, with id 1; user calls start at 2. + const probe = await runIdentityProbe(connectingSocket, timeoutMs, 1); + if (!probe.ok) { + return { ok: false, code: probe.code, message: probe.message }; + } + + const targetDeviceId = selection.target.reactNative?.logicalDeviceId; + if (!targetDeviceId) { + return { + ok: false, + code: HERMES_NOT_VERIFIED, + message: 'Target is missing reactNative.logicalDeviceId', + }; + } + if (this.#pinnedDeviceId === undefined) { + this.#pinnedDeviceId = targetDeviceId; + this.#onPin?.(targetDeviceId); + } else if (this.#pinnedDeviceId !== targetDeviceId) { + return { + ok: false, + code: HERMES_DEVICE_PIN_MISMATCH, + message: `Hermes target device ${targetDeviceId} does not match session pin ${this.#pinnedDeviceId}`, + }; + } + if (this.#explicitlyClosed) { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: `${CLIENT_CLOSED_MESSAGE} before the connection completed`, + }; + } + + this.#adopt(connectingSocket, timeoutMs); + adopted = true; + this.#status = 'open'; + + const target: HermesConnectedTarget = { + id: selection.target.id, + logicalDeviceId: targetDeviceId, + title: selection.target.title, + }; + this.#target = target; + return { ok: true, target }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: `Hermes CDP connection failed: ${message}`, + }; + } finally { + if (!adopted) { + this.#status = 'closed'; + if (socket) { + closeSocket(socket); + } + } + } + } + + /** + * Turns a pinned selection failure into `HERMES_DEVICE_PIN_MISMATCH` during a + * reconnect when Metro reports a different device. Inspection only: no socket + * is opened for the wrong device. + * + * @param targets - All discovered targets. + * @param code - The selection failure code. + * @param reconnect - True for an automatic reconnect attempt. + * @returns The mismatch result, or undefined to keep the selection failure. + */ + #detectReconnectPinMismatch( + targets: Parameters[0], + code: string, + reconnect: boolean, + ): { ok: false; code: string; message: string } | undefined { + const pinnedDeviceId = this.#pinnedDeviceId; + if (!reconnect || !pinnedDeviceId || code !== HERMES_TARGET_NOT_FOUND) { + return undefined; + } + + const unpinned = selectHermesTarget(targets, this.#appId, undefined); + if (!unpinned.ok) { + return undefined; + } + const deviceId = + unpinned.target.reactNative?.logicalDeviceId ?? ''; + if (deviceId === pinnedDeviceId) { + return undefined; + } + return { + ok: false, + code: HERMES_DEVICE_PIN_MISMATCH, + message: `Hermes target device ${deviceId} does not match session pin ${pinnedDeviceId}`, + }; + } + + /** + * Adopts an open, verified socket: installs the dispatcher and resets the CDP + * id sequence for the new connection. + * + * @param socket - The verified socket. + * @param timeoutMs - The timeout to reuse for later reconnect attempts. + */ + #adopt(socket: WebSocket, timeoutMs: number): void { + this.#detachSocket(); + this.#socket = socket; + this.#nextId = 2; + this.#connectTimeoutMs = timeoutMs; + socket.addEventListener('message', this.#handleMessage); + socket.addEventListener('close', this.#handleClose); + socket.addEventListener('error', this.#handleError); + } + + /** + * Removes this client's listeners from the adopted socket, if any. + */ + #detachSocket(): void { + const socket = this.#socket; + if (!socket) { + return; + } + socket.removeEventListener('message', this.#handleMessage); + socket.removeEventListener('close', this.#handleClose); + socket.removeEventListener('error', this.#handleError); + } + + /** + * Dispatches one WebSocket frame: settles a matching pending call, or emits + * the frame as a CDP event. + * + * @param event - The WebSocket message event. + */ + readonly #handleMessage = (event: MessageEvent): void => { + if (typeof event.data !== 'string') { + this.#onSocketLost( + 'Hermes CDP returned a non-text WebSocket frame', + 'Hermes CDP connection failed: Hermes CDP returned a non-text WebSocket frame', + ); + return; + } + + let parsed: unknown; + try { + parsed = JSON.parse(event.data); + } catch { + return; + } + if (typeof parsed !== 'object' || parsed === null) { + return; + } + + const message = parsed as Record; + if (typeof message.id === 'number') { + this.#handleResponse(message); + return; + } + if (typeof message.method === 'string') { + this.#emit(message.method, { + method: message.method, + params: message.params, + }); + } + }; + + /** + * Settles the pending call whose id matches a CDP response. + * + * @param message - The parsed CDP response. + */ + #handleResponse(message: Record): void { + const id = message.id as number; + const pending = this.#pending.get(id); + if (!pending) { + return; + } + + if (typeof message.error === 'object' && message.error !== null) { + this.#settle(id, { + ok: false, + code: HERMES_CDP_FAILED, + message: `Hermes CDP "${pending.method}" failed: ${formatCdpError( + message.error, + )}`, + }); + return; + } + this.#settle(id, { ok: true, result: message.result }); + } + + /** + * Handles a socket close event from the adopted socket. + * + * @param event - The close event, read for its reason. + */ + readonly #handleClose = (event: Event): void => { + if (!this.#socket) { + return; + } + this.#onSocketLost(readCloseReason(event)); + }; + + /** + * Handles a socket error event. Node follows it with `close`; the adopted + * socket is released here so the error is not lost if it does not. + */ + readonly #handleError = (): void => { + this.#onSocketLost( + 'WebSocket error', + 'Hermes CDP connection failed: WebSocket message error', + ); + }; + + /** + * Releases the adopted socket after an unexpected loss, fails pending calls, + * emits `disconnected` and starts the reconnect loop. + * + * @param reason - Why the socket was lost, used for the `disconnected` event. + * @param pendingMessage - Overrides the pending-call failure message. + */ + #onSocketLost(reason: string, pendingMessage?: string): void { + const socket = this.#socket; + if (!socket) { + return; + } + + this.#detachSocket(); + this.#socket = undefined; + this.#target = undefined; + this.#status = 'closed'; + closeSocket(socket); + + this.#failAllPending( + HERMES_CONNECTION_FAILED, + pendingMessage ?? `Hermes CDP connection closed: ${reason}`, + ); + this.#emit('disconnected', { reason }); + + if (!this.#explicitlyClosed) { + this.#startReconnect(); + } + } + + /** + * Restarts the reconnect loop from the first backoff delay. + */ + #startReconnect(): void { + if (this.#explicitlyClosed || this.#reconnectTimer !== undefined) { + return; + } + this.#reconnectAttempt = 0; + this.#scheduleReconnect(); + } + + /** + * Schedules the next reconnect attempt with exponential backoff, or gives up + * after `maxAttempts` (the client then reports itself disconnected and the + * next {@link send} tries a fresh connect). + */ + #scheduleReconnect(): void { + if (this.#explicitlyClosed || this.#reconnectTimer !== undefined) { + return; + } + if (this.#reconnectAttempt >= this.#reconnect.maxAttempts) { + this.#status = 'closed'; + return; + } + + const delay = Math.min( + this.#reconnect.initialDelayMs * 2 ** this.#reconnectAttempt, + this.#reconnect.maxDelayMs, + ); + this.#reconnectAttempt += 1; + + const timer = setTimeout(() => { + this.#reconnectTimer = undefined; + this.#attemptReconnect().catch(() => undefined); + }, delay); + unrefTimer(timer); + this.#reconnectTimer = timer; + } + + /** + * Runs one reconnect attempt. Failures schedule the next backoff step; a + * device pin mismatch stops the loop so the wrong device is never used. + */ + async #attemptReconnect(): Promise { + if (this.#explicitlyClosed) { + return; + } + try { + const result = await this.#connectOnce( + this.#connectTimeoutMs, + this.#reconnectAttempt, + ); + if (this.#explicitlyClosed) { + return; + } + if (result.ok) { + this.#reconnectAttempt = 0; + return; + } + if ( + result.code === HERMES_DEVICE_PIN_MISMATCH || + result.code === HERMES_WEBSOCKET_UNAVAILABLE + ) { + this.#status = 'closed'; + return; + } + this.#scheduleReconnect(); + } catch { + this.#scheduleReconnect(); + } + } + + /** + * Clears the pending reconnect timer, if any. + */ + #clearReconnectTimer(): void { + if (this.#reconnectTimer !== undefined) { + clearTimeout(this.#reconnectTimer); + this.#reconnectTimer = undefined; + } + } + + /** + * Fails every pending call with the same code and message. + * + * @param code - The stable error code. + * @param message - The human-readable message. + */ + #failAllPending(code: string, message: string): void { + for (const id of [...this.#pending.keys()]) { + this.#settle(id, { ok: false, code, message }); + } + } + + /** + * Resolves one pending call and removes it, so a late response is ignored. + * + * @param id - The CDP message id of the pending call. + * @param result - The result to resolve with. + */ + #settle(id: number, result: HermesCdpResult): void { + const pending = this.#pending.get(id); + if (!pending) { + return; + } + this.#pending.delete(id); + clearTimeout(pending.timer); + pending.detachAbort(); + pending.resolve(result); + } + + /** + * Calls every listener registered for an event. + * + * @param event - The lifecycle event name or CDP method name. + * @param payload - The payload to deliver. + */ + #emit(event: string, payload: unknown): void { + const listeners = this.#listeners.get(event); + if (!listeners) { + return; + } + for (const listener of [...listeners]) { + (listener as (value: unknown) => void)(payload); + } + } +} + +/** + * Builds the failure result for a call made while the socket is not open. + * + * @returns A `HERMES_CONNECTION_FAILED` failure. + */ +function connectionNotOpenResult(): HermesCdpResult { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: 'Hermes CDP connection is not open', + }; +} + +/** + * Builds the failure result for an aborted call. + * + * @param method - The CDP method that was aborted. + * @returns A `HERMES_ABORTED` failure. + */ +function abortedResult(method: string): HermesCdpResult { + return { + ok: false, + code: HERMES_ABORTED, + message: `Hermes CDP call "${method}" was aborted`, + }; +} + +/** + * Reads the close reason from a close event, tolerating a plain `Event`. + * + * @param event - The socket close event. + * @returns The close reason, or `socket closed` when empty. + */ +function readCloseReason(event: Event): string { + const { reason } = event as { reason?: unknown }; + return typeof reason === 'string' && reason.length > 0 + ? reason + : 'socket closed'; +} + +/** + * Unrefs a Node timer so an idle client never keeps the process alive. + * + * @param timer - The timer handle (a `NodeJS.Timeout` in Node). + */ +function unrefTimer(timer: unknown): void { + if ( + typeof timer === 'object' && + timer !== null && + 'unref' in timer && + typeof (timer as { unref?: unknown }).unref === 'function' + ) { + (timer as { unref: () => void }).unref(); + } +} diff --git a/src/index.ts b/src/index.ts index fc49fa0..0534543 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,13 +47,30 @@ export { hasAmbiguousTarget, validateWebSocketUrl, LEGACY_SYNTHETIC_TITLE, + HERMES_ABORTED, } from './hermes/hermes-cdp.js'; export type { HermesTarget, HermesCdpResult, + HermesCdpErrorInfo, RunHermesCdpInput, } from './hermes/hermes-cdp.js'; +export { HermesClient } from './hermes/hermes-client.js'; +export type { + HermesClientOptions, + HermesClientReconnectOptions, + HermesConnectOptions, + HermesConnectResult, + HermesConnectedTarget, + HermesSendOptions, + HermesCdpEvent, + HermesClientEventMap, + HermesContextCreatedEvent, + HermesDisconnectedEvent, + HermesReconnectedEvent, +} from './hermes/hermes-client.js'; + export { runWebViewCdp, fetchWebViewTargets, From 347f626b5187be2ec6afeaab5e4acba148e3d8dd Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Mon, 9 Nov 2026 09:13:54 +0000 Subject: [PATCH 17/33] fix: keep HermesClient dispatching when an event listener throws --- src/hermes/hermes-client.test.ts | 23 +++++++++++++++++++++++ src/hermes/hermes-client.ts | 7 ++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 41ce21e..90b5511 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -445,6 +445,29 @@ describe('HermesClient', () => { expect(received).toHaveLength(1); }); + it('keeps dispatching when a listener throws', async () => { + const client = createClient(); + const received: HermesCdpEvent[] = []; + client.on('Runtime.consoleAPICalled', () => { + throw new Error('listener failed'); + }); + client.on('Runtime.consoleAPICalled', (event: HermesCdpEvent) => { + received.push(event); + }); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + socket.receive( + JSON.stringify({ method: 'Runtime.consoleAPICalled', params: {} }), + ); + + expect(received).toHaveLength(1); + const next = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expect(next.ok).toBe(true); + }); + it('ignores malformed and unknown-id frames', async () => { const client = createClient(); await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 889f5f6..e382372 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -949,7 +949,12 @@ export class HermesClient { return; } for (const listener of [...listeners]) { - (listener as (value: unknown) => void)(payload); + try { + (listener as (value: unknown) => void)(payload); + } catch { + // A failing listener must not break the socket handler or the + // other listeners. + } } } } From 6af5e65c83d814e5737b2b0de515a0a2cd248538 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Mon, 9 Nov 2026 09:53:25 +0000 Subject: [PATCH 18/33] feat: emit contextCreated when the app reloads on the same Hermes socket --- src/hermes/hermes-cdp.ts | 3 + src/hermes/hermes-client.test.ts | 222 +++++++++++++++++++++++++++---- src/hermes/hermes-client.ts | 210 +++++++++++++++++++++++++++-- src/index.ts | 2 + 4 files changed, 395 insertions(+), 42 deletions(-) diff --git a/src/hermes/hermes-cdp.ts b/src/hermes/hermes-cdp.ts index 8015627..f74270f 100644 --- a/src/hermes/hermes-cdp.ts +++ b/src/hermes/hermes-cdp.ts @@ -306,6 +306,9 @@ export async function runHermesCdp( pinnedDeviceId: input.pinnedDeviceId, onPin: input.onPin, reconnect: { maxAttempts: 0 }, + // The one-shot path must not pay for (or expose) context tracking, and its + // wire traffic stays probe + one method. + trackContexts: false, }); try { diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 90b5511..3c1ddce 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -11,7 +11,12 @@ import { IDENTITY_PROBE_EXPR, } from './hermes-cdp.js'; import { HermesClient } from './hermes-client.js'; -import type { HermesCdpEvent, HermesClientOptions } from './hermes-client.js'; +import type { + HermesCdpEvent, + HermesClientOptions, + HermesContextCreatedEvent, + HermesContextDestroyedEvent, +} from './hermes-client.js'; const APP_ID = 'io.metamask.MetaMask'; const METRO_PORT = 8085; @@ -157,8 +162,25 @@ function defaultResponseFactory(request: CdpRequest): Record { return { id: request.id, result: { result: { type: 'number', value: 2 } } }; } -function probeOnly(request: CdpRequest): MockResponse { - return isIdentityProbe(request) ? probeResponse(request) : undefined; +function isRuntimeEnable(request: CdpRequest): boolean { + return request.method === 'Runtime.enable'; +} + +/** + * Answers the identity probe and the client's internal `Runtime.enable`, but + * leaves user methods unanswered. + * + * @param request - The sent CDP request. + * @returns The mocked response, or undefined to stay pending. + */ +function controlOnly(request: CdpRequest): MockResponse { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + if (isRuntimeEnable(request)) { + return { id: request.id, result: {} }; + } + return undefined; } function socketAt(index: number): FakeWebSocket { @@ -246,8 +268,11 @@ describe('HermesClient', () => { expect(fetchMock).toHaveBeenCalledTimes(1); const socket = socketAt(0); - expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2, 3]); + expect(socket.sent.map((request) => request.id)).toStrictEqual([ + 1, 2, 3, 4, + ]); expect(socket.sent.filter(isIdentityProbe)).toHaveLength(1); + expect(socket.sent.filter(isRuntimeEnable)).toHaveLength(1); expect(socket.options?.headers.origin).toBe( `http://127.0.0.1:${METRO_PORT}`, ); @@ -278,9 +303,136 @@ describe('HermesClient', () => { title: 'io.metamask.MetaMask (iPhone 15)', }, reconnected: false, + reason: 'connect', + }); + }); + + it('sends Runtime.enable once per socket', async () => { + const client = createClient(); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + const enableMessages = socketAt(0).sent.filter(isRuntimeEnable); + expect(enableMessages).toStrictEqual([ + { id: 2, method: 'Runtime.enable', params: {} }, + ]); + }); + + it('does not send Runtime.enable when trackContexts is off', async () => { + const client = createClient({ trackContexts: false }); + const created = vi.fn(); + client.on('contextCreated', created); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + + expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2]); + expect(socket.sent.filter(isRuntimeEnable)).toHaveLength(0); + + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 2 } }, + }), + ); + expect(created).toHaveBeenCalledTimes(1); + }); + + it('emits one contextDestroyed and one reload contextCreated when the app reloads on the same socket', async () => { + const client = createClient(); + const created: HermesContextCreatedEvent[] = []; + const destroyed: HermesContextDestroyedEvent[] = []; + const raw: HermesCdpEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + client.on('contextDestroyed', (event) => destroyed.push(event)); + client.on('Runtime.executionContextCreated', (event) => raw.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + const socket = socketAt(0); + const expectedTarget = { + id: 'device-page-1', + logicalDeviceId: 'logical-device-1', + title: 'io.metamask.MetaMask (iPhone 15)', + }; + + // The first context after Runtime.enable is the one connect already + // reported, so it must not produce a second contextCreated. + const firstContext = { + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 2 } }, + }; + socket.receive(JSON.stringify(firstContext)); + expect(created).toStrictEqual([ + { target: expectedTarget, reconnected: false, reason: 'connect' }, + ]); + // Raw CDP events still reach listeners. + expect(raw).toStrictEqual([firstContext]); + + // Reload: Hermes sends both destroy events; they coalesce into one. + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextDestroyed', + params: { executionContextId: 2 }, + }), + ); + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextsCleared', + params: {}, + }), + ); + expect(destroyed).toStrictEqual([{ reason: 'reload' }]); + + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 3 } }, + }), + ); + expect(created).toHaveLength(2); + expect(created[1]).toStrictEqual({ + target: expectedTarget, + reconnected: false, + reason: 'reload', + executionContextId: 3, }); }); + it('keeps the connection when Runtime.enable fails', async () => { + FakeWebSocket.responseFactory = (request) => { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + if (isRuntimeEnable(request)) { + return { + id: request.id, + error: { message: 'Method not found', code: -32601 }, + }; + } + return undefined; + }; + const client = createClient(); + const created = vi.fn(); + client.on('contextCreated', created); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result.ok).toBe(true); + expect(client.isConnected).toBe(true); + + socketAt(0).receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 2 } }, + }), + ); + expect(created).toHaveBeenCalledTimes(1); + expect(created).toHaveBeenCalledWith( + expect.objectContaining({ reason: 'connect' }), + ); + }); + it('returns the current target when already connected', async () => { const client = createClient(); await client.connect({ timeoutMs: 1_000 }); @@ -293,7 +445,7 @@ describe('HermesClient', () => { }); it('matches concurrent responses by id, even out of order', async () => { - FakeWebSocket.responseFactory = probeOnly; + FakeWebSocket.responseFactory = controlOnly; const client = createClient(); const first = client.send( @@ -309,17 +461,17 @@ describe('HermesClient', () => { await flush(); const socket = socketAt(0); - expect(socket.sent).toHaveLength(3); + expect(socket.sent).toHaveLength(4); - socket.receive(JSON.stringify({ id: 3, result: 'b' })); - socket.receive(JSON.stringify({ id: 2, result: 'a' })); + socket.receive(JSON.stringify({ id: 4, result: 'b' })); + socket.receive(JSON.stringify({ id: 3, result: 'a' })); expect(await second).toStrictEqual({ ok: true, result: 'b' }); expect(await first).toStrictEqual({ ok: true, result: 'a' }); }); it('fails with HERMES_TIMEOUT on a per-call timeout and drops the pending entry', async () => { - FakeWebSocket.responseFactory = probeOnly; + FakeWebSocket.responseFactory = controlOnly; const client = createClient(); const result = await client.send( @@ -333,7 +485,7 @@ describe('HermesClient', () => { // The late response must be ignored, and the next call gets a fresh id. const socket = socketAt(0); - socket.receive(JSON.stringify({ id: 2, result: 'late' })); + socket.receive(JSON.stringify({ id: 3, result: 'late' })); FakeWebSocket.responseFactory = defaultResponseFactory; const next = await client.send( 'Runtime.evaluate', @@ -342,11 +494,13 @@ describe('HermesClient', () => { ); expect(next.ok).toBe(true); - expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2, 3]); + expect(socket.sent.map((request) => request.id)).toStrictEqual([ + 1, 2, 3, 4, + ]); }); it('fails with HERMES_ABORTED when the signal aborts and drops the pending entry', async () => { - FakeWebSocket.responseFactory = probeOnly; + FakeWebSocket.responseFactory = controlOnly; const controller = new AbortController(); const client = createClient(); @@ -363,7 +517,7 @@ describe('HermesClient', () => { expect(result.message).toContain('aborted'); const socket = socketAt(0); - socket.receive(JSON.stringify({ id: 2, result: 'late' })); + socket.receive(JSON.stringify({ id: 3, result: 'late' })); FakeWebSocket.responseFactory = defaultResponseFactory; const next = await client.send( 'Runtime.evaluate', @@ -372,7 +526,9 @@ describe('HermesClient', () => { ); expect(next.ok).toBe(true); - expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2, 3]); + expect(socket.sent.map((request) => request.id)).toStrictEqual([ + 1, 2, 3, 4, + ]); }); it('does not connect for an already-aborted signal', async () => { @@ -391,17 +547,22 @@ describe('HermesClient', () => { }); it('formats a CDP error into HERMES_CDP_FAILED', async () => { - FakeWebSocket.responseFactory = (request) => - isIdentityProbe(request) - ? probeResponse(request) - : { - id: request.id, - error: { - message: 'Bad params', - code: -32602, - data: { reason: 'invalid' }, - }, - }; + FakeWebSocket.responseFactory = (request) => { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + if (isRuntimeEnable(request)) { + return { id: request.id, result: {} }; + } + return { + id: request.id, + error: { + message: 'Bad params', + code: -32602, + data: { reason: 'invalid' }, + }, + }; + }; const client = createClient(); const result = await client.send('Missing.method', undefined, { @@ -546,7 +707,7 @@ describe('HermesClient', () => { }); it('closing fails pending calls and closes the socket', async () => { - FakeWebSocket.responseFactory = probeOnly; + FakeWebSocket.responseFactory = controlOnly; const client = createClient(); const pending = client.send('Runtime.evaluate', undefined, { @@ -585,12 +746,12 @@ describe('HermesClient', () => { expect(created).toHaveLength(1); expect(FakeWebSocket.instances).toHaveLength(1); - FakeWebSocket.responseFactory = probeOnly; + FakeWebSocket.responseFactory = controlOnly; const pending = client.send('Network.enable', undefined, { timeoutMs: 5_000, }); await flush(); - expect(socketAt(0).sent).toHaveLength(3); + expect(socketAt(0).sent).toHaveLength(4); // The app reloads: the target id and URL change behind the same Metro port. mockDiscovery([ @@ -625,6 +786,7 @@ describe('HermesClient', () => { ]); expect(created[1]).toMatchObject({ reconnected: true, + reason: 'reconnect', target: { id: 'device-page-2' }, }); expect(client.isConnected).toBe(true); @@ -635,7 +797,9 @@ describe('HermesClient', () => { timeoutMs: 1_000, }); expect(after.ok).toBe(true); - expect(socketAt(1).sent.map((request) => request.id)).toStrictEqual([1, 2]); + expect(socketAt(1).sent.map((request) => request.id)).toStrictEqual([ + 1, 2, 3, + ]); }); it('retries with backoff and gives up after maxAttempts', async () => { diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index e382372..ab5a065 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -11,12 +11,16 @@ * selection, the Hermes identity probe once per socket, the device pin, the * WebSocket URL validation, and the blocked-method set. * - * When the app reloads (or Metro restarts) the socket closes. Pending calls are - * failed with `HERMES_CONNECTION_FAILED` and NOT resent (they may have run), then - * the client rediscovers the target (its id and URL change after a reload) and - * reconnects with exponential backoff. Every successful (re)connect emits - * `contextCreated` so callers can re-apply their scripts (page reloads reset the - * runtime). + * When Metro restarts (or the socket is otherwise lost) the socket closes. + * Pending calls are failed with `HERMES_CONNECTION_FAILED` and NOT resent (they + * may have run), then the client rediscovers the target and reconnects with + * exponential backoff. Every successful (re)connect emits `contextCreated`. + * + * An app reload does NOT close the socket: the runtime swaps its JavaScript + * context in place. With `trackContexts` on (the default) the client enables + * `Runtime` context events, emits `contextDestroyed` when the old context goes + * away and `contextCreated` (`reason: 'reload'`) for the new one, so callers can + * re-apply their scripts. */ import type { HermesCdpResult } from './hermes-cdp.js'; @@ -92,6 +96,20 @@ export type HermesClientOptions = { onPin?: (logicalDeviceId: string) => void; /** Automatic reconnect tuning. */ reconnect?: HermesClientReconnectOptions; + /** + * Track JavaScript execution contexts and emit `contextCreated` / + * `contextDestroyed` lifecycle events (default `true`). + * + * When enabled, the client sends `Runtime.enable` itself after each + * connection so Hermes streams `Runtime.executionContextCreated`, + * `Runtime.executionContextDestroyed` and `Runtime.executionContextsCleared` + * over the socket; an app reload keeps the socket open, so this is the only + * signal that the JavaScript context was replaced. Cost: `Runtime.enable` + * also makes Hermes stream `Runtime.consoleAPICalled` (and other `Runtime` + * events) on the socket; listeners that do not consume them still receive + * them. + */ + trackContexts?: boolean; }; /** @@ -142,14 +160,37 @@ export type HermesCdpEvent = { }; /** - * Payload of the `contextCreated` lifecycle event, emitted after every - * successful connect (including the first one) and after every reconnect. + * Why a `contextCreated` lifecycle event fired: + * - `connect`: the first connection of this client. + * - `reconnect`: a new socket after the old one closed (Metro restart, socket + * loss). + * - `reload`: a new JS context on the SAME socket (app reload / fast refresh). + */ +export type HermesContextCreatedReason = 'connect' | 'reconnect' | 'reload'; + +/** + * Payload of the `contextCreated` lifecycle event: emitted after every + * successful connect, after every reconnect, and for every new JavaScript + * execution context created on an open socket (app reload). */ export type HermesContextCreatedEvent = { - /** The verified target of the new connection. */ + /** The verified target of the connection. */ target: HermesConnectedTarget; - /** True for a reconnect, false for the initial connect. */ + /** True for a reconnect, false for the initial connect or a reload. */ reconnected: boolean; + /** Why the event fired. */ + reason: HermesContextCreatedReason; + /** The CDP execution context id for a `reload`, when Hermes reported one. */ + executionContextId?: number; +}; + +/** + * Payload of the `contextDestroyed` lifecycle event, emitted when an open + * socket reports that its JavaScript context went away (a reload started). + */ +export type HermesContextDestroyedEvent = { + /** Contexts are only destroyed by a reload on the same socket. */ + reason: 'reload'; }; /** @@ -177,6 +218,7 @@ export type HermesReconnectedEvent = { */ export type HermesClientEventMap = { contextCreated: HermesContextCreatedEvent; + contextDestroyed: HermesContextDestroyedEvent; disconnected: HermesDisconnectedEvent; reconnected: HermesReconnectedEvent; }; @@ -201,6 +243,12 @@ type PendingCall = { * * Create one per session, call {@link send} for CDP methods (it connects on the * first call), subscribe with {@link on}, and call {@link close} when done. + * + * Reloads keep the socket open, so a closed socket only means a lost connection + * (Metro restart). When `trackContexts` is on (the default), the client enables + * `Runtime` context events and emits a `contextCreated` lifecycle event for + * every new JavaScript context on the open socket, so callers can re-apply + * their scripts. */ export class HermesClient { readonly #metroPort: number; @@ -213,6 +261,8 @@ export class HermesClient { readonly #reconnect: Required; + readonly #trackContexts: boolean; + readonly #listeners = new Map>(); readonly #pending = new Map(); @@ -227,6 +277,26 @@ export class HermesClient { #nextId = 1; + /** + * Whether the adopted socket streams `Runtime` execution-context events. + * True while `Runtime.enable` is in flight or succeeded; false when + * `trackContexts` is off or `Runtime.enable` failed. + */ + #socketTracksContexts = false; + + /** + * Whether the first execution context of the adopted socket was already seen. + * The connect `contextCreated` event covers it, so it is not re-emitted. + */ + #sawContextOnSocket = false; + + /** + * Whether a `contextDestroyed` event was already emitted for the current + * reload; coalesces `executionContextDestroyed` and + * `executionContextsCleared`. + */ + #contextDestroyedForReload = false; + #inFlightConnect: Promise | undefined; #reconnectTimer: ReturnType | undefined; @@ -243,6 +313,7 @@ export class HermesClient { this.#origin = options.origin; this.#pinnedDeviceId = options.pinnedDeviceId; this.#onPin = options.onPin; + this.#trackContexts = options.trackContexts ?? true; this.#reconnect = { initialDelayMs: options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS, @@ -401,9 +472,9 @@ export class HermesClient { /** * Subscribes to a lifecycle event or a CDP event. * - * Lifecycle names are `contextCreated`, `disconnected` and `reconnected`. - * Any other name receives the CDP event messages of that `method` - * (for example `Runtime.consoleAPICalled`). + * Lifecycle names are `contextCreated`, `contextDestroyed`, `disconnected` + * and `reconnected`. Any other name receives the CDP event messages of that + * `method` (for example `Runtime.consoleAPICalled`). * * @param event - The lifecycle event name or CDP method name. * @param listener - Called with the typed lifecycle payload or the CDP event. @@ -496,6 +567,7 @@ export class HermesClient { this.#emit('contextCreated', { target: result.target, reconnected: isReconnect, + reason: isReconnect ? 'reconnect' : 'connect', }); } return result; @@ -626,6 +698,33 @@ export class HermesClient { title: selection.target.title, }; this.#target = target; + + if (this.#trackContexts) { + // Mark tracking before sending: Hermes can emit the first + // `executionContextCreated` before the `Runtime.enable` response, and + // that first context must be recorded (so a later reload is not + // mistaken for it) even though it is not re-emitted. + this.#socketTracksContexts = true; + // Enabling contexts is best effort: a failure only disables the + // `contextCreated` / `contextDestroyed` lifecycle detection for this + // socket, it never fails the connect. + const enabled = await this.send('Runtime.enable', undefined, { + timeoutMs, + }); + if (!enabled.ok) { + this.#socketTracksContexts = false; + this.#sawContextOnSocket = false; + if (!this.isConnected) { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: + 'Hermes CDP connection failed: the socket closed while enabling runtime events', + }; + } + } + } + return { ok: true, target }; } catch (error) { const message = error instanceof Error ? error.message : String(error); @@ -692,6 +791,9 @@ export class HermesClient { this.#socket = socket; this.#nextId = 2; this.#connectTimeoutMs = timeoutMs; + this.#socketTracksContexts = false; + this.#sawContextOnSocket = false; + this.#contextDestroyedForReload = false; socket.addEventListener('message', this.#handleMessage); socket.addEventListener('close', this.#handleClose); socket.addEventListener('error', this.#handleError); @@ -745,9 +847,72 @@ export class HermesClient { method: message.method, params: message.params, }); + this.#trackExecutionContext(message.method, message.params); } }; + /** + * Derives `contextCreated` / `contextDestroyed` lifecycle events from the + * `Runtime` execution-context events of the adopted socket. + * + * The first context of a socket is the one the connect `contextCreated` event + * already described, so it is not re-emitted. A later context means the app + * reloaded while the socket stayed open. + * + * @param method - The CDP event method. + * @param params - The CDP event payload. + */ + #trackExecutionContext(method: string, params: unknown): void { + if (!this.#socketTracksContexts) { + return; + } + + if (method === 'Runtime.executionContextCreated') { + this.#handleExecutionCreated(params); + return; + } + if ( + method === 'Runtime.executionContextDestroyed' || + method === 'Runtime.executionContextsCleared' + ) { + if (this.#contextDestroyedForReload) { + return; + } + this.#contextDestroyedForReload = true; + this.#emit('contextDestroyed', { reason: 'reload' }); + } + } + + /** + * Emits `contextCreated` for a reload, skipping the first context of the + * socket (covered by the connect event). + * + * @param params - The `Runtime.executionContextCreated` payload. + */ + #handleExecutionCreated(params: unknown): void { + const executionContextId = readExecutionContextId(params); + if (!this.#sawContextOnSocket) { + this.#sawContextOnSocket = true; + return; + } + + const target = this.#target; + if (!target) { + return; + } + + this.#contextDestroyedForReload = false; + const event: HermesContextCreatedEvent = { + target, + reconnected: false, + reason: 'reload', + }; + if (executionContextId !== undefined) { + event.executionContextId = executionContextId; + } + this.#emit('contextCreated', event); + } + /** * Settles the pending call whose id matches a CDP response. * @@ -986,6 +1151,25 @@ function abortedResult(method: string): HermesCdpResult { }; } +/** + * Reads the execution context id from a `Runtime.executionContextCreated` + * payload. + * + * @param params - The CDP event payload. + * @returns The numeric context id, or undefined when absent. + */ +function readExecutionContextId(params: unknown): number | undefined { + if (typeof params !== 'object' || params === null) { + return undefined; + } + const { context } = params as { context?: unknown }; + if (typeof context !== 'object' || context === null) { + return undefined; + } + const { id } = context as { id?: unknown }; + return typeof id === 'number' ? id : undefined; +} + /** * Reads the close reason from a close event, tolerating a plain `Event`. * diff --git a/src/index.ts b/src/index.ts index 0534543..da1ead9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -67,6 +67,8 @@ export type { HermesCdpEvent, HermesClientEventMap, HermesContextCreatedEvent, + HermesContextCreatedReason, + HermesContextDestroyedEvent, HermesDisconnectedEvent, HermesReconnectedEvent, } from './hermes/hermes-client.js'; From 42759bebd42d622b659d7fd5b575d455a6b11385 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Mon, 9 Nov 2026 14:31:21 +0000 Subject: [PATCH 19/33] fix: keep HermesClient reconnecting and open one socket per reconnect A caller's connect()/send() no longer stops the background reconnect loop: it used to clear the reconnect timer and reset the backoff, so a send during the reconnect wait killed auto-reconnect for good. - Track an unexpected socket loss and restart the loop after a failed caller-driven attempt, except after close() and on terminal failures. - Report a caller-driven connect after a loss as contextCreated with reason 'reconnect' and reconnected true. - Start the loop before emitting `disconnected`, and make a scheduled attempt a no-op while connected, so one loss opens one socket. - Close any socket adopted over a previous one; one contextCreated per adopted socket. - Bound reconnect attempts with the new reconnect.connectTimeoutMs (default 10 s) instead of the last caller's timeoutMs. - Check close() after every await of the connect path: no pin, no onPin, no adopted socket, and close the in-flight socket. - End an aborted send with HERMES_ABORTED even while it is connecting. - Detect a reload from contextDestroyed even when the socket never reported its first execution context. - Surface a throwing listener through the new listenerError event. --- src/hermes/hermes-client.test.ts | 325 +++++++++++++++++++++++++++++++ src/hermes/hermes-client.ts | 309 ++++++++++++++++++++++++----- 2 files changed, 584 insertions(+), 50 deletions(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 3c1ddce..c41f6ba 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -16,6 +16,7 @@ import type { HermesClientOptions, HermesContextCreatedEvent, HermesContextDestroyedEvent, + HermesListenerErrorEvent, } from './hermes-client.js'; const APP_ID = 'io.metamask.MetaMask'; @@ -888,4 +889,328 @@ describe('HermesClient', () => { expect(FakeWebSocket.instances).toHaveLength(2); expect(socketAt(1).url).toBe(SOCKET_URL); }); + + it('keeps reconnecting when a send fails during the reconnect wait', async () => { + const client = createClient({ + reconnect: { initialDelayMs: 40, maxDelayMs: 80, maxAttempts: 5 }, + }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + + // Metro goes down before the first scheduled attempt runs. + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + const failed = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 100, + }); + + expectError(failed, HERMES_CONNECTION_FAILED); + expect(client.isConnected).toBe(false); + + // Metro comes back: the background loop must still be running. + mockDiscovery([target({ id: 'device-page-2' })]); + + await vi.waitFor(() => expect(client.isConnected).toBe(true), { + timeout: 2_000, + }); + + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + reconnected: true, + target: { id: 'device-page-2' }, + }); + + client.close(); + }); + + it('reports reason reconnect when a send reconnects after a socket loss', async () => { + const client = createClient({ reconnect: { maxAttempts: 0 } }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + mockDiscovery([target({ id: 'device-page-2' })]); + socketAt(0).drop('metro restart'); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result.ok).toBe(true); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + reconnected: true, + target: { id: 'device-page-2' }, + }); + }); + + it('opens one socket when a disconnected listener sends and the reconnect timer fires', async () => { + const client = createClient({ + reconnect: { initialDelayMs: 40, maxDelayMs: 40, maxAttempts: 3 }, + }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + client.on('disconnected', () => { + client + .send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }) + .catch(() => undefined); + }); + + await client.connect({ timeoutMs: 1_000 }); + socketAt(0).drop('metro restart'); + + await vi.waitFor(() => expect(client.isConnected).toBe(true), { + timeout: 1_000, + }); + // Let the scheduled attempt fire: it must find the caller's socket and open + // nothing. + await delay(100); + + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + reconnected: true, + }); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + expect(socketAt(1).readyState).toBe(FakeWebSocket.openState); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('treats a context after contextDestroyed as a reload when no initial context arrived', async () => { + const client = createClient(); + const created: HermesContextCreatedEvent[] = []; + const destroyed: HermesContextDestroyedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + client.on('contextDestroyed', (event) => destroyed.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + const socket = socketAt(0); + + // This socket never reported its first execution context. + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextsCleared', + params: {}, + }), + ); + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 5 } }, + }), + ); + + expect(destroyed).toStrictEqual([{ reason: 'reload' }]); + expect(created).toHaveLength(2); + expect(created[1]).toStrictEqual({ + target: { + id: 'device-page-1', + logicalDeviceId: 'logical-device-1', + title: 'io.metamask.MetaMask (iPhone 15)', + }, + reconnected: false, + reason: 'reload', + executionContextId: 5, + }); + }); + + it('tracks the first context when it arrives before the Runtime.enable response', async () => { + FakeWebSocket.responseFactory = (request) => { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + if (isRuntimeEnable(request)) { + socketAt(FakeWebSocket.instances.length - 1).receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 2 } }, + }), + ); + return { id: request.id, result: {} }; + } + return undefined; + }; + const client = createClient(); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + + // The context seen during Runtime.enable is the connect context: no second + // event, and a later context is a reload, not the socket's first context. + expect(created).toHaveLength(1); + expect(created[0]).toMatchObject({ reason: 'connect' }); + + const socket = socketAt(0); + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextDestroyed', + params: { executionContextId: 2 }, + }), + ); + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 3 } }, + }), + ); + + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reload', + reconnected: false, + executionContextId: 3, + }); + }); + + it('uses reconnect.connectTimeoutMs for reconnect attempts, not the last caller timeout', async () => { + const client = createClient({ + reconnect: { + initialDelayMs: 10, + maxDelayMs: 10, + maxAttempts: 3, + connectTimeoutMs: 30, + }, + }); + // The last caller asks for a 5 s connect. + await client.send('Runtime.evaluate', undefined, { timeoutMs: 5_000 }); + + const abortedAfter: number[] = []; + const startedAt = Date.now(); + fetchMock = vi.fn( + async (_url: string, init?: { signal?: AbortSignal }) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + abortedAfter.push(Date.now() - startedAt); + reject(new Error('discovery aborted')); + }); + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + await vi.waitFor(() => expect(abortedAfter.length).toBeGreaterThan(0), { + timeout: 1_000, + }); + + // A reconnect discovery is bounded by 30 ms, far below the caller's 5 s. + expect(abortedAfter[0]).toBeLessThan(1_000); + expect(client.isConnected).toBe(false); + + client.close(); + }); + + it('fails a send with HERMES_ABORTED while it is still connecting', async () => { + fetchMock = vi.fn(async () => new Promise(() => undefined)); + vi.stubGlobal('fetch', fetchMock); + const client = createClient(); + const controller = new AbortController(); + + const sentAt = Date.now(); + const pending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 500, + signal: controller.signal, + }); + await flush(); + controller.abort(); + + const result = await pending; + + expectError(result, HERMES_ABORTED); + expect(result.message).toContain('aborted'); + expect(Date.now() - sentAt).toBeLessThan(1_000); + expect(FakeWebSocket.instances).toHaveLength(0); + }); + + it('does not pin, adopt or reconnect when close() lands during discovery', async () => { + const onPin = vi.fn(); + const client = createClient({ onPin }); + let resolveDiscovery!: (value: unknown) => void; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + resolveDiscovery = resolve; + }), + ); + vi.stubGlobal('fetch', fetchMock); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await flush(); + client.close(); + resolveDiscovery({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); + + const result = await connecting; + + expect(result).toMatchObject({ ok: false, code: HERMES_CONNECTION_FAILED }); + expect(onPin).not.toHaveBeenCalled(); + expect(FakeWebSocket.instances).toHaveLength(0); + expect(client.isConnected).toBe(false); + + await delay(20); + expect(FakeWebSocket.instances).toHaveLength(0); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('does not pin or adopt when close() lands during the identity probe', async () => { + vi.useFakeTimers(); + FakeWebSocket.responseFactory = () => undefined; + const onPin = vi.fn(); + const client = createClient({ onPin }); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(socketAt(0).readyState).toBe(FakeWebSocket.openState); + + client.close(); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + + const result = await connecting; + + expect(result).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(onPin).not.toHaveBeenCalled(); + expect(client.isConnected).toBe(false); + + await vi.advanceTimersByTimeAsync(100); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('reports a throwing listener through the listenerError event', async () => { + const client = createClient(); + const errors: HermesListenerErrorEvent[] = []; + const received: HermesCdpEvent[] = []; + const failure = new Error('listener failed'); + client.on('listenerError', () => { + throw new Error('nested listener failure'); + }); + client.on('listenerError', (event) => errors.push(event)); + client.on('Runtime.consoleAPICalled', () => { + throw failure; + }); + client.on('Runtime.consoleAPICalled', (event) => received.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + socketAt(0).receive( + JSON.stringify({ method: 'Runtime.consoleAPICalled', params: {} }), + ); + + expect(received).toHaveLength(1); + expect(errors).toStrictEqual([ + { event: 'Runtime.consoleAPICalled', error: failure }, + ]); + }); }); diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index ab5a065..651afee 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -55,9 +55,12 @@ const DEFAULT_RECONNECT_MAX_DELAY_MS = 5_000; /** Default number of automatic reconnect attempts before giving up. */ const DEFAULT_RECONNECT_MAX_ATTEMPTS = 6; -/** Connect timeout used by the automatic reconnect loop. */ +/** Default connect timeout used by the automatic reconnect loop. */ const DEFAULT_RECONNECT_TIMEOUT_MS = 10_000; +/** Lifecycle event name used to report a throwing listener. */ +const LISTENER_ERROR_EVENT = 'listenerError'; + /** Message used when a call is made after {@link HermesClient.close}. */ const CLIENT_CLOSED_MESSAGE = 'HermesClient is closed'; @@ -75,6 +78,12 @@ export type HermesClientReconnectOptions = { * fresh connect. `0` disables auto-reconnect. */ maxAttempts?: number; + /** + * Connect timeout for automatic reconnect attempts, in milliseconds + * (default 10 s). Per-call `timeoutMs` values only apply to the call's own + * connect, so a short call timeout never shortens later reconnect attempts. + */ + connectTimeoutMs?: number; }; /** @@ -132,12 +141,17 @@ export type HermesConnectedTarget = { title: string | undefined; }; +/** + * The failure branch shared by the connect and send results. + */ +type HermesFailureResult = { ok: false; code: string; message: string }; + /** * Result of {@link HermesClient.connect}. */ export type HermesConnectResult = | { ok: true; target: HermesConnectedTarget } - | { ok: false; code: string; message: string }; + | HermesFailureResult; /** * Options for {@link HermesClient.send}. @@ -212,6 +226,18 @@ export type HermesReconnectedEvent = { attempts: number; }; +/** + * Payload of the `listenerError` lifecycle event, emitted when one of the + * client's own listeners throws. The exception is isolated so it cannot break + * the socket handler or the other listeners; this event surfaces it. + */ +export type HermesListenerErrorEvent = { + /** The event name whose listener threw. */ + event: string; + /** The thrown value. */ + error: unknown; +}; + /** * Lifecycle events with a typed payload. Any other event name is a CDP event * and receives a {@link HermesCdpEvent}. @@ -221,6 +247,7 @@ export type HermesClientEventMap = { contextDestroyed: HermesContextDestroyedEvent; disconnected: HermesDisconnectedEvent; reconnected: HermesReconnectedEvent; + listenerError: HermesListenerErrorEvent; }; type HermesClientStatus = 'idle' | 'connecting' | 'open' | 'closed'; @@ -249,6 +276,14 @@ type PendingCall = { * `Runtime` context events and emits a `contextCreated` lifecycle event for * every new JavaScript context on the open socket, so callers can re-apply * their scripts. + * + * An unexpected socket loss starts a background reconnect loop. A caller's + * {@link connect} or {@link send} never stops that loop: while the connection is + * lost, a failed caller-driven attempt (re)starts it, and a successful one is + * reported as `contextCreated` with `reason: 'reconnect'`. + * + * A listener that throws is isolated and reported through the `listenerError` + * lifecycle event; it never breaks the socket handler or the other listeners. */ export class HermesClient { readonly #metroPort: number; @@ -271,6 +306,12 @@ export class HermesClient { #socket: WebSocket | undefined; + /** + * The socket of an in-flight connect, before it is adopted. Kept so + * {@link close} can abandon the connect promptly. + */ + #connectingSocket: WebSocket | undefined; + #target: HermesConnectedTarget | undefined; #status: HermesClientStatus = 'idle'; @@ -293,18 +334,26 @@ export class HermesClient { /** * Whether a `contextDestroyed` event was already emitted for the current * reload; coalesces `executionContextDestroyed` and - * `executionContextsCleared`. + * `executionContextsCleared`. Also marks a reload in progress, so the next + * context is reported as `reload` even when the socket never reported its + * first context. */ #contextDestroyedForReload = false; + /** + * Whether the last connection was lost unexpectedly (not through + * {@link close}). Set on an unexpected loss, cleared on a successful connect + * and by {@link close}. Drives the `reconnect` reason of a caller-driven + * connect and whether a failed caller-driven attempt restarts the loop. + */ + #socketLost = false; + #inFlightConnect: Promise | undefined; #reconnectTimer: ReturnType | undefined; #reconnectAttempt = 0; - #connectTimeoutMs = DEFAULT_RECONNECT_TIMEOUT_MS; - #explicitlyClosed = false; constructor(options: HermesClientOptions) { @@ -321,6 +370,8 @@ export class HermesClient { options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS, maxAttempts: options.reconnect?.maxAttempts ?? DEFAULT_RECONNECT_MAX_ATTEMPTS, + connectTimeoutMs: + options.reconnect?.connectTimeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS, }; } @@ -356,8 +407,12 @@ export class HermesClient { * * Idempotent: when already connected it resolves with the current target, and * concurrent callers share one in-flight connect (one discovery fetch, one - * socket, one identity probe). Emits `contextCreated` on success. A client - * closed with {@link close} reopens. + * socket, one identity probe). Emits `contextCreated` on success, with + * `reason: 'reconnect'` when the previous connection was lost unexpectedly. + * A client closed with {@link close} reopens. + * + * A connect never stops the background reconnect loop: a failed attempt while + * the connection is lost restarts it. * * @param options - The connect timeout. * @returns The verified target or a classified failure. @@ -365,15 +420,14 @@ export class HermesClient { async connect(options: HermesConnectOptions): Promise { const { timeoutMs } = options; this.#explicitlyClosed = false; - this.#clearReconnectTimer(); - this.#reconnectAttempt = 0; - this.#connectTimeoutMs = timeoutMs; if (this.isConnected && this.#target) { return { ok: true, target: this.#target }; } - return await this.#connectOnce(timeoutMs); + const result = await this.#connectOnce(timeoutMs); + this.#resumeReconnectAfterFailedCall(result); + return result; } /** @@ -412,7 +466,10 @@ export class HermesClient { } if (!this.isConnected) { - const connected = await this.connect({ timeoutMs }); + const connected = await this.#connectWithAbort(timeoutMs, signal); + if (connected === undefined) { + return abortedResult(method); + } if (!connected.ok) { return connected; } @@ -519,7 +576,9 @@ export class HermesClient { */ close(): void { this.#explicitlyClosed = true; + this.#socketLost = false; this.#clearReconnectTimer(); + this.#reconnectAttempt = 0; this.#failAllPending( HERMES_CONNECTION_FAILED, `${CLIENT_CLOSED_MESSAGE}: the connection was closed`, @@ -534,15 +593,26 @@ export class HermesClient { this.#detachSocket(); closeSocket(socket); } + + const connecting = this.#connectingSocket; + this.#connectingSocket = undefined; + if (connecting) { + closeSocket(connecting); + } } /** * Shares one in-flight connect between concurrent callers and emits the * connect lifecycle events once. * + * The `reconnect` reason is taken from the connection state at the start of + * the attempt: after an unexpected socket loss the next successful connect is + * a reconnect, whether the background loop or a caller triggered it. + * * @param timeoutMs - The connect timeout. - * @param reconnectAttempts - Set for a reconnect attempt, used for the - * `reconnected` payload and to distinguish the reordered lifecycle events. + * @param reconnectAttempts - Set for a background reconnect attempt, used for + * the `reconnected` payload. A caller-driven reconnect only emits + * `contextCreated`. * @returns The connect result. */ async #connectOnce( @@ -554,11 +624,13 @@ export class HermesClient { return await existing; } - const isReconnect = reconnectAttempts !== undefined; - const promise = this.#doConnect(timeoutMs, isReconnect) + const reconnected = this.#socketLost; + const promise = this.#doConnect(timeoutMs, reconnected) .then((result) => { if (result.ok) { - if (isReconnect) { + this.#socketLost = false; + this.#resetReconnect(); + if (reconnectAttempts !== undefined) { this.#emit('reconnected', { target: result.target, attempts: reconnectAttempts, @@ -566,8 +638,8 @@ export class HermesClient { } this.#emit('contextCreated', { target: result.target, - reconnected: isReconnect, - reason: isReconnect ? 'reconnect' : 'connect', + reconnected, + reason: reconnected ? 'reconnect' : 'connect', }); } return result; @@ -586,12 +658,13 @@ export class HermesClient { * Discovers, opens, probes and adopts a target. Never throws. * * @param timeoutMs - The connect timeout. - * @param reconnect - True for an automatic reconnect attempt. + * @param reconnected - True when the previous connection was lost + * unexpectedly, used to fail closed on a device pin mismatch. * @returns The verified target or a classified failure. */ async #doConnect( timeoutMs: number, - reconnect: boolean, + reconnected: boolean, ): Promise { if (typeof WebSocket !== 'function') { this.#status = 'closed'; @@ -604,6 +677,9 @@ export class HermesClient { try { const targets = await fetchDiscoveryTargets(this.#metroPort, timeoutMs); + if (this.#explicitlyClosed) { + return closedDuringConnectResult(); + } const selection = selectHermesTarget( targets, @@ -614,7 +690,7 @@ export class HermesClient { const pinMismatch = this.#detectReconnectPinMismatch( targets, selection.code, - reconnect, + reconnected, ); if (pinMismatch) { return pinMismatch; @@ -653,14 +729,23 @@ export class HermesClient { headers: { origin }, }); socket = connectingSocket; + this.#connectingSocket = connectingSocket; await waitForSocketOpen(connectingSocket, timeoutMs); + if (this.#explicitlyClosed) { + return closedDuringConnectResult(); + } // The probe runs once per socket, with id 1; user calls start at 2. const probe = await runIdentityProbe(connectingSocket, timeoutMs, 1); if (!probe.ok) { return { ok: false, code: probe.code, message: probe.message }; } + // Checked after every await of the connect path: a close() during the + // connect must not pin the device, call `onPin` or adopt the socket. + if (this.#explicitlyClosed) { + return closedDuringConnectResult(); + } const targetDeviceId = selection.target.reactNative?.logicalDeviceId; if (!targetDeviceId) { @@ -680,15 +765,8 @@ export class HermesClient { message: `Hermes target device ${targetDeviceId} does not match session pin ${this.#pinnedDeviceId}`, }; } - if (this.#explicitlyClosed) { - return { - ok: false, - code: HERMES_CONNECTION_FAILED, - message: `${CLIENT_CLOSED_MESSAGE} before the connection completed`, - }; - } - this.#adopt(connectingSocket, timeoutMs); + this.#adopt(connectingSocket); adopted = true; this.#status = 'open'; @@ -734,6 +812,9 @@ export class HermesClient { message: `Hermes CDP connection failed: ${message}`, }; } finally { + if (this.#connectingSocket === socket) { + this.#connectingSocket = undefined; + } if (!adopted) { this.#status = 'closed'; if (socket) { @@ -743,6 +824,62 @@ export class HermesClient { } } + /** + * Awaits a connect, giving up with `undefined` as soon as the signal aborts. + * The shared connect itself keeps running for other callers. + * + * @param timeoutMs - The connect timeout. + * @param signal - The call's abort signal, if any. + * @returns The connect result, or undefined when the call was aborted. + */ + async #connectWithAbort( + timeoutMs: number, + signal: AbortSignal | undefined, + ): Promise { + const connecting = this.connect({ timeoutMs }); + if (!signal) { + return await connecting; + } + if (signal.aborted) { + return undefined; + } + + let handleAbort = (): void => undefined; + const aborted = new Promise((resolve) => { + handleAbort = (): void => resolve(undefined); + signal.addEventListener('abort', handleAbort, { once: true }); + }); + + try { + return await Promise.race([connecting, aborted]); + } finally { + signal.removeEventListener('abort', handleAbort); + } + } + + /** + * Restarts the reconnect loop after a caller-driven connect failed while the + * connection was lost, so a `send` during the reconnect wait cannot stop the + * background loop. + * + * Does nothing after {@link close} or when the failure is terminal (device + * pin mismatch, WebSocket unavailable): retrying cannot fix those. + * + * @param result - The failed caller-driven connect result. + */ + #resumeReconnectAfterFailedCall(result: HermesConnectResult): void { + if (result.ok || !this.#socketLost || this.#explicitlyClosed) { + return; + } + if ( + result.code === HERMES_DEVICE_PIN_MISMATCH || + result.code === HERMES_WEBSOCKET_UNAVAILABLE + ) { + return; + } + this.#scheduleReconnect(); + } + /** * Turns a pinned selection failure into `HERMES_DEVICE_PIN_MISMATCH` during a * reconnect when Metro reports a different device. Inspection only: no socket @@ -750,16 +887,16 @@ export class HermesClient { * * @param targets - All discovered targets. * @param code - The selection failure code. - * @param reconnect - True for an automatic reconnect attempt. + * @param reconnected - True when the previous connection was lost. * @returns The mismatch result, or undefined to keep the selection failure. */ #detectReconnectPinMismatch( targets: Parameters[0], code: string, - reconnect: boolean, + reconnected: boolean, ): { ok: false; code: string; message: string } | undefined { const pinnedDeviceId = this.#pinnedDeviceId; - if (!reconnect || !pinnedDeviceId || code !== HERMES_TARGET_NOT_FOUND) { + if (!reconnected || !pinnedDeviceId || code !== HERMES_TARGET_NOT_FOUND) { return undefined; } @@ -780,17 +917,20 @@ export class HermesClient { } /** - * Adopts an open, verified socket: installs the dispatcher and resets the CDP - * id sequence for the new connection. + * Adopts an open, verified socket: installs the dispatcher, resets the CDP id + * sequence for the new connection and closes any socket it replaces, so a + * reconnect never leaks the previous socket. * * @param socket - The verified socket. - * @param timeoutMs - The timeout to reuse for later reconnect attempts. */ - #adopt(socket: WebSocket, timeoutMs: number): void { + #adopt(socket: WebSocket): void { + const previous = this.#socket; this.#detachSocket(); this.#socket = socket; + if (previous && previous !== socket) { + closeSocket(previous); + } this.#nextId = 2; - this.#connectTimeoutMs = timeoutMs; this.#socketTracksContexts = false; this.#sawContextOnSocket = false; this.#contextDestroyedForReload = false; @@ -884,8 +1024,12 @@ export class HermesClient { } /** - * Emits `contextCreated` for a reload, skipping the first context of the - * socket (covered by the connect event). + * Emits `contextCreated` for a reload. + * + * The first context of a socket is covered by the connect event and is not + * re-emitted, unless a `contextDestroyed{reload}` was already seen on this + * socket: some devices do not report the initial context, so the next one + * after a destroy is a reload, not the socket's first context. * * @param params - The `Runtime.executionContextCreated` payload. */ @@ -893,7 +1037,9 @@ export class HermesClient { const executionContextId = readExecutionContextId(params); if (!this.#sawContextOnSocket) { this.#sawContextOnSocket = true; - return; + if (!this.#contextDestroyedForReload) { + return; + } } const target = this.#target; @@ -963,7 +1109,11 @@ export class HermesClient { /** * Releases the adopted socket after an unexpected loss, fails pending calls, - * emits `disconnected` and starts the reconnect loop. + * starts the reconnect loop and then emits `disconnected`. + * + * The loop starts first on purpose: a `disconnected` listener may call + * {@link send}, and the socket it opens must already be the one the next + * scheduled attempt finds. * * @param reason - Why the socket was lost, used for the `disconnected` event. * @param pendingMessage - Overrides the pending-call failure message. @@ -978,17 +1128,18 @@ export class HermesClient { this.#socket = undefined; this.#target = undefined; this.#status = 'closed'; + this.#socketLost = true; closeSocket(socket); this.#failAllPending( HERMES_CONNECTION_FAILED, pendingMessage ?? `Hermes CDP connection closed: ${reason}`, ); - this.#emit('disconnected', { reason }); if (!this.#explicitlyClosed) { this.#startReconnect(); } + this.#emit('disconnected', { reason }); } /** @@ -1031,23 +1182,32 @@ export class HermesClient { } /** - * Runs one reconnect attempt. Failures schedule the next backoff step; a - * device pin mismatch stops the loop so the wrong device is never used. + * Runs one reconnect attempt. + * + * Does nothing when the client is already connected: a caller (for example a + * `disconnected` listener) may have connected before the timer fired, and a + * second socket must never be opened. Failures schedule the next backoff + * step; a device pin mismatch or a missing WebSocket stops the loop so the + * wrong device is never used. */ async #attemptReconnect(): Promise { if (this.#explicitlyClosed) { return; } + if (this.isConnected) { + this.#resetReconnect(); + return; + } try { const result = await this.#connectOnce( - this.#connectTimeoutMs, + this.#reconnect.connectTimeoutMs, this.#reconnectAttempt, ); if (this.#explicitlyClosed) { return; } - if (result.ok) { - this.#reconnectAttempt = 0; + if (result.ok || this.isConnected) { + this.#resetReconnect(); return; } if ( @@ -1063,6 +1223,14 @@ export class HermesClient { } } + /** + * Clears the pending reconnect timer and resets the backoff counter. + */ + #resetReconnect(): void { + this.#clearReconnectTimer(); + this.#reconnectAttempt = 0; + } + /** * Clears the pending reconnect timer, if any. */ @@ -1105,6 +1273,10 @@ export class HermesClient { /** * Calls every listener registered for an event. * + * A throwing listener is isolated (the socket handler and the other listeners + * keep working) and reported to the `listenerError` listeners. A throwing + * `listenerError` listener is swallowed, so the report never recurses. + * * @param event - The lifecycle event name or CDP method name. * @param payload - The payload to deliver. */ @@ -1116,14 +1288,51 @@ export class HermesClient { for (const listener of [...listeners]) { try { (listener as (value: unknown) => void)(payload); + } catch (error) { + if (event !== LISTENER_ERROR_EVENT) { + this.#emitListenerError(event, error); + } + } + } + } + + /** + * Reports a throwing listener to the `listenerError` listeners. + * + * @param event - The event name whose listener threw. + * @param error - The thrown value. + */ + #emitListenerError(event: string, error: unknown): void { + const listeners = this.#listeners.get(LISTENER_ERROR_EVENT); + if (!listeners) { + return; + } + const payload: HermesListenerErrorEvent = { event, error }; + for (const listener of [...listeners]) { + try { + (listener as (value: HermesListenerErrorEvent) => void)(payload); } catch { - // A failing listener must not break the socket handler or the - // other listeners. + // A failing `listenerError` listener must not recurse or break the + // socket handler. } } } } +/** + * Builds the failure result for a connect that was still in flight when the + * client was closed. + * + * @returns A `HERMES_CONNECTION_FAILED` failure. + */ +function closedDuringConnectResult(): HermesFailureResult { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: `${CLIENT_CLOSED_MESSAGE} before the connection completed`, + }; +} + /** * Builds the failure result for a call made while the socket is not open. * From 81961c004bdab9fec96f678c06738b5f3a56fff0 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Mon, 9 Nov 2026 14:31:23 +0000 Subject: [PATCH 20/33] test: assert HERMES_TIMEOUT for a Hermes CDP user-method timeout The test still expected HERMES_CONNECTION_FAILED via the finally close, but a user-method timeout has resolved to HERMES_TIMEOUT since runHermesCdp moved onto HermesClient. --- src/hermes/hermes-cdp.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/hermes/hermes-cdp.test.ts b/src/hermes/hermes-cdp.test.ts index 6a77300..bb3523f 100644 --- a/src/hermes/hermes-cdp.test.ts +++ b/src/hermes/hermes-cdp.test.ts @@ -729,7 +729,7 @@ describe('runHermesCdp', () => { expect(result.message).toContain('timed out'); }); - it('user-method timeout → HERMES_CONNECTION_FAILED via finally close', async () => { + it('user-method timeout → HERMES_TIMEOUT and closes the socket', async () => { vi.useFakeTimers(); MockWebSocket.responseFactory = (request) => request.id === 1 ? defaultResponseFactory(request) : undefined; @@ -740,7 +740,8 @@ describe('runHermesCdp', () => { await vi.advanceTimersByTimeAsync(1_000); const result = await resultPromise; - expect(result.ok).toBe(false); + expectError(result, HERMES_TIMEOUT); + expect(result.message).toContain('timed out'); expect(socketAt(0).readyState).toBe(MockWebSocket.closed); }); From 5069bf67ea1eaf5a4140c7a7a59490594f4bee14 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 11:34:00 +0000 Subject: [PATCH 21/33] fix: emit reconnectFailed and let a caller restart a stopped HermesClient reconnect --- src/hermes/hermes-client.test.ts | 209 +++++++++++++++++++++++++++++++ src/hermes/hermes-client.ts | 189 +++++++++++++++++++++------- src/index.ts | 1 + 3 files changed, 357 insertions(+), 42 deletions(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index c41f6ba..14caac0 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -6,6 +6,7 @@ import { HERMES_BLOCKED_METHOD, HERMES_CDP_FAILED, HERMES_CONNECTION_FAILED, + HERMES_DEVICE_PIN_MISMATCH, HERMES_TIMEOUT, HERMES_WEBSOCKET_UNAVAILABLE, IDENTITY_PROBE_EXPR, @@ -17,6 +18,7 @@ import type { HermesContextCreatedEvent, HermesContextDestroyedEvent, HermesListenerErrorEvent, + HermesReconnectFailedEvent, } from './hermes-client.js'; const APP_ID = 'io.metamask.MetaMask'; @@ -928,6 +930,213 @@ describe('HermesClient', () => { client.close(); }); + it('emits reconnectFailed once when the loop gives up on a listen-only client', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const failed: HermesReconnectFailedEvent[] = []; + const disconnected = vi.fn(); + const created = vi.fn(); + client.on('reconnectFailed', (event) => failed.push(event)); + client.on('disconnected', disconnected); + client.on('contextCreated', created); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + await vi.advanceTimersByTimeAsync(1_000); + + // Three attempts, each trying /json then /json/list. + expect(fetchMock).toHaveBeenCalledTimes(6); + expect(failed).toStrictEqual([ + { + attempts: 3, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('ECONNREFUSED'), + }, + ]); + expect(disconnected).toHaveBeenCalledTimes(1); + + // Nothing retries for a client that only listens. + await vi.advanceTimersByTimeAsync(60_000); + expect(fetchMock).toHaveBeenCalledTimes(6); + expect(failed).toHaveLength(1); + expect(created).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(false); + }); + + it('restarts the stopped reconnect loop when a send fails after it gave up', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 2 }, + }); + const failed: HermesReconnectFailedEvent[] = []; + const created: HermesContextCreatedEvent[] = []; + const reconnected = vi.fn(); + client.on('reconnectFailed', (event) => failed.push(event)); + client.on('contextCreated', (event) => created.push(event)); + client.on('reconnected', reconnected); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(1_000); + expect(failed).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(4); + + // A caller tries while Metro is still down: its failure restarts the loop. + const sending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + await vi.advanceTimersByTimeAsync(0); + expectError(await sending, HERMES_CONNECTION_FAILED); + expect(fetchMock).toHaveBeenCalledTimes(6); + + // The restarted loop begins at the first backoff delay (10 ms). + await vi.advanceTimersByTimeAsync(10); + expect(fetchMock).toHaveBeenCalledTimes(8); + + // Metro comes back before the restarted loop gives up. + mockDiscovery([target({ id: 'device-page-2' })]); + await vi.advanceTimersByTimeAsync(20); + + expect(client.isConnected).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect( + created.filter((event) => event.reason === 'reconnect'), + ).toHaveLength(1); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + reconnected: true, + target: { id: 'device-page-2' }, + }); + expect(reconnected).toHaveBeenCalledTimes(1); + expect(reconnected).toHaveBeenCalledWith( + expect.objectContaining({ attempts: 2 }), + ); + expect(failed).toHaveLength(1); + + // Connected again: no further attempt runs. + await vi.advanceTimersByTimeAsync(1_000); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(2); + + client.close(); + }); + + it('emits reconnectFailed once on a pin mismatch and never restarts the loop', async () => { + vi.useFakeTimers(); + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const failed: HermesReconnectFailedEvent[] = []; + client.on('reconnectFailed', (event) => failed.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + mockDiscovery([ + target({ + id: 'other-device', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-2&page=1`, + reactNative: { + logicalDeviceId: 'logical-device-2', + capabilities: { nativePageReloads: true }, + }, + }), + ]); + socketAt(0).drop('app reload'); + await vi.advanceTimersByTimeAsync(1_000); + + expect(failed).toStrictEqual([ + { + attempts: 1, + code: HERMES_DEVICE_PIN_MISMATCH, + message: expect.stringContaining('logical-device-2'), + }, + ]); + expect(fetchMock).toHaveBeenCalledTimes(1); + + // A caller hitting the same terminal failure does not restart the loop. + const sending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + await vi.advanceTimersByTimeAsync(0); + expectError(await sending, HERMES_DEVICE_PIN_MISMATCH); + + await vi.advanceTimersByTimeAsync(60_000); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(failed).toHaveLength(1); + expect(FakeWebSocket.instances).toHaveLength(1); + }); + + it('emits reconnectFailed once when WebSocket becomes unavailable and never restarts the loop', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const failed: HermesReconnectFailedEvent[] = []; + client.on('reconnectFailed', (event) => failed.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + socketAt(0).drop('metro restart'); + vi.stubGlobal('WebSocket', undefined); + await vi.advanceTimersByTimeAsync(1_000); + + expect(failed).toStrictEqual([ + { + attempts: 1, + code: HERMES_WEBSOCKET_UNAVAILABLE, + message: expect.any(String), + }, + ]); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expectError(result, HERMES_WEBSOCKET_UNAVAILABLE); + + await vi.advanceTimersByTimeAsync(60_000); + expect(failed).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('does not emit reconnectFailed when auto-reconnect is disabled', async () => { + const client = createClient({ reconnect: { maxAttempts: 0 } }); + const failed = vi.fn(); + client.on('reconnectFailed', failed); + + await client.connect({ timeoutMs: 1_000 }); + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + await delay(20); + + expectError(result, HERMES_CONNECTION_FAILED); + expect(failed).not.toHaveBeenCalled(); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + it('reports reason reconnect when a send reconnects after a socket loss', async () => { const client = createClient({ reconnect: { maxAttempts: 0 } }); const created: HermesContextCreatedEvent[] = []; diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 651afee..ee6f56e 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -73,9 +73,11 @@ export type HermesClientReconnectOptions = { /** Upper bound for the backoff delay in milliseconds. */ maxDelayMs?: number; /** - * Number of attempts before giving up. When the loop gives up the client - * reports itself disconnected and the next {@link HermesClient.send} tries a - * fresh connect. `0` disables auto-reconnect. + * Number of attempts before giving up. When the loop gives up it emits + * `reconnectFailed`, the client stays disconnected, and the next + * {@link HermesClient.send} tries a fresh connect; if that connect fails, the + * loop starts again from the first backoff delay. `0` disables + * auto-reconnect (and `reconnectFailed`). */ maxAttempts?: number; /** @@ -226,6 +228,22 @@ export type HermesReconnectedEvent = { attempts: number; }; +/** + * Payload of the `reconnectFailed` lifecycle event, emitted once each time the + * background reconnect loop gives up: after `maxAttempts` failed attempts, or + * at once on a terminal failure (`HERMES_DEVICE_PIN_MISMATCH`, + * `HERMES_WEBSOCKET_UNAVAILABLE`). The client then stays disconnected until a + * caller connects. + */ +export type HermesReconnectFailedEvent = { + /** How many backoff attempts ran before the loop gave up. */ + attempts: number; + /** The stable error code of the last failed attempt. */ + code: string; + /** The human-readable message of the last failed attempt. */ + message: string; +}; + /** * Payload of the `listenerError` lifecycle event, emitted when one of the * client's own listeners throws. The exception is isolated so it cannot break @@ -247,6 +265,7 @@ export type HermesClientEventMap = { contextDestroyed: HermesContextDestroyedEvent; disconnected: HermesDisconnectedEvent; reconnected: HermesReconnectedEvent; + reconnectFailed: HermesReconnectFailedEvent; listenerError: HermesListenerErrorEvent; }; @@ -278,9 +297,15 @@ type PendingCall = { * their scripts. * * An unexpected socket loss starts a background reconnect loop. A caller's - * {@link connect} or {@link send} never stops that loop: while the connection is - * lost, a failed caller-driven attempt (re)starts it, and a successful one is - * reported as `contextCreated` with `reason: 'reconnect'`. + * {@link connect} or {@link send} never stops that loop, and a successful one is + * reported as `contextCreated` with `reason: 'reconnect'`. When the loop gives + * up (after `maxAttempts`, or at once on a device pin mismatch or a missing + * WebSocket) it emits `reconnectFailed` and the client stays disconnected. + * While the connection is lost, a failed caller-driven attempt continues a + * running loop, or restarts a stopped one from the first backoff delay; a + * terminal failure (`HERMES_DEVICE_PIN_MISMATCH`, `HERMES_WEBSOCKET_UNAVAILABLE`) + * never restarts it. A client that only listens should handle + * `reconnectFailed`: nothing else retries for it. * * A listener that throws is isolated and reported through the `listenerError` * lifecycle event; it never breaks the socket handler or the other listeners. @@ -354,6 +379,20 @@ export class HermesClient { #reconnectAttempt = 0; + /** + * Whether the background reconnect loop is running: a backoff timer is + * pending, or an attempt (its own or a caller's it waits on) is in flight. + * False before any loss, after a successful connect, after {@link close}, + * and once the loop gave up. + */ + #reconnectRunning = false; + + /** + * Bumped every time the loop starts, stops or resets, so an attempt that was + * in flight across that change does not schedule (or report) anything. + */ + #reconnectGeneration = 0; + #explicitlyClosed = false; constructor(options: HermesClientOptions) { @@ -411,8 +450,11 @@ export class HermesClient { * `reason: 'reconnect'` when the previous connection was lost unexpectedly. * A client closed with {@link close} reopens. * - * A connect never stops the background reconnect loop: a failed attempt while - * the connection is lost restarts it. + * A connect never stops the background reconnect loop. When it fails while + * the connection is lost and the loop has stopped (it gave up), the loop + * restarts from the first backoff delay, unless the failure is terminal + * (`HERMES_DEVICE_PIN_MISMATCH`, `HERMES_WEBSOCKET_UNAVAILABLE`). A running + * loop keeps its own schedule. * * @param options - The connect timeout. * @returns The verified target or a classified failure. @@ -425,8 +467,13 @@ export class HermesClient { return { ok: true, target: this.#target }; } + // Read before connecting: a failure that ends the loop's own last attempt + // (which this call may share) must not restart the loop it just stopped. + const loopStopped = !this.#reconnectRunning; const result = await this.#connectOnce(timeoutMs); - this.#resumeReconnectAfterFailedCall(result); + if (loopStopped) { + this.#resumeReconnectAfterFailedCall(result); + } return result; } @@ -529,9 +576,10 @@ export class HermesClient { /** * Subscribes to a lifecycle event or a CDP event. * - * Lifecycle names are `contextCreated`, `contextDestroyed`, `disconnected` - * and `reconnected`. Any other name receives the CDP event messages of that - * `method` (for example `Runtime.consoleAPICalled`). + * Lifecycle names are the keys of {@link HermesClientEventMap}: + * `contextCreated`, `contextDestroyed`, `disconnected`, `reconnected`, + * `reconnectFailed` and `listenerError`. Any other name receives the CDP + * event messages of that `method` (for example `Runtime.consoleAPICalled`). * * @param event - The lifecycle event name or CDP method name. * @param listener - Called with the typed lifecycle payload or the CDP event. @@ -577,8 +625,7 @@ export class HermesClient { close(): void { this.#explicitlyClosed = true; this.#socketLost = false; - this.#clearReconnectTimer(); - this.#reconnectAttempt = 0; + this.#resetReconnect(); this.#failAllPending( HERMES_CONNECTION_FAILED, `${CLIENT_CLOSED_MESSAGE}: the connection was closed`, @@ -858,12 +905,13 @@ export class HermesClient { } /** - * Restarts the reconnect loop after a caller-driven connect failed while the - * connection was lost, so a `send` during the reconnect wait cannot stop the - * background loop. + * Restarts the stopped reconnect loop from the first backoff delay after a + * caller-driven connect failed while the connection was lost, so a client + * whose loop gave up recovers once a caller tries again. * - * Does nothing after {@link close} or when the failure is terminal (device - * pin mismatch, WebSocket unavailable): retrying cannot fix those. + * Does nothing after {@link close}, while the loop is still running, or when + * the failure is terminal (device pin mismatch, WebSocket unavailable): + * retrying cannot fix those. * * @param result - The failed caller-driven connect result. */ @@ -871,13 +919,10 @@ export class HermesClient { if (result.ok || !this.#socketLost || this.#explicitlyClosed) { return; } - if ( - result.code === HERMES_DEVICE_PIN_MISMATCH || - result.code === HERMES_WEBSOCKET_UNAVAILABLE - ) { + if (isTerminalConnectFailure(result)) { return; } - this.#scheduleReconnect(); + this.#startReconnect(); } /** @@ -1143,27 +1188,43 @@ export class HermesClient { } /** - * Restarts the reconnect loop from the first backoff delay. + * Starts the reconnect loop from the first backoff delay, unless it is + * already running or auto-reconnect is disabled (`maxAttempts: 0`). */ #startReconnect(): void { - if (this.#explicitlyClosed || this.#reconnectTimer !== undefined) { + if ( + this.#explicitlyClosed || + this.#reconnectRunning || + this.#reconnect.maxAttempts === 0 + ) { return; } + this.#reconnectGeneration += 1; + this.#reconnectRunning = true; this.#reconnectAttempt = 0; this.#scheduleReconnect(); } /** * Schedules the next reconnect attempt with exponential backoff, or gives up - * after `maxAttempts` (the client then reports itself disconnected and the - * next {@link send} tries a fresh connect). + * after `maxAttempts`: it then emits `reconnectFailed` and the client stays + * disconnected until a caller connects. + * + * @param failure - The failure of the attempt that just ran, reported by + * `reconnectFailed` if the loop gives up now. */ - #scheduleReconnect(): void { + #scheduleReconnect(failure?: HermesFailureResult): void { if (this.#explicitlyClosed || this.#reconnectTimer !== undefined) { return; } if (this.#reconnectAttempt >= this.#reconnect.maxAttempts) { - this.#status = 'closed'; + this.#stopReconnect( + failure ?? { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: 'Hermes CDP reconnect gave up', + }, + ); return; } @@ -1187,8 +1248,8 @@ export class HermesClient { * Does nothing when the client is already connected: a caller (for example a * `disconnected` listener) may have connected before the timer fired, and a * second socket must never be opened. Failures schedule the next backoff - * step; a device pin mismatch or a missing WebSocket stops the loop so the - * wrong device is never used. + * step; a device pin mismatch or a missing WebSocket stops the loop at once + * (and emits `reconnectFailed`) so the wrong device is never used. */ async #attemptReconnect(): Promise { if (this.#explicitlyClosed) { @@ -1198,36 +1259,65 @@ export class HermesClient { this.#resetReconnect(); return; } + const generation = this.#reconnectGeneration; try { const result = await this.#connectOnce( this.#reconnect.connectTimeoutMs, this.#reconnectAttempt, ); - if (this.#explicitlyClosed) { + // A close(), a success or a restart while this attempt was in flight + // already decided what happens next. + if (this.#explicitlyClosed || generation !== this.#reconnectGeneration) { return; } if (result.ok || this.isConnected) { this.#resetReconnect(); return; } - if ( - result.code === HERMES_DEVICE_PIN_MISMATCH || - result.code === HERMES_WEBSOCKET_UNAVAILABLE - ) { - this.#status = 'closed'; + if (isTerminalConnectFailure(result)) { + this.#stopReconnect(result); return; } - this.#scheduleReconnect(); - } catch { - this.#scheduleReconnect(); + this.#scheduleReconnect(result); + } catch (error) { + if (this.#explicitlyClosed || generation !== this.#reconnectGeneration) { + return; + } + const message = error instanceof Error ? error.message : String(error); + this.#scheduleReconnect({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: `Hermes CDP connection failed: ${message}`, + }); } } /** - * Clears the pending reconnect timer and resets the backoff counter. + * Stops the reconnect loop for good (until a caller restarts it) and emits + * `reconnectFailed` once. + * + * @param failure - The failure of the last attempt. + */ + #stopReconnect(failure: HermesFailureResult): void { + this.#clearReconnectTimer(); + this.#reconnectGeneration += 1; + this.#reconnectRunning = false; + this.#status = 'closed'; + this.#emit('reconnectFailed', { + attempts: this.#reconnectAttempt, + code: failure.code, + message: failure.message, + }); + } + + /** + * Stops the reconnect loop after a successful connect or {@link close}: clears + * the pending timer and resets the backoff counter. */ #resetReconnect(): void { this.#clearReconnectTimer(); + this.#reconnectGeneration += 1; + this.#reconnectRunning = false; this.#reconnectAttempt = 0; } @@ -1333,6 +1423,21 @@ function closedDuringConnectResult(): HermesFailureResult { }; } +/** + * Whether a connect failure is terminal for the reconnect loop: retrying cannot + * fix a device pin mismatch (it must never connect to the wrong device) or a + * missing WebSocket implementation. + * + * @param result - The failed connect result. + * @returns True when the loop must stop and not restart on its own. + */ +function isTerminalConnectFailure(result: HermesFailureResult): boolean { + return ( + result.code === HERMES_DEVICE_PIN_MISMATCH || + result.code === HERMES_WEBSOCKET_UNAVAILABLE + ); +} + /** * Builds the failure result for a call made while the socket is not open. * diff --git a/src/index.ts b/src/index.ts index da1ead9..b5b98df 100644 --- a/src/index.ts +++ b/src/index.ts @@ -71,6 +71,7 @@ export type { HermesContextDestroyedEvent, HermesDisconnectedEvent, HermesReconnectedEvent, + HermesReconnectFailedEvent, } from './hermes/hermes-client.js'; export { From f69a403f2bdb5b5db3e4a254f6ec2cd85c11afbf Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 11:39:06 +0000 Subject: [PATCH 22/33] fix: bound a HermesClient send's wait for a shared connect by its timeout --- src/hermes/hermes-client.test.ts | 174 +++++++++++++++++++++++++++++++ src/hermes/hermes-client.ts | 101 ++++++++++++++++-- 2 files changed, 265 insertions(+), 10 deletions(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 14caac0..6c12ac9 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -1318,6 +1318,180 @@ describe('HermesClient', () => { client.close(); }); + it('bounds a send that joins a background reconnect attempt by its own timeout', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { + initialDelayMs: 10, + maxDelayMs: 10, + maxAttempts: 3, + connectTimeoutMs: 10_000, + }, + }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + // Metro is slow to answer: the background attempt's discovery hangs. + let resolveDiscovery!: (value: unknown) => void; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + resolveDiscovery = resolve; + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(10); + expect(fetchMock).toHaveBeenCalledTimes(1); + + let settledAt: number | undefined; + const startedAt = Date.now(); + const sending = client + .send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }) + .then((result) => { + settledAt = Date.now() - startedAt; + return result; + }); + + await vi.advanceTimersByTimeAsync(999); + expect(settledAt).toBeUndefined(); + await vi.advanceTimersByTimeAsync(1); + + const result = await sending; + expectError(result, HERMES_TIMEOUT); + expect(settledAt).toBe(1_000); + // The send joined the attempt: no discovery or socket of its own. + expect(fetchMock).toHaveBeenCalledTimes(1); + + // The background attempt keeps running and succeeds later, within its own + // 10 s budget. + await vi.advanceTimersByTimeAsync(4_000); + resolveDiscovery({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); + await vi.advanceTimersByTimeAsync(0); + + expect(client.isConnected).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ reason: 'reconnect' }); + + client.close(); + }); + + it('gives a background attempt its full connectTimeoutMs after a short caller connect fails', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { + initialDelayMs: 100, + maxDelayMs: 100, + maxAttempts: 1, + connectTimeoutMs: 10_000, + }, + }); + const created: HermesContextCreatedEvent[] = []; + const failed = vi.fn(); + client.on('contextCreated', (event) => created.push(event)); + client.on('reconnectFailed', failed); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + // Discovery hangs until it is aborted; record each abort time. + const resolvers: ((value: unknown) => void)[] = []; + const abortedAt: number[] = []; + const startedAt = Date.now(); + fetchMock = vi.fn( + async (_url: string, init?: { signal?: AbortSignal }) => + new Promise((resolve, reject) => { + resolvers.push(resolve); + init?.signal?.addEventListener('abort', () => { + abortedAt.push(Date.now() - startedAt); + reject(new Error('discovery aborted')); + }); + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + // A caller starts a short connect before the background attempt fires. + const sending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 200, + }); + await vi.advanceTimersByTimeAsync(0); + expect(fetchMock).toHaveBeenCalledTimes(1); + + // The background attempt fires at 100 ms and meets the caller's connect. + await vi.advanceTimersByTimeAsync(100); + expect(fetchMock).toHaveBeenCalledTimes(1); + + // The caller's connect gives up at 200 ms per discovery path. + await vi.advanceTimersByTimeAsync(300); + expectError(await sending, HERMES_CONNECTION_FAILED); + expect(abortedAt).toStrictEqual([200, 400]); + + // The attempt then runs its own connect: its discovery is not aborted at + // the caller's 200 ms, only at its own 10 s. + expect(fetchMock).toHaveBeenCalledTimes(3); + await vi.advanceTimersByTimeAsync(9_999); + expect(abortedAt).toStrictEqual([200, 400]); + expect(failed).not.toHaveBeenCalled(); + + resolvers[2]?.({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); + await vi.advanceTimersByTimeAsync(0); + + expect(client.isConnected).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ reason: 'reconnect' }); + expect(failed).not.toHaveBeenCalled(); + + client.close(); + }); + + it('opens one socket when a background attempt meets a caller connect that succeeds', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 100, maxDelayMs: 100, maxAttempts: 3 }, + }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + let resolveDiscovery!: (value: unknown) => void; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + resolveDiscovery = resolve; + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + const sending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + await vi.advanceTimersByTimeAsync(150); + resolveDiscovery({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); + await vi.advanceTimersByTimeAsync(0); + + expect((await sending).ok).toBe(true); + await vi.advanceTimersByTimeAsync(1_000); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ reason: 'reconnect' }); + + client.close(); + }); + it('fails a send with HERMES_ABORTED while it is still connecting', async () => { fetchMock = vi.fn(async () => new Promise(() => undefined)); vi.stubGlobal('fetch', fetchMock); diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index ee6f56e..51c42cf 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -82,8 +82,10 @@ export type HermesClientReconnectOptions = { maxAttempts?: number; /** * Connect timeout for automatic reconnect attempts, in milliseconds - * (default 10 s). Per-call `timeoutMs` values only apply to the call's own - * connect, so a short call timeout never shortens later reconnect attempts. + * (default 10 s). Per-call `timeoutMs` values never shorten a reconnect + * attempt: an attempt that finds a caller's connect in flight waits for it + * (so no second socket opens) and, if it fails, then runs its own connect + * with this full timeout. */ connectTimeoutMs?: number; }; @@ -159,9 +161,25 @@ export type HermesConnectResult = * Options for {@link HermesClient.send}. */ export type HermesSendOptions = { - /** Per-call timeout in milliseconds. */ + /** + * Per-phase timeout in milliseconds. It bounds each phase of the call on its + * own, not their sum: + * - Connect, when the client is not connected. If this call starts the + * connect, each connect step (discovery, socket open, identity probe) gets + * `timeoutMs`, as in `runHermesCdp`. If a connect is already in + * flight (another call's, or a background reconnect attempt), this call + * waits for it at most `timeoutMs`, then fails with `HERMES_TIMEOUT`; the + * shared connect keeps running for the others. + * - Response: once connected, the CDP response gets `timeoutMs`. + * + * So a call that has to connect can take longer than `timeoutMs`. To bound + * the total time, pass `signal: AbortSignal.timeout(n)`. + */ timeoutMs: number; - /** Aborts the call; the pending response is discarded. */ + /** + * Aborts the call, including its wait for a connect; the pending response is + * discarded. `AbortSignal.timeout(n)` bounds the total time of the call. + */ signal?: AbortSignal; }; @@ -446,8 +464,11 @@ export class HermesClient { * * Idempotent: when already connected it resolves with the current target, and * concurrent callers share one in-flight connect (one discovery fetch, one - * socket, one identity probe). Emits `contextCreated` on success, with - * `reason: 'reconnect'` when the previous connection was lost unexpectedly. + * socket, one identity probe). A caller that joins a connect already in + * flight waits for it at most its own `timeoutMs`, then gets + * `HERMES_TIMEOUT` while the connect keeps running. Emits `contextCreated` + * on success, with `reason: 'reconnect'` when the previous connection was + * lost unexpectedly. * A client closed with {@link close} reopens. * * A connect never stops the background reconnect loop. When it fails while @@ -467,6 +488,14 @@ export class HermesClient { return { ok: true, target: this.#target }; } + const joined = this.#inFlightConnect; + if (joined) { + // Another caller or the reconnect loop owns this connect and its + // timeouts: wait for it at most this call's own timeout. It keeps running + // for the others when this call stops waiting. + return await waitAtMost(joined, timeoutMs); + } + // Read before connecting: a failure that ends the loop's own last attempt // (which this call may share) must not restart the loop it just stopped. const loopStopped = !this.#reconnectRunning; @@ -480,10 +509,12 @@ export class HermesClient { /** * Sends one CDP method over the persistent socket and awaits its response. * - * Connects first when needed. Many calls can be in flight: responses are - * matched by CDP `id`. On timeout the call fails with `HERMES_TIMEOUT`; on - * abort with `HERMES_ABORTED`. Both remove the pending entry, so a late - * response is ignored. A CDP-level error becomes `HERMES_CDP_FAILED`. + * Connects first when needed; see {@link HermesSendOptions.timeoutMs} for how + * the timeout applies to the connect and the response. Many calls can be in + * flight: responses are matched by CDP `id`. On timeout the call fails with + * `HERMES_TIMEOUT`; on abort with `HERMES_ABORTED`. Both remove the pending + * entry, so a late response is ignored. A CDP-level error becomes + * `HERMES_CDP_FAILED`. * * @param method - The CDP method, e.g. `Runtime.evaluate`. * @param params - The CDP parameters. @@ -1261,6 +1292,25 @@ export class HermesClient { } const generation = this.#reconnectGeneration; try { + // A caller's connect is already in flight, with the caller's (possibly + // shorter) timeouts. Wait for it instead of opening a second socket; if + // it fails, this attempt then runs its own connect with the full + // `connectTimeoutMs`. + let callerConnect = this.#inFlightConnect; + while (callerConnect) { + await callerConnect; + if ( + this.#explicitlyClosed || + generation !== this.#reconnectGeneration + ) { + return; + } + if (this.isConnected) { + this.#resetReconnect(); + return; + } + callerConnect = this.#inFlightConnect; + } const result = await this.#connectOnce( this.#reconnect.connectTimeoutMs, this.#reconnectAttempt, @@ -1423,6 +1473,37 @@ function closedDuringConnectResult(): HermesFailureResult { }; } +/** + * Waits for a shared connect at most `timeoutMs`. The connect itself keeps + * running; only this wait stops. + * + * @param connecting - The shared in-flight connect. + * @param timeoutMs - The longest this caller waits, in milliseconds. + * @returns The connect result, or `HERMES_TIMEOUT` when the wait ran out first. + */ +async function waitAtMost( + connecting: Promise, + timeoutMs: number, +): Promise { + let timer: ReturnType | undefined; + const timedOut = new Promise((resolve) => { + timer = setTimeout(() => { + resolve({ + ok: false, + code: HERMES_TIMEOUT, + message: `Hermes CDP connect did not complete within ${timeoutMs}ms`, + }); + }, timeoutMs); + unrefTimer(timer); + }); + + try { + return await Promise.race([connecting, timedOut]); + } finally { + clearTimeout(timer); + } +} + /** * Whether a connect failure is terminal for the reconnect loop: retrying cannot * fix a device pin mismatch (it must never connect to the wrong device) or a From 878ac8300a8ce5845f7c0f87ea9cf2386563f84f Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 11:41:30 +0000 Subject: [PATCH 23/33] fix: export HermesListenerErrorEvent --- src/index.test.ts | 23 ++++++++++++++++++++++- src/index.ts | 1 + 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/index.test.ts b/src/index.test.ts index a9ed952..e6b97c9 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -1,6 +1,15 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, expectTypeOf } from 'vitest'; import * as publicApi from './index.js'; +import type { + HermesClientEventMap, + HermesContextCreatedEvent, + HermesContextDestroyedEvent, + HermesDisconnectedEvent, + HermesListenerErrorEvent, + HermesReconnectedEvent, + HermesReconnectFailedEvent, +} from './index.js'; describe('public API surface', () => { it('exports the element locator helpers consumers depend on', () => { @@ -28,6 +37,18 @@ describe('public API surface', () => { }); }); + it('exports HermesClient and every payload type of its event map', () => { + expect(typeof publicApi.HermesClient).toBe('function'); + expectTypeOf().toEqualTypeOf<{ + contextCreated: HermesContextCreatedEvent; + contextDestroyed: HermesContextDestroyedEvent; + disconnected: HermesDisconnectedEvent; + reconnected: HermesReconnectedEvent; + reconnectFailed: HermesReconnectFailedEvent; + listenerError: HermesListenerErrorEvent; + }>(); + }); + it('exports the typed idb transport error', () => { expect( new publicApi.IdbUnavailableError('IDB_HID_UNAVAILABLE', 'u', 'x').code, diff --git a/src/index.ts b/src/index.ts index b5b98df..424a197 100644 --- a/src/index.ts +++ b/src/index.ts @@ -70,6 +70,7 @@ export type { HermesContextCreatedReason, HermesContextDestroyedEvent, HermesDisconnectedEvent, + HermesListenerErrorEvent, HermesReconnectedEvent, HermesReconnectFailedEvent, } from './hermes/hermes-client.js'; From 36a2e3da58def62d32b6a3e229472b6f95bd5976 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 11:43:39 +0000 Subject: [PATCH 24/33] refactor: drop a HermesClient connect guard made redundant by the bounded join --- src/hermes/hermes-client.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 51c42cf..93a261d 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -496,13 +496,8 @@ export class HermesClient { return await waitAtMost(joined, timeoutMs); } - // Read before connecting: a failure that ends the loop's own last attempt - // (which this call may share) must not restart the loop it just stopped. - const loopStopped = !this.#reconnectRunning; const result = await this.#connectOnce(timeoutMs); - if (loopStopped) { - this.#resumeReconnectAfterFailedCall(result); - } + this.#resumeReconnectAfterFailedCall(result); return result; } From 0ca114e26ce91fcfd088cf76c6beeda287670e28 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 13:49:23 +0000 Subject: [PATCH 25/33] fix: make HermesClient trackContexts opt-in so sessions do not enable Runtime --- src/hermes/hermes-client.test.ts | 54 ++++++++++++++++++++++++++------ src/hermes/hermes-client.ts | 37 +++++++++++++++------- 2 files changed, 70 insertions(+), 21 deletions(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 6c12ac9..43924b0 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -249,7 +249,7 @@ describe('HermesClient', () => { }); it('connects once and runs the identity probe once across many sends', async () => { - const client = createClient(); + const client = createClient({ trackContexts: true }); const first = await client.send( 'Runtime.evaluate', @@ -311,7 +311,7 @@ describe('HermesClient', () => { }); it('sends Runtime.enable once per socket', async () => { - const client = createClient(); + const client = createClient({ trackContexts: true }); await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); @@ -322,6 +322,41 @@ describe('HermesClient', () => { ]); }); + it('does not send Runtime.enable or report reloads by default', async () => { + const client = createClient(); + const created: HermesContextCreatedEvent[] = []; + const destroyed = vi.fn(); + client.on('contextCreated', (event) => created.push(event)); + client.on('contextDestroyed', destroyed); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + + expect(socket.sent.filter(isRuntimeEnable)).toHaveLength(0); + expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2]); + + // Even if Hermes streamed context events, no reload is reported. + for (const message of [ + { + method: 'Runtime.executionContextCreated', + params: { context: { id: 1 } }, + }, + { method: 'Runtime.executionContextDestroyed', params: {} }, + { method: 'Runtime.executionContextsCleared', params: {} }, + { + method: 'Runtime.executionContextCreated', + params: { context: { id: 2 } }, + }, + ]) { + socket.receive(JSON.stringify(message)); + } + + expect(destroyed).not.toHaveBeenCalled(); + expect(created).toStrictEqual([ + expect.objectContaining({ reason: 'connect' }), + ]); + }); + it('does not send Runtime.enable when trackContexts is off', async () => { const client = createClient({ trackContexts: false }); const created = vi.fn(); @@ -343,7 +378,7 @@ describe('HermesClient', () => { }); it('emits one contextDestroyed and one reload contextCreated when the app reloads on the same socket', async () => { - const client = createClient(); + const client = createClient({ trackContexts: true }); const created: HermesContextCreatedEvent[] = []; const destroyed: HermesContextDestroyedEvent[] = []; const raw: HermesCdpEvent[] = []; @@ -415,7 +450,7 @@ describe('HermesClient', () => { } return undefined; }; - const client = createClient(); + const client = createClient({ trackContexts: true }); const created = vi.fn(); client.on('contextCreated', created); @@ -449,7 +484,7 @@ describe('HermesClient', () => { it('matches concurrent responses by id, even out of order', async () => { FakeWebSocket.responseFactory = controlOnly; - const client = createClient(); + const client = createClient({ trackContexts: true }); const first = client.send( 'Runtime.evaluate', @@ -475,7 +510,7 @@ describe('HermesClient', () => { it('fails with HERMES_TIMEOUT on a per-call timeout and drops the pending entry', async () => { FakeWebSocket.responseFactory = controlOnly; - const client = createClient(); + const client = createClient({ trackContexts: true }); const result = await client.send( 'Runtime.evaluate', @@ -505,7 +540,7 @@ describe('HermesClient', () => { it('fails with HERMES_ABORTED when the signal aborts and drops the pending entry', async () => { FakeWebSocket.responseFactory = controlOnly; const controller = new AbortController(); - const client = createClient(); + const client = createClient({ trackContexts: true }); const pending = client.send( 'Runtime.evaluate', @@ -736,6 +771,7 @@ describe('HermesClient', () => { it('reconnects after an unexpected close, rediscovers the target and emits contextCreated again', async () => { const client = createClient({ + trackContexts: true, reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, }); const disconnected: { reason: string }[] = []; @@ -1195,7 +1231,7 @@ describe('HermesClient', () => { }); it('treats a context after contextDestroyed as a reload when no initial context arrived', async () => { - const client = createClient(); + const client = createClient({ trackContexts: true }); const created: HermesContextCreatedEvent[] = []; const destroyed: HermesContextDestroyedEvent[] = []; client.on('contextCreated', (event) => created.push(event)); @@ -1248,7 +1284,7 @@ describe('HermesClient', () => { } return undefined; }; - const client = createClient(); + const client = createClient({ trackContexts: true }); const created: HermesContextCreatedEvent[] = []; client.on('contextCreated', (event) => created.push(event)); diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 93a261d..20c1f6a 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -17,10 +17,10 @@ * exponential backoff. Every successful (re)connect emits `contextCreated`. * * An app reload does NOT close the socket: the runtime swaps its JavaScript - * context in place. With `trackContexts` on (the default) the client enables + * context in place. With `trackContexts` on (off by default) the client enables * `Runtime` context events, emits `contextDestroyed` when the old context goes * away and `contextCreated` (`reason: 'reload'`) for the new one, so callers can - * re-apply their scripts. + * re-apply their scripts. With it off, a reload is not reported. */ import type { HermesCdpResult } from './hermes-cdp.js'; @@ -110,17 +110,26 @@ export type HermesClientOptions = { /** Automatic reconnect tuning. */ reconnect?: HermesClientReconnectOptions; /** - * Track JavaScript execution contexts and emit `contextCreated` / - * `contextDestroyed` lifecycle events (default `true`). + * Track JavaScript execution contexts and emit `contextDestroyed` and + * `contextCreated` (`reason: 'reload'`) lifecycle events for an app reload + * (default `false`). The `connect` and `reconnect` `contextCreated` events + * fire either way. * * When enabled, the client sends `Runtime.enable` itself after each * connection so Hermes streams `Runtime.executionContextCreated`, * `Runtime.executionContextDestroyed` and `Runtime.executionContextsCleared` * over the socket; an app reload keeps the socket open, so this is the only - * signal that the JavaScript context was replaced. Cost: `Runtime.enable` - * also makes Hermes stream `Runtime.consoleAPICalled` (and other `Runtime` - * events) on the socket; listeners that do not consume them still receive - * them. + * signal that the JavaScript context was replaced. + * + * Cost, while the socket is open: `Runtime.enable` also makes Hermes send a + * `Runtime.consoleAPICalled` event, with object previews, for every + * `console.*` call in the app, which costs JS-thread time. Hermes also keeps + * every object argument of those calls alive in its remote-objects table + * (object group `ConsoleObjectGroup`) until a + * `Runtime.releaseObjectGroup { objectGroup: 'ConsoleObjectGroup' }`, which + * this client never sends. A long session therefore holds every logged + * object; callers that turn this on and log a lot should send that release + * themselves from time to time. Leave it off unless you need reload events. */ trackContexts?: boolean; }; @@ -199,13 +208,15 @@ export type HermesCdpEvent = { * - `reconnect`: a new socket after the old one closed (Metro restart, socket * loss). * - `reload`: a new JS context on the SAME socket (app reload / fast refresh). + * Only reported with `trackContexts` on. */ export type HermesContextCreatedReason = 'connect' | 'reconnect' | 'reload'; /** * Payload of the `contextCreated` lifecycle event: emitted after every - * successful connect, after every reconnect, and for every new JavaScript - * execution context created on an open socket (app reload). + * successful connect, after every reconnect, and, with `trackContexts` on, for + * every new JavaScript execution context created on an open socket (app + * reload). */ export type HermesContextCreatedEvent = { /** The verified target of the connection. */ @@ -221,6 +232,7 @@ export type HermesContextCreatedEvent = { /** * Payload of the `contextDestroyed` lifecycle event, emitted when an open * socket reports that its JavaScript context went away (a reload started). + * Only emitted with `trackContexts` on. */ export type HermesContextDestroyedEvent = { /** Contexts are only destroyed by a reload on the same socket. */ @@ -309,7 +321,8 @@ type PendingCall = { * first call), subscribe with {@link on}, and call {@link close} when done. * * Reloads keep the socket open, so a closed socket only means a lost connection - * (Metro restart). When `trackContexts` is on (the default), the client enables + * (Metro restart). When `trackContexts` is on (it is off by default, see + * {@link HermesClientOptions.trackContexts} for its cost), the client enables * `Runtime` context events and emits a `contextCreated` lifecycle event for * every new JavaScript context on the open socket, so callers can re-apply * their scripts. @@ -419,7 +432,7 @@ export class HermesClient { this.#origin = options.origin; this.#pinnedDeviceId = options.pinnedDeviceId; this.#onPin = options.onPin; - this.#trackContexts = options.trackContexts ?? true; + this.#trackContexts = options.trackContexts ?? false; this.#reconnect = { initialDelayMs: options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS, From 71bc1aa96630f802ca6c6db9d42be1abd75d5e57 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 13:54:30 +0000 Subject: [PATCH 26/33] fix: abandon a HermesClient in-flight connect on close so a reopen starts fresh --- src/hermes/hermes-client.test.ts | 169 +++++++++++++++++++++++++++++++ src/hermes/hermes-client.ts | 58 +++++++++-- 2 files changed, 216 insertions(+), 11 deletions(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 43924b0..0cba45f 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -78,15 +78,26 @@ class FakeWebSocket extends EventTarget { } } + /** + * Closes the socket. Like Node's WebSocket, closing a CONNECTING socket fires + * `error` and then `close` at once. + */ close(): void { if (this.readyState === FakeWebSocket.closed) { return; } + const wasConnecting = this.readyState === FakeWebSocket.connecting; this.readyState = FakeWebSocket.closed; + if (wasConnecting) { + this.dispatchEvent(new Event('error')); + } this.dispatchEvent(new Event('close')); } open(): void { + if (this.readyState !== FakeWebSocket.connecting) { + return; + } this.readyState = FakeWebSocket.openState; this.dispatchEvent(new Event('open')); } @@ -1608,6 +1619,164 @@ describe('HermesClient', () => { expect(fetchMock).toHaveBeenCalledTimes(1); }); + it('does not pin or adopt when close() lands right after the socket opens', async () => { + FakeWebSocket.autoOpen = false; + const onPin = vi.fn(); + const client = createClient({ onPin }); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1)); + const socket = socketAt(0); + // Runs after the client's own open listener, before its connect resumes. + socket.addEventListener('open', () => client.close()); + socket.open(); + + const result = await connecting; + + expect(result).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(socket.sent).toHaveLength(0); + expect(socket.readyState).toBe(FakeWebSocket.closed); + expect(onPin).not.toHaveBeenCalled(); + expect(client.isConnected).toBe(false); + }); + + it('does not report a connect when close() lands during Runtime.enable', async () => { + FakeWebSocket.responseFactory = (request) => + isIdentityProbe(request) ? probeResponse(request) : undefined; + const client = createClient({ trackContexts: true }); + const created = vi.fn(); + client.on('contextCreated', created); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.waitFor(() => + expect(socketAt(0).sent.filter(isRuntimeEnable)).toHaveLength(1), + ); + client.close(); + + const result = await connecting; + + expect(result).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(created).not.toHaveBeenCalled(); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + expect(client.isConnected).toBe(false); + }); + + it('starts a fresh connect on reopen and never pins from the abandoned one (S1)', async () => { + const onPin = vi.fn(); + const client = createClient({ onPin }); + const discoveries: ((value: unknown) => void)[] = []; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + discoveries.push(resolve); + }), + ); + vi.stubGlobal('fetch', fetchMock); + const discovered = { ok: true, json: async () => [target()] }; + + const first = client.connect({ timeoutMs: 1_000 }); + await flush(); + client.close(); + const second = client.connect({ timeoutMs: 1_000 }); + await flush(); + + // The reopen ran its own discovery instead of joining the abandoned one. + expect(fetchMock).toHaveBeenCalledTimes(2); + + discoveries[0]?.(discovered); + expect(await first).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(onPin).not.toHaveBeenCalled(); + expect(FakeWebSocket.instances).toHaveLength(0); + + discoveries[1]?.(discovered); + expect((await second).ok).toBe(true); + expect(onPin).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('reopens with a fresh socket after close() lands while the socket is connecting (S2)', async () => { + FakeWebSocket.autoOpen = false; + const client = createClient(); + + const first = client.connect({ timeoutMs: 1_000 }); + await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1)); + client.close(); + const second = client.connect({ timeoutMs: 1_000 }); + + expect(await first).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + + await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(2)); + socketAt(1).open(); + + expect((await second).ok).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('reports a reopen as connect, not reconnect, when a background attempt was in flight (S3)', async () => { + const client = createClient({ + reconnect: { initialDelayMs: 5, maxDelayMs: 5, maxAttempts: 3 }, + }); + const events: string[] = []; + client.on('reconnected', () => events.push('reconnected')); + client.on('contextCreated', (event) => + events.push(`created:${event.reason}`), + ); + await client.connect({ timeoutMs: 1_000 }); + + const discoveries: ((value: unknown) => void)[] = []; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + discoveries.push(resolve); + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + + client.close(); + const reopened = client.connect({ timeoutMs: 1_000 }); + await flush(); + expect(fetchMock).toHaveBeenCalledTimes(2); + + const discovered = { ok: true, json: async () => [target()] }; + discoveries[0]?.(discovered); + discoveries[1]?.(discovered); + + expect((await reopened).ok).toBe(true); + await delay(50); + + expect(events).toStrictEqual(['created:connect', 'created:connect']); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(client.isConnected).toBe(true); + + client.close(); + }); + it('reports a throwing listener through the listenerError event', async () => { const client = createClient(); const errors: HermesListenerErrorEvent[] = []; diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 20c1f6a..b1e5cd2 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -426,6 +426,13 @@ export class HermesClient { #explicitlyClosed = false; + /** + * Bumped by {@link close}. A connect started under an older epoch was + * abandoned: it must not pin, call `onPin`, adopt its socket, touch the + * connection state or emit events, and a reopen never joins it. + */ + #connectEpoch = 0; + constructor(options: HermesClientOptions) { this.#metroPort = options.metroPort; this.#appId = options.appId; @@ -509,8 +516,11 @@ export class HermesClient { return await waitAtMost(joined, timeoutMs); } + const epoch = this.#connectEpoch; const result = await this.#connectOnce(timeoutMs); - this.#resumeReconnectAfterFailedCall(result); + if (epoch === this.#connectEpoch) { + this.#resumeReconnectAfterFailedCall(result); + } return result; } @@ -659,10 +669,14 @@ export class HermesClient { /** * Stops reconnecting, closes the socket and fails pending calls. * - * Idempotent. A later {@link connect} reopens the client. + * An in-flight connect is abandoned: its callers get a failure, it closes any + * socket it opened, and it never pins, adopts or emits. Idempotent. A later + * {@link connect} reopens the client with a fresh connect. */ close(): void { this.#explicitlyClosed = true; + this.#connectEpoch += 1; + this.#inFlightConnect = undefined; this.#socketLost = false; this.#resetReconnect(); this.#failAllPending( @@ -711,9 +725,10 @@ export class HermesClient { } const reconnected = this.#socketLost; - const promise = this.#doConnect(timeoutMs, reconnected) + const epoch = this.#connectEpoch; + const promise = this.#doConnect(timeoutMs, reconnected, epoch) .then((result) => { - if (result.ok) { + if (result.ok && epoch === this.#connectEpoch) { this.#socketLost = false; this.#resetReconnect(); if (reconnectAttempts !== undefined) { @@ -743,14 +758,21 @@ export class HermesClient { /** * Discovers, opens, probes and adopts a target. Never throws. * + * Every await is followed by an epoch check: a connect abandoned by + * {@link close} closes its own socket and returns without pinning, calling + * `onPin`, adopting the socket or changing the connection status, even when + * the client was reopened in the meantime. + * * @param timeoutMs - The connect timeout. * @param reconnected - True when the previous connection was lost * unexpectedly, used to fail closed on a device pin mismatch. + * @param epoch - The {@link close} epoch this connect started in. * @returns The verified target or a classified failure. */ async #doConnect( timeoutMs: number, reconnected: boolean, + epoch: number, ): Promise { if (typeof WebSocket !== 'function') { this.#status = 'closed'; @@ -763,7 +785,7 @@ export class HermesClient { try { const targets = await fetchDiscoveryTargets(this.#metroPort, timeoutMs); - if (this.#explicitlyClosed) { + if (epoch !== this.#connectEpoch) { return closedDuringConnectResult(); } @@ -818,20 +840,21 @@ export class HermesClient { this.#connectingSocket = connectingSocket; await waitForSocketOpen(connectingSocket, timeoutMs); - if (this.#explicitlyClosed) { + if (epoch !== this.#connectEpoch) { return closedDuringConnectResult(); } // The probe runs once per socket, with id 1; user calls start at 2. const probe = await runIdentityProbe(connectingSocket, timeoutMs, 1); - if (!probe.ok) { - return { ok: false, code: probe.code, message: probe.message }; - } // Checked after every await of the connect path: a close() during the // connect must not pin the device, call `onPin` or adopt the socket. - if (this.#explicitlyClosed) { + // close() closes this socket, which also fails the probe. + if (epoch !== this.#connectEpoch) { return closedDuringConnectResult(); } + if (!probe.ok) { + return { ok: false, code: probe.code, message: probe.message }; + } const targetDeviceId = selection.target.reactNative?.logicalDeviceId; if (!targetDeviceId) { @@ -875,6 +898,11 @@ export class HermesClient { const enabled = await this.send('Runtime.enable', undefined, { timeoutMs, }); + // close() fails the pending Runtime.enable, so this also covers a + // close() while it was in flight. + if (epoch !== this.#connectEpoch) { + return closedDuringConnectResult(); + } if (!enabled.ok) { this.#socketTracksContexts = false; this.#sawContextOnSocket = false; @@ -891,6 +919,10 @@ export class HermesClient { return { ok: true, target }; } catch (error) { + // close() closes the connecting socket, which rejects the open wait. + if (epoch !== this.#connectEpoch) { + return closedDuringConnectResult(); + } const message = error instanceof Error ? error.message : String(error); return { ok: false, @@ -902,7 +934,11 @@ export class HermesClient { this.#connectingSocket = undefined; } if (!adopted) { - this.#status = 'closed'; + // An abandoned connect must not mark a reopened client's connect (or + // its adopted socket) closed. + if (epoch === this.#connectEpoch) { + this.#status = 'closed'; + } if (socket) { closeSocket(socket); } From c94168d9aaee1a12c84ee08718af79627a3fabf2 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 13:56:33 +0000 Subject: [PATCH 27/33] fix: retry a HermesClient pin mismatch on reconnect; only a missing WebSocket is terminal --- src/hermes/hermes-client.test.ts | 92 +++++++++++++++++++++++++------- src/hermes/hermes-client.ts | 53 +++++++++--------- 2 files changed, 102 insertions(+), 43 deletions(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 0cba45f..2cc34cd 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -145,6 +145,22 @@ function target( }; } +/** + * A MetaMask target on another simulator (a different logical device). + * + * @returns The discovery entry. + */ +function otherDeviceTarget(): Record { + return target({ + id: 'other-device', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-2&page=1`, + reactNative: { + logicalDeviceId: 'logical-device-2', + capabilities: { nativePageReloads: true }, + }, + }); +} + function mockDiscovery(targets: unknown[]): void { fetchMock = vi.fn().mockResolvedValue({ ok: true, @@ -1082,7 +1098,7 @@ describe('HermesClient', () => { client.close(); }); - it('emits reconnectFailed once on a pin mismatch and never restarts the loop', async () => { + it('retries a pin mismatch and reports it in reconnectFailed when the loop gives up', async () => { vi.useFakeTimers(); const client = createClient({ pinnedDeviceId: 'logical-device-1', @@ -1095,39 +1111,79 @@ describe('HermesClient', () => { await vi.advanceTimersByTimeAsync(0); expect((await connecting).ok).toBe(true); - mockDiscovery([ - target({ - id: 'other-device', - webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-2&page=1`, - reactNative: { - logicalDeviceId: 'logical-device-2', - capabilities: { nativePageReloads: true }, - }, - }), - ]); - socketAt(0).drop('app reload'); + mockDiscovery([otherDeviceTarget()]); + socketAt(0).drop('metro restart'); await vi.advanceTimersByTimeAsync(1_000); + // Every attempt retried; none opened a socket to the other device. + expect(fetchMock).toHaveBeenCalledTimes(3); expect(failed).toStrictEqual([ { - attempts: 1, + attempts: 3, code: HERMES_DEVICE_PIN_MISMATCH, message: expect.stringContaining('logical-device-2'), }, ]); - expect(fetchMock).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(1); - // A caller hitting the same terminal failure does not restart the loop. + // A caller's pin mismatch restarts the stopped loop like any retryable + // failure. const sending = client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000, }); await vi.advanceTimersByTimeAsync(0); expectError(await sending, HERMES_DEVICE_PIN_MISMATCH); + expect(fetchMock).toHaveBeenCalledTimes(4); - await vi.advanceTimersByTimeAsync(60_000); - expect(fetchMock).toHaveBeenCalledTimes(2); - expect(failed).toHaveLength(1); + await vi.advanceTimersByTimeAsync(1_000); + expect(fetchMock).toHaveBeenCalledTimes(7); + expect(failed).toHaveLength(2); expect(FakeWebSocket.instances).toHaveLength(1); + + client.close(); + }); + + it('reconnects to the pinned device once it returns after a pin mismatch', async () => { + vi.useFakeTimers(); + const onPin = vi.fn(); + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + onPin, + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 6 }, + }); + const failed = vi.fn(); + const created: HermesContextCreatedEvent[] = []; + client.on('reconnectFailed', failed); + client.on('contextCreated', (event) => created.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + // Metro restarts and only the other simulator registers at first. + mockDiscovery([otherDeviceTarget()]); + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(40); + expect(fetchMock.mock.calls.length).toBeGreaterThanOrEqual(2); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(false); + + // The pinned device registers too. + mockDiscovery([otherDeviceTarget(), target({ id: 'device-page-2' })]); + await vi.advanceTimersByTimeAsync(200); + + expect(client.isConnected).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(socketAt(1).url).toBe(SOCKET_URL); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + target: { id: 'device-page-2', logicalDeviceId: 'logical-device-1' }, + }); + expect(failed).not.toHaveBeenCalled(); + expect(onPin).not.toHaveBeenCalled(); + + client.close(); }); it('emits reconnectFailed once when WebSocket becomes unavailable and never restarts the loop', async () => { diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index b1e5cd2..95aa660 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -260,10 +260,10 @@ export type HermesReconnectedEvent = { /** * Payload of the `reconnectFailed` lifecycle event, emitted once each time the - * background reconnect loop gives up: after `maxAttempts` failed attempts, or - * at once on a terminal failure (`HERMES_DEVICE_PIN_MISMATCH`, - * `HERMES_WEBSOCKET_UNAVAILABLE`). The client then stays disconnected until a - * caller connects. + * background reconnect loop gives up: after `maxAttempts` failed attempts (the + * last one may be `HERMES_DEVICE_PIN_MISMATCH` when Metro only lists another + * device), or at once when `HERMES_WEBSOCKET_UNAVAILABLE`, the only terminal + * failure. The client then stays disconnected until a caller connects. */ export type HermesReconnectFailedEvent = { /** How many backoff attempts ran before the loop gave up. */ @@ -330,13 +330,16 @@ type PendingCall = { * An unexpected socket loss starts a background reconnect loop. A caller's * {@link connect} or {@link send} never stops that loop, and a successful one is * reported as `contextCreated` with `reason: 'reconnect'`. When the loop gives - * up (after `maxAttempts`, or at once on a device pin mismatch or a missing - * WebSocket) it emits `reconnectFailed` and the client stays disconnected. + * up (after `maxAttempts`, or at once when no `WebSocket` implementation + * exists) it emits `reconnectFailed` and the client stays disconnected. * While the connection is lost, a failed caller-driven attempt continues a - * running loop, or restarts a stopped one from the first backoff delay; a - * terminal failure (`HERMES_DEVICE_PIN_MISMATCH`, `HERMES_WEBSOCKET_UNAVAILABLE`) - * never restarts it. A client that only listens should handle - * `reconnectFailed`: nothing else retries for it. + * running loop, or restarts a stopped one from the first backoff delay. The + * decision depends only on that caller's own failure: every code restarts the + * loop except `HERMES_WEBSOCKET_UNAVAILABLE`. A device pin mismatch is + * retryable (Metro may list the other device first after a restart); the pin + * filter means a socket is never opened to, or adopted for, the wrong device. + * A client that only listens should handle `reconnectFailed`: nothing else + * retries for it. * * A listener that throws is isolated and reported through the `listenerError` * lifecycle event; it never breaks the socket handler or the other listeners. @@ -493,9 +496,9 @@ export class HermesClient { * * A connect never stops the background reconnect loop. When it fails while * the connection is lost and the loop has stopped (it gave up), the loop - * restarts from the first backoff delay, unless the failure is terminal - * (`HERMES_DEVICE_PIN_MISMATCH`, `HERMES_WEBSOCKET_UNAVAILABLE`). A running - * loop keeps its own schedule. + * restarts from the first backoff delay, unless this connect's own failure is + * `HERMES_WEBSOCKET_UNAVAILABLE`, the only terminal failure. A running loop + * keeps its own schedule. * * @param options - The connect timeout. * @returns The verified target or a classified failure. @@ -985,8 +988,9 @@ export class HermesClient { * whose loop gave up recovers once a caller tries again. * * Does nothing after {@link close}, while the loop is still running, or when - * the failure is terminal (device pin mismatch, WebSocket unavailable): - * retrying cannot fix those. + * the failure is terminal (`HERMES_WEBSOCKET_UNAVAILABLE`): retrying cannot + * fix that. The decision depends only on this failure, not on how the loop + * stopped. * * @param result - The failed caller-driven connect result. */ @@ -1003,7 +1007,8 @@ export class HermesClient { /** * Turns a pinned selection failure into `HERMES_DEVICE_PIN_MISMATCH` during a * reconnect when Metro reports a different device. Inspection only: no socket - * is opened for the wrong device. + * is opened for the wrong device. The code is informative (it names the + * device Metro listed); the reconnect loop retries it like any other failure. * * @param targets - All discovered targets. * @param code - The selection failure code. @@ -1322,9 +1327,9 @@ export class HermesClient { * * Does nothing when the client is already connected: a caller (for example a * `disconnected` listener) may have connected before the timer fired, and a - * second socket must never be opened. Failures schedule the next backoff - * step; a device pin mismatch or a missing WebSocket stops the loop at once - * (and emits `reconnectFailed`) so the wrong device is never used. + * second socket must never be opened. Failures, including a device pin + * mismatch, schedule the next backoff step; a missing WebSocket stops the + * loop at once (and emits `reconnectFailed`). */ async #attemptReconnect(): Promise { if (this.#explicitlyClosed) { @@ -1550,17 +1555,15 @@ async function waitAtMost( /** * Whether a connect failure is terminal for the reconnect loop: retrying cannot - * fix a device pin mismatch (it must never connect to the wrong device) or a - * missing WebSocket implementation. + * fix a missing WebSocket implementation. A device pin mismatch is NOT + * terminal: target selection filters by the pin, so no socket is ever opened to + * the other device, and the pinned device may register with Metro later. * * @param result - The failed connect result. * @returns True when the loop must stop and not restart on its own. */ function isTerminalConnectFailure(result: HermesFailureResult): boolean { - return ( - result.code === HERMES_DEVICE_PIN_MISMATCH || - result.code === HERMES_WEBSOCKET_UNAVAILABLE - ); + return result.code === HERMES_WEBSOCKET_UNAVAILABLE; } /** From 8ee134985bf64c6627b9331da6b75142836f5e39 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 13:58:21 +0000 Subject: [PATCH 28/33] fix: do not emit HermesClient disconnected for a socket lost before its connect completed --- src/hermes/hermes-client.test.ts | 77 ++++++++++++++++++++++++++++++++ src/hermes/hermes-client.ts | 25 ++++++++++- 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 2cc34cd..92b9b94 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -1833,6 +1833,83 @@ describe('HermesClient', () => { client.close(); }); + it('fails a first connect whose socket is lost during Runtime.enable, without disconnected (S4)', async () => { + vi.useFakeTimers(); + FakeWebSocket.responseFactory = (request) => + isIdentityProbe(request) ? probeResponse(request) : undefined; + const client = createClient({ + trackContexts: true, + reconnect: { initialDelayMs: 5, maxDelayMs: 5, maxAttempts: 2 }, + }); + const events: string[] = []; + client.on('contextCreated', (event) => + events.push(`created:${event.reason}`), + ); + client.on('disconnected', () => events.push('disconnected')); + client.on('reconnectFailed', () => events.push('reconnectFailed')); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect(socketAt(0).sent.filter(isRuntimeEnable)).toHaveLength(1); + socketAt(0).drop('gone'); + + expect(await connecting).toStrictEqual({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: + 'Hermes CDP connection failed: the socket closed while enabling runtime events', + }); + + // Listeners never saw this connection, so they hear nothing about it, and + // no reconnect loop runs for a connection that never completed. + await vi.advanceTimersByTimeAsync(1_000); + expect(events).toStrictEqual([]); + expect(client.isConnected).toBe(false); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('keeps reconnecting when a reconnect socket is lost during Runtime.enable', async () => { + vi.useFakeTimers(); + const client = createClient({ + trackContexts: true, + reconnect: { initialDelayMs: 10, maxDelayMs: 10, maxAttempts: 3 }, + }); + const events: string[] = []; + client.on('contextCreated', (event) => + events.push(`created:${event.reason}`), + ); + client.on('disconnected', () => events.push('disconnected')); + client.on('reconnected', () => events.push('reconnected')); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + // The first reconnect socket never answers Runtime.enable and drops. + FakeWebSocket.responseFactory = (request) => + isIdentityProbe(request) ? probeResponse(request) : undefined; + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(10); + expect(FakeWebSocket.instances).toHaveLength(2); + + FakeWebSocket.responseFactory = defaultResponseFactory; + socketAt(1).drop('gone again'); + + await vi.advanceTimersByTimeAsync(10); + + expect(events).toStrictEqual([ + 'created:connect', + 'disconnected', + 'reconnected', + 'created:reconnect', + ]); + expect(FakeWebSocket.instances).toHaveLength(3); + expect(client.isConnected).toBe(true); + + client.close(); + }); + it('reports a throwing listener through the listenerError event', async () => { const client = createClient(); const errors: HermesListenerErrorEvent[] = []; diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 95aa660..89d5501 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -399,6 +399,14 @@ export class HermesClient { */ #contextDestroyedForReload = false; + /** + * Whether the adopted socket was reported to listeners with `contextCreated`. + * A socket is adopted before `Runtime.enable` runs; if it is lost before the + * connect completes, the connect fails and no `disconnected` is emitted for a + * connection listeners never saw. + */ + #socketReported = false; + /** * Whether the last connection was lost unexpectedly (not through * {@link close}). Set on an unexpected loss, cleared on a successful connect @@ -733,6 +741,7 @@ export class HermesClient { .then((result) => { if (result.ok && epoch === this.#connectEpoch) { this.#socketLost = false; + this.#socketReported = true; this.#resetReconnect(); if (reconnectAttempts !== undefined) { this.#emit('reconnected', { @@ -1056,6 +1065,7 @@ export class HermesClient { closeSocket(previous); } this.#nextId = 2; + this.#socketReported = false; this.#socketTracksContexts = false; this.#sawContextOnSocket = false; this.#contextDestroyedForReload = false; @@ -1240,6 +1250,12 @@ export class HermesClient { * {@link send}, and the socket it opens must already be the one the next * scheduled attempt finds. * + * A socket lost before its connect completed (during `Runtime.enable`) was + * never reported: it is released and its pending calls fail, which fails the + * connect, but the connection state is left as it was and no `disconnected` + * is emitted. The failed connect then follows the normal rules: a first + * connect simply fails, and a reconnect continues or restarts the loop. + * * @param reason - Why the socket was lost, used for the `disconnected` event. * @param pendingMessage - Overrides the pending-call failure message. */ @@ -1249,11 +1265,15 @@ export class HermesClient { return; } + const reported = this.#socketReported; this.#detachSocket(); this.#socket = undefined; + this.#socketReported = false; this.#target = undefined; this.#status = 'closed'; - this.#socketLost = true; + if (reported) { + this.#socketLost = true; + } closeSocket(socket); this.#failAllPending( @@ -1261,6 +1281,9 @@ export class HermesClient { pendingMessage ?? `Hermes CDP connection closed: ${reason}`, ); + if (!reported) { + return; + } if (!this.#explicitlyClosed) { this.#startReconnect(); } From f27edf74ab702be32937d29b3634530fde0b1b00 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 13:59:02 +0000 Subject: [PATCH 29/33] fix: treat an empty HermesClient pinnedDeviceId as no pin, as the one-shot path did --- src/hermes/hermes-client.test.ts | 13 +++++++++++++ src/hermes/hermes-client.ts | 8 ++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index 92b9b94..f5321f4 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -730,6 +730,19 @@ describe('HermesClient', () => { expect(onPin).not.toHaveBeenCalled(); }); + it('treats an empty pinnedDeviceId as no pin and pins on first connect', async () => { + const onPin = vi.fn(); + const client = createClient({ pinnedDeviceId: '', onPin }); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result.ok).toBe(true); + expect(onPin).toHaveBeenCalledTimes(1); + expect(onPin).toHaveBeenCalledWith('logical-device-1'); + }); + it('fails with HERMES_BLOCKED_METHOD without discovering or connecting', async () => { const client = createClient(); diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 89d5501..3729131 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -100,7 +100,10 @@ export type HermesClientOptions = { appId: string; /** Override the HTTP(S) Origin for Metro's debugger WebSocket handshake. */ origin?: string; - /** The pinned `logicalDeviceId` for this session, if one has been set. */ + /** + * The pinned `logicalDeviceId` for this session, if one has been set. An + * empty string means no pin. + */ pinnedDeviceId?: string; /** * Callback invoked with the resolved `logicalDeviceId` on the FIRST @@ -448,7 +451,8 @@ export class HermesClient { this.#metroPort = options.metroPort; this.#appId = options.appId; this.#origin = options.origin; - this.#pinnedDeviceId = options.pinnedDeviceId; + // An empty pin means no pin, as in the one-shot path's `!pinnedDeviceId`. + this.#pinnedDeviceId = options.pinnedDeviceId || undefined; this.#onPin = options.onPin; this.#trackContexts = options.trackContexts ?? false; this.#reconnect = { From de910d0659c376cac198d31d181fe7be0d2f04f4 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 14:01:56 +0000 Subject: [PATCH 30/33] refactor: remove unreachable guards from HermesClient #attemptReconnect --- src/hermes/hermes-client.ts | 94 ++++++++++++++----------------------- 1 file changed, 35 insertions(+), 59 deletions(-) diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 3729131..22bebca 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -1350,72 +1350,48 @@ export class HermesClient { } /** - * Runs one reconnect attempt. + * Runs one reconnect attempt. Called only from the backoff timer, which + * every successful connect and every {@link close} clear, so the client is + * open and disconnected when it starts. * - * Does nothing when the client is already connected: a caller (for example a - * `disconnected` listener) may have connected before the timer fired, and a - * second socket must never be opened. Failures, including a device pin - * mismatch, schedule the next backoff step; a missing WebSocket stops the - * loop at once (and emits `reconnectFailed`). + * A caller (for example a `disconnected` listener) may have started a + * connect before the timer fired; the attempt waits for it, and a second + * socket is never opened. Failures, including a device pin mismatch, + * schedule the next backoff step; a missing WebSocket stops the loop at once + * (and emits `reconnectFailed`). Never rejects. */ async #attemptReconnect(): Promise { - if (this.#explicitlyClosed) { - return; - } - if (this.isConnected) { - this.#resetReconnect(); - return; - } const generation = this.#reconnectGeneration; - try { - // A caller's connect is already in flight, with the caller's (possibly - // shorter) timeouts. Wait for it instead of opening a second socket; if - // it fails, this attempt then runs its own connect with the full - // `connectTimeoutMs`. - let callerConnect = this.#inFlightConnect; - while (callerConnect) { - await callerConnect; - if ( - this.#explicitlyClosed || - generation !== this.#reconnectGeneration - ) { - return; - } - if (this.isConnected) { - this.#resetReconnect(); - return; - } - callerConnect = this.#inFlightConnect; - } - const result = await this.#connectOnce( - this.#reconnect.connectTimeoutMs, - this.#reconnectAttempt, - ); - // A close(), a success or a restart while this attempt was in flight - // already decided what happens next. - if (this.#explicitlyClosed || generation !== this.#reconnectGeneration) { - return; - } - if (result.ok || this.isConnected) { - this.#resetReconnect(); - return; - } - if (isTerminalConnectFailure(result)) { - this.#stopReconnect(result); + // A caller's connect is already in flight, with the caller's (possibly + // shorter) timeouts. Wait for it instead of opening a second socket; if it + // fails, this attempt then runs its own connect with the full + // `connectTimeoutMs`. Connect promises never reject. + let callerConnect = this.#inFlightConnect; + while (callerConnect) { + await callerConnect; + // Every successful connect and every close() bumps the generation (via + // #resetReconnect), so an unchanged generation means the client is still + // disconnected and this loop still owns the retry. + if (generation !== this.#reconnectGeneration) { return; } - this.#scheduleReconnect(result); - } catch (error) { - if (this.#explicitlyClosed || generation !== this.#reconnectGeneration) { - return; - } - const message = error instanceof Error ? error.message : String(error); - this.#scheduleReconnect({ - ok: false, - code: HERMES_CONNECTION_FAILED, - message: `Hermes CDP connection failed: ${message}`, - }); + callerConnect = this.#inFlightConnect; + } + const result = await this.#connectOnce( + this.#reconnect.connectTimeoutMs, + this.#reconnectAttempt, + ); + // Same rule: a success (`result.ok`), a close() or a restart while this + // attempt was in flight already decided what happens next. `result.ok` + // only narrows the type: a success always changed the generation. + if (generation !== this.#reconnectGeneration || result.ok) { + return; + } + if (isTerminalConnectFailure(result)) { + this.#stopReconnect(result); + return; } + this.#scheduleReconnect(result); } /** From 368506cbf5ce1f6736e60013946177e5ea32d5c5 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 14:01:56 +0000 Subject: [PATCH 31/33] docs: list HermesClient timeout steps, socket lifetime and per-socket domain state --- src/hermes/hermes-client.ts | 60 +++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 22bebca..7e77fd6 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -82,10 +82,15 @@ export type HermesClientReconnectOptions = { maxAttempts?: number; /** * Connect timeout for automatic reconnect attempts, in milliseconds - * (default 10 s). Per-call `timeoutMs` values never shorten a reconnect - * attempt: an attempt that finds a caller's connect in flight waits for it - * (so no second socket opens) and, if it fails, then runs its own connect - * with this full timeout. + * (default 10 s). Like a caller's `timeoutMs`, it applies to each connect + * step on its own: the `/json` and the fallback `/json/list` discovery, the + * WebSocket open, the identity probe and, with `trackContexts` on, + * `Runtime.enable`. One attempt can therefore take up to about 4 × this + * value (5 × with `trackContexts` on). + * + * Per-call `timeoutMs` values never shorten a reconnect attempt: an attempt + * that finds a caller's connect in flight waits for it (so no second socket + * opens) and, if it fails, then runs its own connect with this full timeout. */ connectTimeoutMs?: number; }; @@ -141,7 +146,12 @@ export type HermesClientOptions = { * Options for {@link HermesClient.connect}. */ export type HermesConnectOptions = { - /** Timeout in milliseconds for discovery, the socket open and the probe. */ + /** + * Timeout in milliseconds for each connect step on its own: the `/json` and + * the fallback `/json/list` discovery, the socket open, the probe and, with + * `trackContexts` on, `Runtime.enable` (up to about 4 × `timeoutMs` in all, + * 5 × with tracking). + */ timeoutMs: number; }; @@ -174,18 +184,26 @@ export type HermesConnectResult = */ export type HermesSendOptions = { /** - * Per-phase timeout in milliseconds. It bounds each phase of the call on its + * Per-step timeout in milliseconds. It bounds each step of the call on its * own, not their sum: * - Connect, when the client is not connected. If this call starts the - * connect, each connect step (discovery, socket open, identity probe) gets - * `timeoutMs`, as in `runHermesCdp`. If a connect is already in - * flight (another call's, or a background reconnect attempt), this call - * waits for it at most `timeoutMs`, then fails with `HERMES_TIMEOUT`; the - * shared connect keeps running for the others. + * connect, each of these steps gets its own `timeoutMs`, as in + * `runHermesCdp`: + * 1. discovery of `/json`, then 2. of `/json/list` (only if `/json` + * failed); + * 3. the WebSocket open; + * 4. the identity probe; + * 5. `Runtime.enable`, only with `trackContexts` on. + * + * If a connect is already in flight (another call's, or a background + * reconnect attempt), this call instead waits for it at most `timeoutMs`, + * then fails with `HERMES_TIMEOUT`; the shared connect keeps running for + * the others. * - Response: once connected, the CDP response gets `timeoutMs`. * - * So a call that has to connect can take longer than `timeoutMs`. To bound - * the total time, pass `signal: AbortSignal.timeout(n)`. + * So a cold `send` can take up to about 5 × `timeoutMs` (6 × with + * `trackContexts` on); a connected one, `timeoutMs`. To bound the total + * time, pass `signal: AbortSignal.timeout(n)`. */ timeoutMs: number; /** @@ -321,7 +339,14 @@ type PendingCall = { * Persistent, verified Hermes CDP connection. * * Create one per session, call {@link send} for CDP methods (it connects on the - * first call), subscribe with {@link on}, and call {@link close} when done. + * first call), subscribe with {@link on}, and call {@link close} when done: an + * open socket keeps the Node process alive. + * + * One socket serves every call, so CDP domain state lasts across calls until + * the socket is lost or closed: an enabled domain (`Debugger.enable`), + * breakpoints, a paused debugger, object groups. `runHermesCdp` opened and + * closed a socket per call, which reset that state each time; callers that + * set such state should undo it (or {@link close} the client) when done. * * Reloads keep the socket open, so a closed socket only means a lost connection * (Metro restart). When `trackContexts` is on (it is off by default, see @@ -684,6 +709,9 @@ export class HermesClient { /** * Stops reconnecting, closes the socket and fails pending calls. * + * Call it when done: the client's timers are unref'd, but an open WebSocket + * keeps the Node process alive. + * * An in-flight connect is abandoned: its callers get a failure, it closes any * socket it opened, and it never pins, adopts or emits. Idempotent. A later * {@link connect} reopens the client with a fresh connect. @@ -1629,7 +1657,9 @@ function readCloseReason(event: Event): string { } /** - * Unrefs a Node timer so an idle client never keeps the process alive. + * Unrefs a Node timer so the client's own timers (call timeouts, backoff) never + * keep the process alive. An open WebSocket still does: a connected client + * keeps Node running until {@link HermesClient.close} is called. * * @param timer - The timer handle (a `NodeJS.Timeout` in Node). */ From 07c3d9aea38f61922ba435f35b9e7ddef5d41fe7 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 14:04:01 +0000 Subject: [PATCH 32/33] refactor: remove the unreachable same-device branch from HermesClient pin-mismatch detection --- src/hermes/hermes-client.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts index 7e77fd6..c8b2d40 100644 --- a/src/hermes/hermes-client.ts +++ b/src/hermes/hermes-client.ts @@ -1070,11 +1070,10 @@ export class HermesClient { if (!unpinned.ok) { return undefined; } + // Never the pinned device: the pinned selection is this selection filtered + // by the pin, and it found nothing. const deviceId = unpinned.target.reactNative?.logicalDeviceId ?? ''; - if (deviceId === pinnedDeviceId) { - return undefined; - } return { ok: false, code: HERMES_DEVICE_PIN_MISMATCH, From 0aa6e766f651702b0f8ca0cb92c9d7541552a8e4 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Thu, 19 Nov 2026 14:04:01 +0000 Subject: [PATCH 33/33] test: cover HermesClient close, send and pin-mismatch edge cases on fake timers --- src/hermes/hermes-client.test.ts | 177 +++++++++++++++++++++++++------ 1 file changed, 142 insertions(+), 35 deletions(-) diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts index f5321f4..4e48986 100644 --- a/src/hermes/hermes-client.test.ts +++ b/src/hermes/hermes-client.test.ts @@ -7,6 +7,7 @@ import { HERMES_CDP_FAILED, HERMES_CONNECTION_FAILED, HERMES_DEVICE_PIN_MISMATCH, + HERMES_TARGET_NOT_FOUND, HERMES_TIMEOUT, HERMES_WEBSOCKET_UNAVAILABLE, IDENTITY_PROBE_EXPR, @@ -250,16 +251,6 @@ async function flush(): Promise { await new Promise((resolve) => setTimeout(resolve, 0)); } -/** - * Waits for a fixed duration. - * - * @param ms - Milliseconds to wait. - * @returns A promise resolved after the delay. - */ -async function delay(ms: number): Promise { - await new Promise((resolve) => setTimeout(resolve, ms)); -} - describe('HermesClient', () => { beforeEach(() => { FakeWebSocket.instances = []; @@ -802,6 +793,101 @@ describe('HermesClient', () => { expect(client.isConnected).toBe(false); }); + it('fails a send after close() without connecting until connect() reopens', async () => { + const client = createClient(); + client.close(); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result).toStrictEqual({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: 'HermesClient is closed', + }); + expect(fetchMock).not.toHaveBeenCalled(); + + expect((await client.connect({ timeoutMs: 1_000 })).ok).toBe(true); + const reopened = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expect(reopened.ok).toBe(true); + + client.close(); + }); + + it('fails a call with HERMES_CONNECTION_FAILED when socket.send throws', async () => { + const client = createClient(); + await client.connect({ timeoutMs: 1_000 }); + const socket = socketAt(0); + vi.spyOn(socket, 'send').mockImplementation(() => { + throw new Error('socket buffer full'); + }); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result).toStrictEqual({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: 'Hermes CDP connection failed: socket buffer full', + }); + // The pending entry was removed: the connection stays usable. + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('keeps the selection failure on reconnect when the unpinned targets are ambiguous', async () => { + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + reconnect: { maxAttempts: 0 }, + }); + await client.connect({ timeoutMs: 1_000 }); + + mockDiscovery([ + otherDeviceTarget(), + target({ + id: 'third-device', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-3&page=1`, + reactNative: { logicalDeviceId: 'logical-device-3' }, + }), + ]); + socketAt(0).drop('metro restart'); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result).toMatchObject({ + ok: false, + code: HERMES_TARGET_NOT_FOUND, + }); + expect(FakeWebSocket.instances).toHaveLength(1); + }); + + it('keeps the selection failure on reconnect when no target is usable', async () => { + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + reconnect: { maxAttempts: 0 }, + }); + await client.connect({ timeoutMs: 1_000 }); + + // The pinned device is listed, but without a debugger URL: neither the + // pinned nor the unpinned selection finds a usable target. + const { webSocketDebuggerUrl: _url, ...withoutUrl } = target(); + mockDiscovery([withoutUrl]); + socketAt(0).drop('metro restart'); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result).toMatchObject({ + ok: false, + code: HERMES_TARGET_NOT_FOUND, + }); + expect(FakeWebSocket.instances).toHaveLength(1); + }); + it('reports the configured port and app id', () => { const client = createClient({ appId: 'io.metamask', metroPort: 9000 }); @@ -882,6 +968,7 @@ describe('HermesClient', () => { }); it('retries with backoff and gives up after maxAttempts', async () => { + vi.useFakeTimers(); const client = createClient({ reconnect: { initialDelayMs: 5, maxDelayMs: 10, maxAttempts: 2 }, }); @@ -891,15 +978,23 @@ describe('HermesClient', () => { vi.stubGlobal('fetch', fetchMock); socketAt(0).drop('app reload'); - await delay(60); + // Backoff is 5 ms, then 10 ms: both attempts have run by 15 ms. + await vi.advanceTimersByTimeAsync(4); + expect(fetchMock).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(fetchMock).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(10); // Two attempts, then the client gives up (no socket was ever adopted). expect(fetchMock).toHaveBeenCalledTimes(4); + await vi.advanceTimersByTimeAsync(60_000); + expect(fetchMock).toHaveBeenCalledTimes(4); expect(FakeWebSocket.instances).toHaveLength(1); expect(client.isConnected).toBe(false); }); it('does not reconnect to a different device after a reload (pin mismatch)', async () => { + vi.useFakeTimers(); const client = createClient({ pinnedDeviceId: 'logical-device-1', reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, @@ -924,15 +1019,18 @@ describe('HermesClient', () => { ]); socketAt(0).drop('app reload'); - await delay(80); + await vi.advanceTimersByTimeAsync(1_000); expect(FakeWebSocket.instances).toHaveLength(1); expect(client.isConnected).toBe(false); expect(reconnected).not.toHaveBeenCalled(); expect(created).toHaveBeenCalledTimes(1); + // Three attempts (10, 20, 40 ms), none of which opened a socket. + expect(fetchMock).toHaveBeenCalledTimes(3); }); it('close() stops a scheduled reconnect', async () => { + vi.useFakeTimers(); const client = createClient({ reconnect: { initialDelayMs: 20, maxDelayMs: 40, maxAttempts: 3 }, }); @@ -941,13 +1039,14 @@ describe('HermesClient', () => { socketAt(0).drop('app reload'); client.close(); - await delay(80); + await vi.advanceTimersByTimeAsync(60_000); expect(FakeWebSocket.instances).toHaveLength(1); expect(fetchMock).toHaveBeenCalledTimes(1); }); it('connects again on the next send after the reconnect loop gave up', async () => { + vi.useFakeTimers(); const client = createClient({ reconnect: { initialDelayMs: 5, maxDelayMs: 10, maxAttempts: 1 }, }); @@ -956,7 +1055,8 @@ describe('HermesClient', () => { fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); vi.stubGlobal('fetch', fetchMock); socketAt(0).drop('app reload'); - await delay(40); + await vi.advanceTimersByTimeAsync(5); + expect(fetchMock).toHaveBeenCalledTimes(2); mockDiscovery([target({ id: 'device-page-3' })]); const result = await client.send('Runtime.evaluate', undefined, { @@ -969,6 +1069,7 @@ describe('HermesClient', () => { }); it('keeps reconnecting when a send fails during the reconnect wait', async () => { + vi.useFakeTimers(); const client = createClient({ reconnect: { initialDelayMs: 40, maxDelayMs: 80, maxAttempts: 5 }, }); @@ -992,9 +1093,12 @@ describe('HermesClient', () => { // Metro comes back: the background loop must still be running. mockDiscovery([target({ id: 'device-page-2' })]); - await vi.waitFor(() => expect(client.isConnected).toBe(true), { - timeout: 2_000, - }); + // The failed send restarted nothing: the loop's first attempt still + // fires at 40 ms. + await vi.advanceTimersByTimeAsync(39); + expect(client.isConnected).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(client.isConnected).toBe(true); expect(created).toHaveLength(2); expect(created[1]).toMatchObject({ @@ -1234,6 +1338,7 @@ describe('HermesClient', () => { }); it('does not emit reconnectFailed when auto-reconnect is disabled', async () => { + vi.useFakeTimers(); const client = createClient({ reconnect: { maxAttempts: 0 } }); const failed = vi.fn(); client.on('reconnectFailed', failed); @@ -1246,7 +1351,7 @@ describe('HermesClient', () => { const result = await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000, }); - await delay(20); + await vi.advanceTimersByTimeAsync(60_000); expectError(result, HERMES_CONNECTION_FAILED); expect(failed).not.toHaveBeenCalled(); @@ -1276,6 +1381,7 @@ describe('HermesClient', () => { }); it('opens one socket when a disconnected listener sends and the reconnect timer fires', async () => { + vi.useFakeTimers(); const client = createClient({ reconnect: { initialDelayMs: 40, maxDelayMs: 40, maxAttempts: 3 }, }); @@ -1290,12 +1396,11 @@ describe('HermesClient', () => { await client.connect({ timeoutMs: 1_000 }); socketAt(0).drop('metro restart'); - await vi.waitFor(() => expect(client.isConnected).toBe(true), { - timeout: 1_000, - }); - // Let the scheduled attempt fire: it must find the caller's socket and open - // nothing. - await delay(100); + await vi.advanceTimersByTimeAsync(0); + expect(client.isConnected).toBe(true); + // Let the scheduled attempt fire at 40 ms: it must find the caller's + // socket and open nothing. + await vi.advanceTimersByTimeAsync(100); expect(created).toHaveLength(2); expect(created[1]).toMatchObject({ @@ -1398,6 +1503,7 @@ describe('HermesClient', () => { }); it('uses reconnect.connectTimeoutMs for reconnect attempts, not the last caller timeout', async () => { + vi.useFakeTimers(); const client = createClient({ reconnect: { initialDelayMs: 10, @@ -1423,12 +1529,10 @@ describe('HermesClient', () => { vi.stubGlobal('fetch', fetchMock); socketAt(0).drop('metro restart'); - await vi.waitFor(() => expect(abortedAfter.length).toBeGreaterThan(0), { - timeout: 1_000, - }); - - // A reconnect discovery is bounded by 30 ms, far below the caller's 5 s. - expect(abortedAfter[0]).toBeLessThan(1_000); + // The attempt fires at 10 ms; its discovery is aborted 30 ms later, far + // below the caller's 5 s. + await vi.advanceTimersByTimeAsync(40); + expect(abortedAfter).toStrictEqual([40]); expect(client.isConnected).toBe(false); client.close(); @@ -1631,6 +1735,7 @@ describe('HermesClient', () => { }); it('does not pin, adopt or reconnect when close() lands during discovery', async () => { + vi.useFakeTimers(); const onPin = vi.fn(); const client = createClient({ onPin }); let resolveDiscovery!: (value: unknown) => void; @@ -1643,7 +1748,7 @@ describe('HermesClient', () => { vi.stubGlobal('fetch', fetchMock); const connecting = client.connect({ timeoutMs: 1_000 }); - await flush(); + await vi.advanceTimersByTimeAsync(0); client.close(); resolveDiscovery({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); @@ -1654,7 +1759,7 @@ describe('HermesClient', () => { expect(FakeWebSocket.instances).toHaveLength(0); expect(client.isConnected).toBe(false); - await delay(20); + await vi.advanceTimersByTimeAsync(60_000); expect(FakeWebSocket.instances).toHaveLength(0); expect(fetchMock).toHaveBeenCalledTimes(1); }); @@ -1805,6 +1910,7 @@ describe('HermesClient', () => { }); it('reports a reopen as connect, not reconnect, when a background attempt was in flight (S3)', async () => { + vi.useFakeTimers(); const client = createClient({ reconnect: { initialDelayMs: 5, maxDelayMs: 5, maxAttempts: 3 }, }); @@ -1824,11 +1930,12 @@ describe('HermesClient', () => { ); vi.stubGlobal('fetch', fetchMock); socketAt(0).drop('metro restart'); - await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + await vi.advanceTimersByTimeAsync(5); + expect(fetchMock).toHaveBeenCalledTimes(1); client.close(); const reopened = client.connect({ timeoutMs: 1_000 }); - await flush(); + await vi.advanceTimersByTimeAsync(0); expect(fetchMock).toHaveBeenCalledTimes(2); const discovered = { ok: true, json: async () => [target()] }; @@ -1836,7 +1943,7 @@ describe('HermesClient', () => { discoveries[1]?.(discovered); expect((await reopened).ok).toBe(true); - await delay(50); + await vi.advanceTimersByTimeAsync(60_000); expect(events).toStrictEqual(['created:connect', 'created:connect']); expect(FakeWebSocket.instances).toHaveLength(2);