/** * The agent-device surface: one simulator or emulator session, driven through * agent-device's typed client, exposed to the runner as the contract's * observe/locate/perform members. It owns the id space (one fresh generation * per observation), the attempt state (artifact directory, screenshot * counter), and every translation between the contract's vocabulary and * agent-device's commands. Its device and session come from the target's * `DevicePool`, by worker slot. The runner owns everything else. * * Every observation is reported under one root of a stable id (`ROOT_ID`) * wrapping the device's top-level elements; a `swipe` performed on that root * scrolls the whole screen. */ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { formatPinnedRef, type CaptureSnapshotResult } from 'agent-device'; import { EngineError, KEY_NAMES, parseKey, raceAbort, rejectUnknownKeys, stopProviderRecording, withinCleanupBudget, type EngineAttemptContext, type EngineCleanupContext, type EngineDoctorCheck, type EngineDoctorInfo, type EngineInitInfo, type EngineObserveOptions, type EngineSnapshot, type EngineAppInfo, type LaunchArguments, type ResolvedLaunchArguments, type LocatorAction, type LocatorExpression, type NodeRef, type ObservationPixels, type OperationContext, type PointerAction, type ProviderRecording, type ScrollEdge, type VideoSegment, type SemanticNode, type ViewportIntersection, type ViewportPoint, type ViewportSize, ConfigurationError, readPngSize, TestError, } from '@e2e-dev/core/engine'; import { isAppNotRunning, isSnapshotPresentationFailure, isUnreadableCapture, ORIGIN_UNKNOWN_BOUNDS, ORIGIN_WARNING, refusedSwipePath, runCommand, staleOr } from './errors.ts'; import { pointerInteraction, DEFAULT_LONG_PRESS_MS, MAX_TAP_COUNT } from './actions.ts'; import { resolveExpression } from './locate.ts'; import { launchArgumentList, launchArgumentsForOpen } from './launch-arguments.ts'; import { isWithin, keyboardElementsTop, keyboardBand, mayTakeText, projectSnapshot, ROOT_ID, screenRoot, screenTitle, withEmptyState, type ProjectedNode, type ProjectedSnapshot, } from './nodes.ts'; import { keyboardDragStart, keyboardShownIn, type KeyboardUnknown } from './keyboard.ts'; import { DEVICE_PERMISSIONS, type AgentDeviceClient, type ClientFactory, type DevicePermission, type LaunchPermissions, type MobileOptions, type MobilePlatform, type PermissionState } from './options.ts'; import { maskPng } from './png.ts'; import { above, clipTo, dragToEdge, EDGE_DIRECTION, regionSignature } from './scroll-to.ts'; import { mobileDoctor } from './doctor.ts'; import { deviceLabel, deviceSelection, pinnedApp, type DeviceSelection, type SlotBinding } from './bindings.ts'; import { assertAppId } from './links.ts'; import { bootRequest, DevicePool } from './pool.ts'; import { recordLease, travelledLease, type DeviceLease, type RecordingDeviceProvider } from './provider.ts'; import { installedIdentity, invalidState, notActionable, logicalScreenSize, sanitizeFilename, screenLocation, type RawScreenshotResult, swipeWithin, unsupported, type Rect, InputBudget, type InstallIdentity, } from './support.ts'; /** Hinge poses `device.fold` accepts: `closed` lights the outer display, `half-open` and `open` the inner one. */ export type FoldPose = 'closed' | 'half-open' | 'open'; /** How `installApp` puts a build on the device. */ export interface InstallAppOptions { /** * Bundle id or package of the build. `reinstall` needs one: agent-device * removes that app before installing. Defaults to the pinned app. */ readonly app?: string; /** Remove the installed app first so the build starts with no data. */ readonly reinstall?: boolean; } /** What an install put on the device, as agent-device identified it. */ export interface InstalledApp { /** The bundle id or package to open the app by. */ readonly app: string; readonly bundleId?: string; } /** Why nothing is pinned with `appPath` alone: the install is the suite's. */ const UNINSTALLED_BUILD = "the build the target's `app.appPath` names installed first with `device.installApp()`"; /** How `device.openApp` launches an app. */ export interface OpenAppOptions { /** Terminate the app first, so it starts fresh; without it a running app is brought forward as it is. */ readonly relaunch?: boolean; /** * Arguments this launch hands the app, a list or an object like * `app.launchArguments`: its process arguments on iOS, `am start` * arguments on Android. Replaces the target's `app.launchArguments` for a * relaunch of the pinned app. */ readonly launchArguments?: LaunchArguments; /** * Permissions the app holds before this launch, each granted, denied, or * reset, or `'all'` to grant every one the platform can. Replaces the * target's `app.permissions` for a relaunch of the pinned app. */ readonly permissions?: LaunchPermissions; } /** * The snapshot fields this engine reads off agent-device's response. `keyboard` * is the band the capture's producer measured: `visible` with its frame, * `absent`, or that it could not look. `refsGeneration` is the capture its * refs were issued from. `warnings` is read for `ORIGIN_WARNING` only. */ type RawSnapshot = Partial>; /** * How far the dismissing drag travels, as a share of the viewport: short * enough that a list under the finger barely moves, long enough for a scroll * view to read it as a drag and let go of the keyboard. The same ratio * Maestro's `hideKeyboard` uses. */ const KEYBOARD_DRAG_RATIO = 0.03; /** What a test does instead when the engine cannot send the keyboard away. */ const KEYBOARD_ALTERNATIVES = 'Tap the app\'s own Done or close control, or press Enter on the field when submitting is what you want.'; /** * Whether one line of agent-device's app list names `app`. A line reads * `Name (id)`, the bundle id or package in the parentheses, or carries the * id alone; either the id or the whole name matches. */ function listsApp(entry: string, app: string): boolean { if (entry === app) return true; const named = /^(.*) \(([^()]+)\)$/.exec(entry); return named !== null && (named[2] === app || named[1] === app); } /** * The top edge of the soft keyboard: the higher of the band the capture's * producer measured and the highest keyboard element drawn on screen (a key, * the keyboard, or the suggestion strip above it, which a frame derived from * the keys leaves out). Undefined when the capture says the keyboard is up * but bounds it nowhere, as a visibility probe alone does: the keyboard * could reach anywhere, so no point is known to be above it. */ function keyboardTop(raw: RawSnapshot, viewport: ViewportSize): number | undefined { const elements = keyboardElementsTop(raw.nodes ?? [], raw.viewport ?? viewport); const frame = raw.keyboard?.kind === 'visible' || raw.keyboard?.kind === 'derived' ? raw.keyboard.frame.y : undefined; const tops = [frame, elements].filter((top) => top !== undefined); return tops.length === 0 ? undefined : Math.min(viewport.height, ...tops); } /** * One projection and the keyboard state captured with it, kept together * across an action. `originUnknown` is set when the capture could not place * its window on the screen, so its rects may be window-local. */ type ProjectedScreen = ProjectedSnapshot & { readonly keyboardVisible: boolean; readonly originUnknown: boolean }; /** * Whether the capture's producer measured the soft keyboard on screen: * undefined when it did not look or could not. */ function measuredKeyboard(raw: RawSnapshot): boolean | undefined { if (raw.keyboard?.kind === 'visible') return true; if (raw.keyboard?.kind === 'absent') return false; return undefined; } /** * Whether a capture shows the soft keyboard, by {@link keyboardShownIn}: a * capture that cannot answer counts as no keyboard here, since a drag on a * guess costs more than a keyboard a later tap refuses against by name. */ function keyboardShowing(raw: RawSnapshot): boolean { return keyboardShownIn(raw, isTruncated(raw)) === true; } /** * Whether a snapshot leaves out nodes that are on screen: agent-device says * it cut the tree, or the tree is still sparse after the retries (one * application node while the app publishes its tree). The harness never * calls such a screen unchanged, and the trace cache records the flag. */ function isTruncated(raw: RawSnapshot): boolean { return raw.truncated === true || raw.snapshotQuality?.state === 'sparse'; } /** Action data only: located references never retain a projected snapshot through parent links. */ interface NodeBinding { readonly id: string; readonly ref: string; readonly node: SemanticNode; readonly controlRef: string; /** The capture `ref` and `controlRef` came from, pinned on every action so agent-device refuses them once a newer capture supersedes it. */ readonly refsGeneration: number | undefined; readonly keyboardVisible: boolean; /** Whether the capture `node.rect` came from could not place its window on the screen. */ readonly originUnknown: boolean; /** The size that capture read off its own tree, which `viewportFor` checks against the screen. */ readonly captureViewport: ViewportSize | undefined; /** Whether `fill` and `clear` may type into the node, judged with the children `node` leaves out. */ readonly takesText: boolean; } /** * How long a control that appeared or moved with the last action is given to * finish arriving before a test acts on it. The tree cannot tell a sliding * control from a landed one: iOS reports the final frame the moment a * transition starts, Android the frame in flight, so a modal or pushed screen * keeps sliding for about half a second after the action that opened it and * a tap aimed from either frame lands on whatever is behind the control. * Once the budget has passed the control is found again in a fresh * snapshot. Unmoved controls are immediate only when keyboard state also * stayed the same; a visible keyboard can precede the app's relayout. */ const DEFAULT_TRANSITION_MS = 500; /** * How long after a test's swipe or scroll skipped agent-device's stabilization * wait the next action on a control first confirms the control stopped moving. * A list still coasting swallows a tap to stop itself, so the press would * report success and change nothing. */ const GESTURE_STEADY_MS = 2_000; /** Pause between the reads that confirm a control stopped moving after a gesture. */ const GESTURE_STEADY_POLL_MS = 100; /** How one screenshot is taken. */ interface ScreenshotCapture { /** The status bar in a fixed state (time, battery, signal), for a screenshot compared against a stored one (`comparable`). */ readonly normalizeStatusBar?: boolean; } /** Whether two viewports are one screen, in the same orientation or rotated; rects from the tree carry fractions. */ function sameScreen(a: ViewportSize, b: ViewportSize): boolean { const near = (x: number, y: number): boolean => Math.abs(x - y) < 1; return (near(a.width, b.width) && near(a.height, b.height)) || (near(a.width, b.height) && near(a.height, b.width)); } /** The centre of a rect in logical pixels. */ function centreOf(rect: Rect): { x: number; y: number } { return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; } /** Whether two rects are the same to the pixel; a missing rect never matches, so a target must be measurable to be stable. */ function sameRect(a: Rect | undefined, b: Rect | undefined): boolean { if (a === undefined || b === undefined) return false; return Math.abs(a.x - b.x) < 1 && Math.abs(a.y - b.y) < 1 && Math.abs(a.width - b.width) < 1 && Math.abs(a.height - b.height) < 1; } const MAX_LOCATED_REFS = 2048; interface Attempt { readonly attemptId: string; readonly artifactsDir: string; screenshots: number; } /** One recording of the device: agent-device's screen recording, or the device provider's own. */ type Recording = ScreenRecording | LeaseRecording; /** agent-device's screen recording: where its file lands, and when the device confirmed it was on. */ interface ScreenRecording { readonly kind: 'screen'; readonly relative: string; readonly absolute: string; startedAt: string; /** Shared finalization survives a caller's cancelled wait, including its successful result. */ stopping?: Promise<{ readonly outPath?: unknown }> | undefined; } /** The device provider's recording of the leased device, as its `record` is starting it or started it. */ interface LeaseRecording { readonly kind: 'lease'; readonly artifactsDir: string; readonly recorder: LeaseRecorder; readonly started: Promise; /** The stop in flight, shared: a retry while a stop that ran out of budget is still running waits for it instead of stopping twice. */ stopping?: Promise | undefined; } /** What a worker records its device through when its provider records: the provider, and the lease the slot rides. */ interface LeaseRecorder { readonly provider: RecordingDeviceProvider; readonly lease: DeviceLease; readonly runId: string; readonly targetName: string; readonly env: Readonly>; } /** * The Apple runner defers a full snapshot after slow accessibility work and * returns a sparse one-node tree. Retrying device-side costs under a second; * returning the sparse tree costs the model a confused turn. */ const SPARSE_RETRY_BACKOFF_MS = [0, 1_200, 3_000] as const; /** * Waits between captures while the keyboard reads as moving * ({@link KeyboardUnknown.settling}): an iPhone keyboard slides in or out in * about a third of a second, longer on a loaded simulator, and a reading * taken mid-slide can say neither way. */ const KEYBOARD_SETTLE_BACKOFF_MS = [0, 250, 500, 1_000] as const; /** Number of parent hops from `entry` up to `ancestor`. */ function depthBelow(entry: ProjectedNode, ancestor: ProjectedNode): number { let hops = 0; for (let current = entry.parent; current !== undefined; current = current.parent) { hops += 1; if (current === ancestor) return hops; } return hops; } function sleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { const timer = setTimeout(done, ms); function done(): void { clearTimeout(timer); signal.removeEventListener('abort', done); resolve(); } signal.addEventListener('abort', done, { once: true }); }); } /** What agent-device is told about settling after an action. */ type SettleOptions = { readonly settle: true; readonly settleQuietMs: number } | Record; /** * Whether agent-device holds the next read after a scroll or swipe until the * tree stops moving. A test's gesture opts out: its `expect` polls the screen * itself, and agent-device otherwise waits up to 3.5 s for a swipe that left * the tree unchanged. An agent keeps the wait, since it reads the screen next. */ type GestureStabilizationOptions = { readonly postGestureStabilization: false } | Record; const DEFAULT_SETTLE_QUIET_MS = 150; /** Every option `mobile()` takes, kept equal to `MobileOptions` by the compiler. */ const MOBILE_OPTION_KEYS: readonly string[] = Object.keys({ platform: true, device: true, session: true, snapshot: true, settle: true, transition: true, videoTouches: true, } satisfies Record); /** Every `snapshot` value, kept equal to `MobileOptions['snapshot']` by the compiler. */ const SNAPSHOT_MODES: readonly string[] = Object.keys({ full: true, interactive: true } satisfies Record, true>); /** Every state a permission takes, kept equal to `PermissionState` by the compiler. */ const PERMISSION_STATES: readonly string[] = Object.keys({ grant: true, deny: true, reset: true } satisfies Record); /** The target's `app.permissions` as a launch takes them: `'all'` arrives from the harness as `allPermissions`. */ function configuredPermissions(app: EngineAppInfo): LaunchPermissions | undefined { return app.allPermissions === true ? 'all' : app.permissions; } /** * Refuses a permissions map before any device command: anything but `'all'` * or a plain object, a name agent-device * does not set, naming the nearest, or a state other than grant, deny, or * reset. `INVALID_CONFIG` for a target's `app.permissions`, `INVALID_ARGUMENT` * for a test's `device.openApp`. An `undefined` state is skipped, as the preset * skips it. */ export function assertPermissions(label: string, permissions: unknown, code: 'INVALID_CONFIG' | 'INVALID_ARGUMENT'): void { if (permissions === 'all') return; // A Map or class instance carries no own keys to check, and the preset would apply none of it. const prototype: unknown = typeof permissions === 'object' && permissions !== null ? Object.getPrototypeOf(permissions) : undefined; if (prototype !== Object.prototype && prototype !== null) { permissionError(code, `${label} must be 'all' or a plain object of permission names to ${PERMISSION_STATES.join(', ')}`); } rejectUnknownKeys(label, permissions as object, DEVICE_PERMISSIONS, code); for (const [name, state] of Object.entries(permissions as Record)) { if (state !== undefined) assertPermission(label, name, state, code); } } /** * Refuses one permission before any device command: a name that is not a * string or not one agent-device sets, naming the nearest, or a state other * than grant, deny, or reset, `undefined` included. The one owner of the * permission messages, for `assertPermissions` and `device.setPermission`. */ function assertPermission(label: string, name: unknown, state: unknown, code: 'INVALID_CONFIG' | 'INVALID_ARGUMENT'): void { if (typeof name !== 'string') { permissionError(code, `${label} permission must be one of ${DEVICE_PERMISSIONS.join(', ')}, got type ${typeof name}`); } if (!(DEVICE_PERMISSIONS as readonly string[]).includes(name)) rejectUnknownKeys(label, { [name]: state }, DEVICE_PERMISSIONS, code); if (!PERMISSION_STATES.includes(state as string)) { permissionError(code, `${label}.${name} must be one of ${PERMISSION_STATES.join(', ')}, got ${typeof state === 'string' ? `"${state}"` : String(state)}`); } } /** Throws a permission refusal as the error class its code belongs to. */ function permissionError(code: 'INVALID_CONFIG' | 'INVALID_ARGUMENT', message: string): never { throw code === 'INVALID_CONFIG' ? new ConfigurationError(code, message) : new TestError(code, message); } /** Resolves the `transition` option: the default budget or a custom one. */ function transitionMs(transition: MobileOptions['transition']): number { const budget = transition ?? DEFAULT_TRANSITION_MS; if (!Number.isInteger(budget) || budget < 0) { throw new ConfigurationError('INVALID_CONFIG', 'mobile: `transition` must be a non-negative integer of milliseconds'); } return budget; } /** The stabilization wait a gesture carries: none for a test's own step, agent-device's default for the agent. */ function gestureStabilization(operation: OperationContext): GestureStabilizationOptions { return operation.origin === 'test' ? { postGestureStabilization: false } : {}; } /** True when two bounds are the same; a control without bounds has nothing to compare, so it counts as unmoved. */ function sameBounds(a: NodeBinding['node']['rect'], b: NodeBinding['node']['rect']): boolean { if (a === undefined || b === undefined) return true; return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height; } /** Resolves the `settle` option: the default window, a custom one, or no wait at all. */ function settleOptions(settle: MobileOptions['settle']): SettleOptions { if (settle === false) return {}; const quietMs = settle ?? DEFAULT_SETTLE_QUIET_MS; if (!Number.isInteger(quietMs) || quietMs < 0) { throw new ConfigurationError('INVALID_CONFIG', 'mobile: `settle` must be a non-negative integer of milliseconds, or false'); } return { settle: true, settleQuietMs: quietMs }; } /** * Resolves the `snapshot` option to whether captures keep interactive nodes * only; `'Interactive'` used to capture the full tree as if unset. */ function interactiveSnapshots(snapshot: MobileOptions['snapshot']): boolean { if (snapshot !== undefined && !SNAPSHOT_MODES.includes(snapshot)) { throw new ConfigurationError('INVALID_CONFIG', `mobile: \`snapshot\` must be ${SNAPSHOT_MODES.map((mode) => `'${mode}'`).join(' or ')}, got ${JSON.stringify(snapshot)}`); } return snapshot === 'interactive'; } /** * Resolves the `videoTouches` option to whether recordings hide the touch * overlay; `'false'` used to draw the touches as if unset. */ function hideTouches(videoTouches: MobileOptions['videoTouches']): boolean { if (videoTouches !== undefined && typeof videoTouches !== 'boolean') { throw new ConfigurationError('INVALID_CONFIG', `mobile: \`videoTouches\` must be true or false, got ${JSON.stringify(videoTouches)}`); } return videoTouches === false; } /** Calls one of the harness's trace hooks; a hook that throws, or one an older harness lacks, never fails the device's work. */ function tellHarness(call: () => void): void { try { call(); } catch { // The trace is a reader of the attempt, never a reason it fails. } } /** The agent-device session a worker drives, and the device agent-device booted for it. */ export interface BoundDevice { readonly session: string; readonly deviceId: string; readonly deviceName: string; } export class AgentDeviceSurface { private client: AgentDeviceClient | undefined; private attempt: Attempt | undefined; /** Retained across attempt cleanup until a stop or native session reset is confirmed. */ private recording: Recording | undefined; /** The attempt's `EngineAttemptContext.screen`, which locate captures feed; undefined between attempts. */ private screenSink: ((snapshot: EngineSnapshot) => void) | undefined; /** The device this worker drives, the pool's binding for its slot; undefined leaves the choice to agent-device. */ private device: SlotBinding | undefined; private generation = new Map(); private readonly located = new Map(); private idCounter = 0; private appIdentity: string | undefined; /** True from a launch until a snapshot succeeds: an app iOS reports not running in between is still starting, not gone. */ private launching = false; /** The app the build `appPath` installed, once `init` has, itself or through a lease. */ private installedApp: string | undefined; /** The target's app, as `init` received it. */ private app: EngineAppInfo = {}; /** Where relative build paths resolve; the run's project root once init has told us. */ private projectRoot = process.cwd(); /** The session and device this worker drives, for the error messages whose recovery is per device; set in init. */ private where: string | undefined; /** The agent-device session this worker drives and the device `init` booted under it. */ private bound: BoundDevice | undefined; /** How this worker's device records through its provider: set in init when the pool's provider records and the slot rides one of its leases. */ private leaseRecorder: LeaseRecorder | undefined; /** * SDK requests still pending, including uncancelled commands abandoned * by their caller. Cancelled press promises can settle before native * work ends; agent-device owns its bounded drain and device-request ordering. */ private readonly inflight = new Set>(); /** The target's devices, one per worker slot; `init` takes this worker's from it. */ readonly pool: DevicePool; /** The settle wait every action carries: quiet window from the `settle` option, or nothing when it is `false`. */ readonly settleOptions: SettleOptions; /** When this surface last acted on the device (an input or an app launch); the screen may be in transition for a while after. */ private lastActionAt = 0; /** When a test's swipe or scroll last went out without agent-device's stabilization wait; 0 when nothing is pending. */ private skippedStabilizationAt = 0; /** The screen as last projected before that action, to tell controls that were already there from ones that came with it. */ private screenBeforeAction: ProjectedScreen | undefined; /** The most recent projection of the screen, from any observe or locate. */ private latestScreen: ProjectedScreen | undefined; /** Budget a control that came with the last action gets to finish arriving; see DEFAULT_TRANSITION_MS. */ private readonly transitionMs: number; /** Whether snapshots keep interactive nodes only, from the `snapshot` option. */ private readonly interactiveSnapshots: boolean; /** Whether recordings hide the touch overlay, from the `videoTouches` option. */ private readonly hideTouches: boolean; /** * The screen's logical size as last learned from a snapshot with geometry * or from the device itself, so a snapshot without geometry (an empty * screen before any app is open, a sparse tree) or with an app drawn * smaller than the screen still reports the viewport every observation * must carry. A rotation replaces it; any other size needs the device's * screen to agree, see `viewportFor`. */ private knownViewport: ViewportSize | undefined; constructor( readonly options: MobileOptions, private readonly createClient: ClientFactory, ) { rejectUnknownKeys('mobile()', options, MOBILE_OPTION_KEYS); this.pool = new DevicePool(options, createClient); this.settleOptions = settleOptions(options.settle); this.transitionMs = transitionMs(options.transition); this.interactiveSnapshots = interactiveSnapshots(options.snapshot); this.hideTouches = hideTouches(options.videoTouches); } /** Whether the target pins an app for `app.open()`, `app.restart()`, and `app.clearState()` to launch. */ private get managesApp(): boolean { return this.app.bundleId !== undefined || this.app.appPath !== undefined; } /** The checks of `e2e doctor`, under the session a run's first slot uses; see `mobileDoctor`. */ doctor(info: EngineDoctorInfo): Promise { return mobileDoctor(this.options, this.createClient, this.pool.session(info, 0), info); } /** The app `app.open()` launches: the target's `bundleId`, else the app its build `appPath` installed. */ get pinnedApp(): string | undefined { return pinnedApp(this.app, this.installedApp); } /** The build the target's `app.appPath` names, as declared. */ get appPath(): string | undefined { return this.app.appPath; } /** Whether an attempt is running on this surface right now. */ get attemptRunning(): boolean { return this.attempt !== undefined; } /** The agent-device session and the device it runs on; INVALID_STATE before init or after dispose. */ get boundDevice(): BoundDevice { if (this.bound === undefined) throw invalidState('the agent-device engine is not initialized'); return this.bound; } /** The live client; INVALID_STATE before init or after dispose. */ requireClient(): AgentDeviceClient { if (this.client === undefined) throw invalidState('the agent-device engine is not initialized'); return this.client; } /** * Runs one agent-device command under an operation budget and translates * its failure. Contributed-fixture methods route through here too, so the * device fixture never carries its own error mapping. */ async command(label: string, run: (client: AgentDeviceClient) => Promise, signal?: AbortSignal): Promise { const client = this.requireClient(); return runCommand(label, () => this.track(run(client)), signal ?? new AbortController().signal, this.where); } /** * Runs a fixture command that changes the screen (a back, the home screen, * a dismissed alert or keyboard, a rotation) and records it as an action, * so a control that arrives with the change waits out the transition * budget before a test acts on it, as it does after a tap. Without this a * `device.back()` followed by a tap lands where the returning screen has * not yet arrived. */ async screenCommand(label: string, run: (client: AgentDeviceClient) => Promise, signal: AbortSignal): Promise { const before = this.latestScreen; const result = await this.command(label, run, signal); this.markAction(before); return result; } /** The budget and cancellation signal shared by one operation's inputs. */ inputBudget(label: string, operation: Pick): InputBudget { return new InputBudget(label, operation.timeoutMs, (pending) => this.track(pending), operation.signal); } /** Registers one device command as in flight until it settles. */ private track(pending: Promise): Promise { this.inflight.add(pending); pending.then( () => this.inflight.delete(pending), () => this.inflight.delete(pending), ); return pending; } /** * Waits for every abandoned command to settle, within the caller's * budget. A command that never settles fails the attempt launch instead of * racing it: the launch timeout is the honest bound on a stuck device. */ private async settleInflight(signal: AbortSignal): Promise { while (this.inflight.size > 0) { await raceAbort(Promise.allSettled(this.inflight), signal, 'settling in-flight device commands'); } } /** * The device selection this worker's commands take. A command that can * run with no app open (before `app.open()`, after `closeApp()` ends the * session) carries it: the daemon then resolves the device from it and * not from every booted one. With a session open it names the session's * own device, which agent-device accepts. */ selection(): DeviceSelection { return deviceSelection(this.options.platform, this.device); } async init(info: EngineInitInfo): Promise { this.projectRoot = info.projectRoot; this.app = info.app; const binding = this.pool.binding(info, info.workerSlot, info.env); this.device = binding; const session = this.pool.slotSession(info, info.workerSlot, binding); const label = deviceLabel(binding); this.where = `session ${session}${label === undefined ? '' : ` on ${label}`}`; this.client ??= this.createClient(session, binding); const provider = this.pool.recorder; const lease = travelledLease(binding); this.leaseRecorder = provider === undefined || lease === undefined ? undefined : { provider, lease, runId: info.runId, targetName: info.targetName, env: info.env }; const booted = await this.command('boot', (client) => client.devices.boot(bootRequest(this.selection())), info.signal); this.bound = { session, deviceId: booted.id, deviceName: booted.device }; // Nothing is installed here: a device provider that installed the build // from `appPath` says so on the binding, and otherwise the suite installs // it where it wants to, with `device.installApp()`. this.installedApp = binding?.installedApp; } async startAttempt(context: EngineAttemptContext): Promise { if (this.attempt !== undefined) { throw invalidState('an attempt is already running on this agent-device engine'); } await this.settleInflight(context.signal); const recording = this.recording; if (recording?.kind === 'screen') { await this.command('reset video recording', (client) => client.sessions.close(), context.signal); if (this.recording === recording) this.recording = undefined; this.screenReplaced(); } else if (recording?.kind === 'lease') { await this.stopLeaseRecording(recording, context.signal); } // Nothing is launched here: the app is where the last test, or the // worker's `prepare`, left it, and a test that wants it fresh calls // `app.open()`, which is `restart` below. The bindings are forgotten, the // screen is not, so a control still in place is acted on at once. this.attempt = { attemptId: context.attemptId, artifactsDir: context.artifactsDir, screenshots: 0 }; this.generation = new Map(); this.located.clear(); this.screenSink = context.screen; const device = deviceLabel(this.device); tellHarness(() => context.environment?.({ platform: this.options.platform, ...(device === undefined ? {} : { device }) })); } async endAttempt(context: EngineCleanupContext): Promise { const dangling = this.recording; this.attempt = undefined; this.screenSink = undefined; this.generation = new Map(); this.located.clear(); // The harness stops the video before it ends the attempt; a recording still // marked here belongs to an attempt cut short, or to a stop that failed, // and the device must not keep recording into the next one. A start that // outlived its budget may still be landing: it settles first, so the stop // cannot overtake it. if (dangling?.kind === 'lease') { await this.stopLeaseRecording(dangling, context.signal).catch(() => undefined); } else if (dangling !== undefined) { await this.settleInflight(context.signal).catch(() => undefined); await this.stopScreenRecording(dangling, context.signal).catch(() => undefined); } } // --- video --- /** * Asks the device to record its screen into the attempt directory. Taps stay * visible in the recording (agent-device's touch indicator), which is the * closest a phone comes to a cursor, unless `videoTouches` is `false`. A * device provider that records its devices records the attempt instead, * when the slot rides one of its leases. */ async startVideo(operation: OperationContext): Promise { const attempt = this.attempt; if (attempt === undefined) throw invalidState('startVideo outside an attempt'); if (this.recording !== undefined) throw invalidState('a video is already recording'); if (this.leaseRecorder !== undefined) { await this.startLeaseRecording(attempt, this.leaseRecorder, operation.signal); return; } const relative = path.join('video', 'video.mp4'); const absolute = path.join(attempt.artifactsDir, relative); mkdirSync(path.dirname(absolute), { recursive: true }); // Marked before the device is asked: a start that outlives its budget // still records, and `endAttempt` must be able to stop it. const recording: ScreenRecording = { kind: 'screen', relative, absolute, startedAt: new Date().toISOString() }; this.recording = recording; await this.command( 'start video recording', // The whole screen: an app scope refuses to start while no app is open, before `app.open()` and after `closeApp()`. (client) => client.recording.record({ ...this.selection(), action: 'start', path: absolute, quality: 'medium', recordingScope: 'device', ...(this.hideTouches ? { hideTouches: true } : {}), }), operation.signal, ); // The device confirmed: it is recording from about now. recording.startedAt = new Date().toISOString(); } /** Stops the recording and returns its one segment, or none when the device wrote nothing. */ async stopVideo(operation: OperationContext): Promise { const attempt = this.attempt; if (attempt === undefined) throw invalidState('stopVideo outside an attempt'); const video = this.recording; if (video === undefined) return []; if (video.kind === 'lease') { return [await this.stopLeaseRecording(video, operation.signal)]; } const result = await this.stopScreenRecording(video, operation.signal); // The device may finalize the file under a path of its own choosing; the // artifact must live where the attempt directory expects it. const written = typeof result.outPath === 'string' ? result.outPath : video.absolute; if (written !== video.absolute && existsSync(written)) renameSync(written, video.absolute); if (!existsSync(video.absolute)) return []; return [{ path: video.relative, startedAt: video.startedAt }]; } /** * Stops the device's screen recording. A device-scope recording started * with no session made one of its own, and stopping it ends that session, * whatever the test opened in it since, so the session is then as * `closeApp` leaves it. */ private async stopScreenRecording(video: ScreenRecording, signal: AbortSignal): Promise<{ readonly outPath?: unknown }> { return raceAbort(() => { // Cleanup must wait for this bookkeeping as well as the SDK request. video.stopping ??= this.track(this.command('stop video recording', (client) => client.recording.record({ ...this.selection(), action: 'stop' })).then((result) => { if (this.recording === video) this.recording = undefined; if (result.recordOnlySession === true) this.screenReplaced(); return result; }, (cause: unknown) => { video.stopping = undefined; throw cause; })); return video.stopping; }, signal, 'stop video recording'); } /** * Starts the device provider's recording of the leased device. Marked * the moment `record` is called, before it settles, as the screen * recording is before its start command: a start that outlives its budget * may still come up, and `endAttempt` then stops it. */ private async startLeaseRecording(attempt: Attempt, recorder: LeaseRecorder, signal: AbortSignal): Promise { const { provider, lease, runId, targetName, env } = recorder; const started = recordLease(provider, lease, { runId, targetName, attemptId: attempt.attemptId, env, signal }); const video: LeaseRecording = { kind: 'lease', recorder, started, artifactsDir: attempt.artifactsDir }; this.recording = video; void started.catch(() => { if (this.recording === video) this.recording = undefined; }); await raceAbort(started, signal, 'start video recording'); } /** Ends the provider's recording as the attempt's one segment, a file in its `video` directory or a link. */ private async stopLeaseRecording(video: LeaseRecording, signal: AbortSignal): Promise { const { provider, lease } = video.recorder; video.stopping ??= (async () => { const recording = await video.started; return stopProviderRecording({ startedAt: recording.startedAt, stop: async (context) => { const result = await recording.stop(context); if (this.recording === video) this.recording = undefined; return result; }, }, { artifactsDir: video.artifactsDir, provider: `device provider "${provider.name}"`, leaseId: lease.id, signal }); })().finally(() => { video.stopping = undefined; }); return raceAbort(video.stopping, signal, 'stop video recording'); } async dispose(context: EngineCleanupContext & { readonly reuseSignal?: AbortSignal }): Promise { const client = this.client; const recording = this.recording; this.client = undefined; this.bound = undefined; this.attempt = undefined; this.screenSink = undefined; this.generation = new Map(); this.located.clear(); this.appIdentity = undefined; this.installedApp = undefined; this.knownViewport = undefined; let closing: Promise | undefined; const close = (): void => { if (client === undefined) return; closing ??= client.sessions.close().then(() => { if (recording?.kind === 'screen' && this.recording === recording) this.recording = undefined; }).catch(() => undefined); }; const reuse = context.reuseSignal; reuse?.addEventListener('abort', close, { once: true }); const canKeepSession = this.device?.leaseId !== undefined && recording?.kind !== 'screen' && reuse !== undefined && !reuse.aborted; if (!canKeepSession) close(); try { const stopping = recording?.kind === 'lease' ? this.stopLeaseRecording(recording, context.signal).catch(() => undefined) : undefined; await withinCleanupBudget((async () => { await stopping; await closing; })(), context); } finally { reuse?.removeEventListener('abort', close); } } /** * Opens an app in the session, remembering its identity for the path * anchor. A link is refused before the device sees it: agent-device would * open it as a URL, and `openLink` is the path that carries the * navigation rule. */ async openApp(app: string, options: OpenAppOptions, signal: AbortSignal): Promise { assertAppId(app); if (options.permissions !== undefined) assertPermissions('device.openApp({ permissions })', options.permissions, 'INVALID_ARGUMENT'); const relaunch = options.relaunch === true; // The engine's own launch options belong to a fresh launch of the pinned // app. A foreground-only open of a running app takes no arguments, and a // permission change there would terminate the app it means to keep. const configured = relaunch && app === this.pinnedApp; const launchArguments = launchArgumentsForOpen(this.options.platform, options.launchArguments) ?? (configured ? (this.app.launchArgumentValues ?? this.app.launchArguments) : undefined); const permissions = options.permissions ?? (configured ? configuredPermissions(this.app) : undefined); if (permissions !== undefined) await this.presetPermissions(app, permissions, signal); await this.open(app, relaunch, launchArguments, signal); } /** One `open` of an app, remembered as the session's app and as the screen's replacement. */ private async open(app: string, relaunch: boolean, launchArguments: ResolvedLaunchArguments | undefined, signal: AbortSignal): Promise { const launchArgs = launchArgumentList(this.options.platform, launchArguments); const result = await this.command( `open ${app}`, (client) => client.apps.open({ app, ...this.selection(), ...(relaunch ? { relaunch: true } : {}), ...(launchArgs === undefined ? {} : { launchArgs: [...launchArgs] }), }), signal, ); this.launched(result.appBundleId ?? result.appName ?? app); } /** * Puts an app's permissions in place before it launches, never after: iOS * terminates a running app whose permission changed, and Android one whose * permission was revoked, so a change after the launch would leave the * test on no screen. `'all'` is one agent-device `all` grant on either * platform; `LaunchPermissions` says what it grants on each. */ private async presetPermissions(app: string, permissions: LaunchPermissions, signal: AbortSignal): Promise { if (permissions === 'all') { await this.permission('all', 'grant', app, signal); return; } const entries = Object.entries(permissions).filter( (entry): entry is [DevicePermission, PermissionState] => entry[1] !== undefined, ); for (const [permission, state] of entries) await this.permission(permission, state, app, signal); } /** * One permission change for `device.setPermission`: on the pinned app, else * on the app agent-device's session is on. The name and state are checked * before any device command, a missing state refused rather than skipped. */ async setPermission(permission: DevicePermission, state: PermissionState, signal: AbortSignal): Promise { assertPermission('device.setPermission', permission, state, 'INVALID_ARGUMENT'); await this.permission(permission, state, this.pinnedApp, signal); } /** One permission change on `app`, which needs no running app and no open in the session. */ private async permission(permission: DevicePermission | 'all', state: PermissionState, app: string | undefined, signal: AbortSignal): Promise { await this.command( `permission ${permission} ${state}`, (client) => client.settings.update({ setting: 'permission', permission, state, ...this.selection(), ...(app === undefined ? {} : { app }) }), signal, ); } /** * Opens a link on the device, into `app` (the pinned app when none is * named). Bound to an app, agent-device hands the link to it and the * session observes that app afterwards: iOS launches the app first for a * web link and then opens the URL, Android starts a VIEW intent on the * package. Without an app the OS routes the link to the scheme's app, a * verified app link owner, or the browser. iOS needs the app: an unbound * `open ` there leaves no app session, so the next snapshot would * fail, and agent-device refuses a deep link without one on a physical * device anyway. An unbound open reports the URL as its app name, which is * no identity, and the package that took the link as its bundle id when * the OS told it; the next snapshot names the foreground app either way. */ async openLink(url: URL, app: string | undefined, signal: AbortSignal, input?: InputBudget): Promise { const target = app ?? this.pinnedApp; if (target === undefined && this.options.platform === 'ios') { throw new TestError( 'INVALID_ARGUMENT', "openLink needs an app on iOS: pass `app`, or pin one with the target's app.bundleId or app.appPath; the session observes the app a link is opened into", ); } const result = await this.command( 'device.openLink', (client) => { const open = () => client.apps.open({ ...this.selection(), ...(target === undefined ? { app: url.href } : { app: target, url: url.href }), }); // An `app.open(path)` is an input like a tap: past its budget the link may have opened, so it is never repeated. return input === undefined ? open() : input.send(open); }, signal, ); this.launched(result.appBundleId ?? (target === undefined ? undefined : (result.appName ?? target))); } /** * What a launch leaves behind. The identity is the app agent-device named; * a link the OS routed keeps the last known one until the next snapshot * reports the foreground app. */ private launched(identity: string | undefined): void { if (identity !== undefined) this.appIdentity = identity; this.launching = true; this.screenReplaced(); } /** * Forgets the screen after a launch or a close. There is no screen before * it worth matching against: every control of whatever shows next is * arriving, whatever the previous screen looked like, and none of its * bindings names a node that still exists. */ private screenReplaced(): void { this.markAction(undefined); this.generation = new Map(); this.located.clear(); } /** * Terminates the session's app, then ends the session. agent-device's bare * `close` ends the session and leaves the app running, so the next * `openApp` would resume it mid-flow; a close that names the app * terminates it first. The app is the one the session last observed, else * the pinned one; with neither known there is nothing to terminate and * only the session ends. */ async closeApp(signal: AbortSignal): Promise { const app = this.appIdentity ?? this.pinnedApp; await this.command('device.closeApp', (client) => client.apps.close({ ...this.selection(), ...(app === undefined ? {} : { app }) }), signal); this.screenReplaced(); } /** * Installs a build on the session's device. `reinstall` removes the app * named by `options.app` (else the pinned app) first, so the build starts * with no data; a plain install replaces the binary and keeps its data. * A leased daemon can resolve an absolute path on its own filesystem. * Other explicit paths must exist on the runner. */ async installApp(appPath: string | undefined, options: InstallAppOptions, signal: AbortSignal): Promise { const build = appPath ?? this.app.appPath; if (build === undefined) throw invalidState("installApp needs a build: pass a path, or name one with the target's app.appPath"); const resolved = path.resolve(this.projectRoot, build); // The remote client uploads a runner-visible build and forwards an absent // path to the leased daemon. Relative paths belong to the project root. const daemonCanResolve = this.device?.daemon !== undefined && path.isAbsolute(build); if (appPath !== undefined && (appPath.trim() === '' || (!daemonCanResolve && !existsSync(resolved)))) { throw new TestError('INVALID_ARGUMENT', `device.installApp(${JSON.stringify(appPath)}): no build at ${resolved}; the path resolves against the project root`); } const selection = this.selection(); const engineBuild = appPath === undefined || (this.app.appPath !== undefined && resolved === path.resolve(this.projectRoot, this.app.appPath)); const app = options.app ?? (engineBuild ? this.app.bundleId : undefined) ?? (options.reinstall === true ? this.pinnedApp : undefined); if (options.reinstall === true && app === undefined) { throw invalidState("reinstall needs an app: pass `app`, or pin one with the target's app.bundleId or app.appPath"); } const result: InstallIdentity = await this.command( `install ${resolved}`, (client) => options.reinstall === true && app !== undefined ? client.apps.reinstall({ ...selection, app, appPath: resolved }) : client.apps.install({ ...selection, ...(app === undefined ? {} : { app }), appPath: resolved }), signal, ); const installed: InstalledApp = installedIdentity(result, app, resolved, "the target's `app.bundleId` or installApp's `app` option"); // The engine's own build, installed: without `app`, this is what `app.open()` launches from here on. if (engineBuild) this.installedApp = installed.app; return installed; } /** * Removes an app (default: the pinned one) from the session's device and * resolves to whether it was installed; an app named by id that is not * there is no error (a missing display name is `APP_NOT_INSTALLED`). * Removing an app drops the nodes read from the session's screen, and * removing the build `installApp` pinned without an `app.bundleId` unpins it, so * `app.open()` asks for an install instead of launching an app that is gone. */ async uninstallApp(app: string | undefined, signal: AbortSignal): Promise { const target = this.appArgument('uninstallApp', app); const result = await this.command(`uninstall ${target}`, (client) => client.apps.uninstall({ ...this.selection(), app: target }), signal); // agent-device resolves display names too: compare the id it removed, not only the string the caller passed. const removed = typeof result['appId'] === 'string' ? result['appId'] : target; // The identity may be a display name no id comparison matches, so it always goes: the next snapshot fills it again. this.appIdentity = undefined; this.launching = false; this.screenReplaced(); if (target === this.installedApp || removed === this.installedApp) this.installedApp = undefined; return result['wasInstalled'] === true; } /** * Whether an app (default: the pinned one) is on the session's device, * system apps included. `app` is a bundle id or package, or the exact * name agent-device lists the app under. */ async isAppInstalled(app: string | undefined, signal: AbortSignal): Promise { const target = this.appArgument('isAppInstalled', app); const apps = await this.command('list apps', (client) => client.apps.list({ ...this.selection(), appsFilter: 'all' }), signal); return apps.some((entry) => listsApp(entry, target)); } /** The app a `device` method names, else the pinned one; neither is `INVALID_STATE`. */ private appArgument(method: string, app: string | undefined): string { const target = app ?? this.pinnedApp; if (target === undefined) { throw invalidState(`${method} needs an app: pass a bundle id or package, pin one with the target's app.bundleId, or ${UNINSTALLED_BUILD}`); } return target; } private async snapshot(signal: AbortSignal, interactiveOnly: boolean, budget: InputBudget): Promise { let last: RawSnapshot = {}; let captureMs = 0; for (const backoffMs of SPARSE_RETRY_BACKOFF_MS) { if (backoffMs > 0) { // A sparse capture is still the screen: a retry the budget cannot fit returns it instead of timing out. if (budget !== undefined && budget.remainingMs() <= backoffMs + captureMs) return last; await sleep(backoffMs, signal); } if (signal.aborted) throw new EngineError('CANCELLED', 'snapshot cancelled', { retryable: false }); const startedAt = Date.now(); last = await this.capture(signal, interactiveOnly, budget); captureMs = Date.now() - startedAt; this.launching = false; if (last.appBundleId !== undefined || last.appName !== undefined) { this.appIdentity = last.appBundleId ?? last.appName; } if (last.snapshotQuality?.state !== 'sparse') return last; } return last; } /** * One capture, taken again once when the iOS runner acquired the tree but * failed its own presentation check on it (a viewport it could not read, a * malformed graph). The check is per capture and a capture is a read, so * the retry is safe; a second failure is the runner's and propagates. Each * capture runs under `budget`, so one the budget abandoned is not retried. */ private async capture(signal: AbortSignal, interactiveOnly: boolean, budget: InputBudget): Promise { const take = (): Promise => budget.read(() => this.command('snapshot', (client) => client.capture.snapshot({ interactiveOnly }), signal)); try { return await take(); } catch (cause) { if (signal.aborted || !isSnapshotPresentationFailure(cause)) throw cause; return take(); } } /** * Snapshot for an observation. Without a pinned app, an observation before * anything is open is an empty screen rather than a fault: the model's next * move is the open tool, and failing the step would take that move away. */ private async snapshotOrEmpty(operation: OperationContext, interactiveOnly: boolean, budget: InputBudget): Promise { try { return await this.snapshot(operation.signal, interactiveOnly, budget); } catch (cause) { if (!this.managesApp && cause instanceof EngineError && cause.code === 'INVALID_STATE') return { nodes: [] }; throw cause; } } /** * Snapshot for a locate; undefined for a screen agent-device could not read * yet (an app still on its splash, or one iOS does not report running yet * after a launch). The harness polls a locate until its deadline, so that * screen matches nothing and the poll waits for it to render. When what is * left of the budget cannot fit another capture as long as this one, the * locate fails with the reason instead: the budget bounds every capture, so * an unreadable one never outlasts it, and the wait that ends on an * unreadable screen says so. */ private async locateSnapshot(operation: OperationContext, budget: InputBudget): Promise { const startedMs = Date.now(); try { return await this.snapshotOrEmpty(operation, false, budget); } catch (cause) { const arriving = isUnreadableCapture(cause) || (this.launching && isAppNotRunning(cause)); if (operation.signal.aborted || !arriving || budget.remainingMs() < Date.now() - startedMs) throw cause; return undefined; } } /** * Projects a snapshot and learns its viewport when it is plainly the * screen's: the first one the session reads, the one it knows, or that one * rotated. A tree of any other size may be an app drawn smaller than the * screen (behind Notification Center, iOS shrinks it to a third), so an * observation's `viewportFor` checks it against the device before it * replaces the known one. */ private project(raw: RawSnapshot): ProjectedScreen { const projected = { ...projectSnapshot(raw.nodes ?? [], { mintId: () => { this.idCounter += 1; return `n${this.idCounter}`; }, viewport: raw.viewport, refsGeneration: raw.refsGeneration, keyboard: keyboardBand(raw.nodes ?? [], raw.keyboard, raw.viewport), }), keyboardVisible: keyboardShowing(raw), originUnknown: raw.warnings?.includes(ORIGIN_WARNING) === true, }; this.latestScreen = projected; const read = projected.viewport; if (read !== undefined && (this.knownViewport === undefined || sameScreen(read, this.knownViewport))) this.knownViewport = read; return projected; } /** * The viewport of a snapshot: its own geometry when that is the screen, * else the last one this session learned, else the device's logical screen * size read off one screenshot. A tree whose size is neither the known one * nor that one rotated replaces it only when the screenshot's size, in * either orientation, agrees: a screenshot reports the portrait size even * in landscape, so it confirms a size but cannot pick the orientation. Only * a simulator's screenshot reports a logical size; on a real device the * tree's size is taken as it comes. A device whose size cannot be learned * at all fails the observation: the harness * measures every rect and point against the viewport, so an invented one * would misplace every tap. */ private async viewportFor(read: ViewportSize | undefined, signal: AbortSignal, budget: InputBudget): Promise { const known = this.knownViewport; if (known !== undefined) { if (read === undefined) return known; if (!sameScreen(read, known)) { const probed = await this.probeViewport(signal, budget); if (probed !== undefined && !sameScreen(read, probed)) return known; } this.knownViewport = read; return read; } const probed = await this.probeViewport(signal, budget); if (probed === undefined) { throw new EngineError( 'ENGINE_FAILURE', 'the device reported no screen geometry: the snapshot has no bounds and the screenshot no logical size, so the viewport is unknown', { retryable: false }, ); } this.knownViewport = probed; return probed; } /** The device's logical screen size as its screenshot reports it; undefined when it reports none. */ private async probeViewport(signal: AbortSignal, budget: InputBudget): Promise { const result = await this.captureScreenshot(signal, async (shot) => shot, {}, budget); return logicalScreenSize(result); } /** Reads the screen size in the coordinate space of screen taps. */ async viewport(operation: OperationContext, budget: InputBudget): Promise { const raw = await this.snapshotOrEmpty(operation, this.interactiveSnapshots, budget); const projected = this.project(raw); const { width, height } = await this.viewportFor(projected.viewport, operation.signal, budget); return { width, height }; } async observe(operation: OperationContext, options: EngineObserveOptions | undefined, budget: InputBudget): Promise { const raw = await this.snapshotOrEmpty(operation, this.interactiveSnapshots, budget); const projected = this.project(raw); this.generation = new Map(projected.index.map((entry) => [entry.id, this.bind(entry, projected)])); const viewport = await this.viewportFor(projected.viewport, operation.signal, budget); const location = screenLocation(raw.appBundleId ?? raw.appName ?? this.appIdentity, screenTitle(projected)); const capture = options?.pixels === true ? await this.capturePixels(operation, projected, viewport, { normalizeStatusBar: options.comparable === true }, budget) : undefined; const keyboardVisible = measuredKeyboard(raw); return { root: screenRoot(projected.roots, viewport), viewport, ...(isTruncated(raw) ? { truncated: true } : {}), ...(keyboardVisible === undefined ? {} : { keyboardVisible }), ...(location === undefined ? {} : { location }), ...(capture?.pixels === undefined ? {} : { pixels: capture.pixels }), ...(capture === undefined ? {} : { maskedRegionCount: capture.masked }), }; } /** Retains only action bindings for matches, independently of the observation generation. */ async locate(expression: LocatorExpression, operation: OperationContext, budget: InputBudget): Promise { const raw = await this.locateSnapshot(operation, budget); if (raw === undefined) return []; const projected = this.project(raw); this.traceScreen(raw, projected); const matches = resolveExpression(expression, projected.index, this.options.platform); for (const entry of matches) this.located.set(entry.id, this.bind(entry, projected)); for (const oldest of this.located.keys()) { if (this.located.size <= MAX_LOCATED_REFS) break; this.located.delete(oldest); } return matches.map((entry) => withEmptyState(entry.node)); } /** * Hands the harness the capture a locate matched against, for the trace: * the screen the step acted on, at no cost of another snapshot. A screen * whose viewport is not known yet is skipped rather than probed. */ private traceScreen(raw: RawSnapshot, projected: ProjectedSnapshot): void { const sink = this.screenSink; const viewport = this.knownViewport; if (sink === undefined || viewport === undefined) return; const location = screenLocation(raw.appBundleId ?? raw.appName ?? this.appIdentity, screenTitle(projected)); tellHarness(() => sink({ root: screenRoot(projected.roots, viewport), viewport, ...(isTruncated(raw) ? { truncated: true } : {}), ...(location === undefined ? {} : { location }), }), ); } /** * Whether a positive area of a node is on the screen, read off the capture * that located it. agent-device clips each rect to the window and to its * scrolling ancestors, and leaves out a node with nothing on screen, so a * rect is only the visible part of a box: the share of the whole is * unknown, and the answer carries no `ratio`. The screen is the one * `viewportFor` confirms, as `observe` does: a capture whose size is not * the known screen's asks the device, since an app drawn smaller than the * screen shrinks it and a resized screen (a foldable, Split View) grows it. * A rect whose window could not be placed on the screen is refused rather * than guessed at. */ async viewportIntersection(ref: NodeRef, operation: OperationContext, budget: InputBudget): Promise { const entry = this.resolveRef(ref); const rect = entry.node.rect; if (entry.originUnknown) { throw new EngineError('UNSUPPORTED_CAPABILITY', `whether node ${ref.id} is in the viewport is unknown: the ${ORIGIN_UNKNOWN_BOUNDS}`, { retryable: false, }); } if (rect === undefined) { throw new EngineError('UNSUPPORTED_CAPABILITY', `node ${ref.id} has no bounds on the screen, so whether it is in the viewport is unknown`, { retryable: false, }); } const screen = await this.viewportFor(entry.captureViewport, operation.signal, budget); const width = Math.min(rect.x + rect.width, screen.width) - Math.max(rect.x, 0); const height = Math.min(rect.y + rect.height, screen.height) - Math.max(rect.y, 0); return { intersects: width > 0 && height > 0 }; } private resolveRef(ref: NodeRef): NodeBinding { const entry = this.located.get(ref.id) ?? this.generation.get(ref.id); if (entry === undefined) { throw new EngineError('NODE_STALE', `node ${ref.id} is not part of the newest observation`, { retryable: true }); } return entry; } private actionTarget(entry: NodeBinding, control = false): { ref: string } { const ref = control ? entry.controlRef : entry.ref; if (ref === '') throw notActionable(`node ${entry.id} has no agent-device ref to act on`); return { ref: entry.refsGeneration === undefined ? `@${ref}` : formatPinnedRef(ref, entry.refsGeneration) }; } /** * The node a toggle press must land on. UIKit reports a settings row as a * labelled `Switch` spanning the whole row with the real control as an * unlabelled `Switch` child at its trailing edge; a press at the row's * centre hits the label and changes nothing. The innermost same-role * descendant with a ref is the control; a node without one is its own. */ private controlOf(entry: ProjectedNode, snapshot: readonly ProjectedNode[]): ProjectedNode { const role = entry.node.role; if (role !== 'switch' && role !== 'checkbox') return entry; let control = entry; let depth = 0; for (const candidate of snapshot) { if (candidate.ref === '' || candidate.node.role !== role || !isWithin(candidate, entry)) continue; const candidateDepth = depthBelow(candidate, entry); if (candidateDepth > depth) { control = candidate; depth = candidateDepth; } } return control; } /** Copies the fields actions use and pre-resolves a toggle's inner control. */ private bind(entry: ProjectedNode, snapshot: ProjectedScreen): NodeBinding { const { children: _children, ...node } = entry.node; const control = this.controlOf(entry, snapshot.index); return { id: entry.id, ref: entry.ref, node, controlRef: control.ref, keyboardVisible: snapshot.keyboardVisible, originUnknown: snapshot.originUnknown, captureViewport: snapshot.viewport, takesText: mayTakeText(entry.node), refsGeneration: snapshot.refsGeneration, }; } /** The same control in the newest capture: the binding itself when it came from that capture, else found there again where it was. */ private current(entry: NodeBinding): NodeBinding { const latest = this.latestScreen; if (latest === undefined || entry.refsGeneration === latest.refsGeneration) return entry; const found = this.samePlace(entry, latest.index); if (found === undefined) { throw new EngineError('NODE_STALE', `node ${entry.id} changed since it was located; re-resolve`, { retryable: true }); } return this.bind(found, latest); } /** The node a binding stands for in a snapshot, when it is still where it was. */ private samePlace(entry: NodeBinding, index: readonly ProjectedNode[]): ProjectedNode | undefined { const found = this.refind(entry, index); return found !== undefined && sameRect(found.node.rect, entry.node.rect) ? found : undefined; } /** * The node a binding stands for, in a fresh snapshot: same role, same test * id, same name and text, and of those the one closest to where it was. */ private refind(entry: NodeBinding, index: readonly ProjectedNode[]): ProjectedNode | undefined { const candidates = index.filter( (candidate) => candidate.node.role === entry.node.role && candidate.node.testId === entry.node.testId && candidate.node.name === entry.node.name && candidate.node.text === entry.node.text, ); if (candidates.length <= 1 || entry.node.rect === undefined) return candidates[0]; const was = centreOf(entry.node.rect); let best = candidates[0]; let bestDistance = Number.POSITIVE_INFINITY; for (const candidate of candidates) { if (candidate.node.rect === undefined) continue; const at = centreOf(candidate.node.rect); const distance = Math.hypot(at.x - was.x, at.y - was.y); if (distance < bestDistance) { best = candidate; bestDistance = distance; } } return best; } /** Waits for the transition without exceeding the action's remaining budget. */ private async waitOutTransition(operation: OperationContext, budget: InputBudget): Promise { await raceAbort(async () => { const remaining = this.transitionMs - (Date.now() - this.lastActionAt); if (remaining <= 0) return; const available = budget.remainingMs(); if (available > 0) await sleep(Math.min(remaining, available), operation.signal); // A capped timer can wake before the clock reaches the deadline. It // still could not fit the transition, so it must never send input. if (available < remaining) { throw new EngineError('OPERATION_TIMEOUT', 'transition could not finish within the action budget', { retryable: false }); } }, operation.signal, 'transition wait'); } /** * Waits for a control that arrived or moved with the last action, returning * whether it needs a fresh capture. Controls already present at the same * place need no wait, unless keyboard state changed: a keyboard change can * precede the app's relayout. */ private async waitForTransition(entry: NodeBinding, operation: OperationContext, budget: InputBudget): Promise { const since = Date.now() - this.lastActionAt; const remaining = this.transitionMs - since; if (remaining <= 0) return false; const before = this.screenBeforeAction; if (before !== undefined && before.keyboardVisible === entry.keyboardVisible && this.samePlace(entry, before.index) !== undefined) return false; await this.waitOutTransition(operation, budget); return true; } /** Records that a test's gesture skipped the stabilization wait, so the next action on a control checks it stopped moving. */ private noteGesture(operation: OperationContext): void { if (operation.origin === 'test') this.skippedStabilizationAt = Date.now(); } /** * After a gesture that skipped the stabilization wait, re-reads the control * until two reads agree on where it is, so an action does not land on a list * still coasting. Costs one extra snapshot when the screen already rests, * and nothing once GESTURE_STEADY_MS has passed. An input action keeps the * checks `relocated` makes on every read, and the poll never outlasts the * action's budget. */ private async steadied(entry: NodeBinding, operation: OperationContext, budget: InputBudget, input: boolean): Promise { const deadline = this.skippedStabilizationAt + GESTURE_STEADY_MS; if (this.skippedStabilizationAt === 0 || Date.now() >= deadline) return entry; let current = entry; for (;;) { const next = await this.relocated(current, operation, budget, input); const steady = sameBounds(current.node.rect, next.node.rect); current = next; if (steady || Date.now() >= deadline) break; if (budget.remainingMs() <= GESTURE_STEADY_POLL_MS) { throw new EngineError('OPERATION_TIMEOUT', 'the control kept moving until the action budget ran out', { retryable: false }); } await sleep(GESTURE_STEADY_POLL_MS, operation.signal); if (operation.signal.aborted) throw new EngineError('CANCELLED', 'gesture wait cancelled', { retryable: false }); } this.skippedStabilizationAt = 0; return current; } /** Refreshes a control after a transition wait, keeping the binding when no wait was needed. */ private async settled(entry: NodeBinding, operation: OperationContext, budget: InputBudget): Promise { if (await this.waitForTransition(entry, operation, budget)) return this.relocated(entry, operation, budget); return entry; } /** * The same control in a fresh snapshot. A snapshot that no longer lists it * is a retryable NODE_STALE, so the locator resolves again; input mutations * also refuse a truncated snapshot or changed security facts. */ private async relocated(entry: NodeBinding, operation: OperationContext, budget: InputBudget, input = false): Promise { const raw = await this.snapshotOrEmpty(operation, false, budget); const projected = this.project(raw); const found = this.refind(entry, projected.index); if (input && (isTruncated(raw) || found === undefined || entry.node.inputPurpose !== found.node.inputPurpose || entry.node.states?.disabled !== found.node.states?.disabled || entry.node.states?.secure !== found.node.states?.secure || entry.node.states?.hidden !== found.node.states?.hidden)) { throw new EngineError('NODE_STALE', `input node ${entry.id} changed before mutation; observe and authorize it again`, { retryable: true }); } if (found === undefined) { throw new EngineError('NODE_STALE', `node ${entry.id} changed during transition; re-resolve`, { retryable: true }); } return this.bind(found, projected); } /** * Records an action the device received: the screen as it was projected * before it, and when it returned. The transition budget counts from the * return, since the input lands late in the command's own round trip. */ private markAction(before: ProjectedScreen | undefined): void { this.screenBeforeAction = before; this.lastActionAt = Date.now(); } async perform(ref: NodeRef, action: LocatorAction, operation: OperationContext, input: InputBudget): Promise { // A test's step verifies its outcome with `expect`, so it never waits for // the screen to settle afterwards; it only lets a control that came with // the last action finish arriving. The agent reads the screen right after // acting, so its actions settle first. const deterministic = operation.origin === 'test'; const settle = deterministic ? {} : this.settleOptions; // The observation root is the screen: a swipe on it scrolls the whole // viewport, which is the one action a screen takes. It sends no `amount` // and keeps agent-device's default for every momentum and every origin: // agent-device centres the gesture on the viewport, so the finger starts // at `0.5 + amount / 2` of the height, and a larger amount lands it in // bottom chrome (a sticky footer, a tab bar) that swallows the drag. A // live iOS run lost every `slow` scroll of the mobile benchmark's sticky // chrome flow that way. if (ref.id === ROOT_ID) { if (action.kind !== 'swipe' && action.kind !== 'scrollTo') { throw notActionable(`the screen root takes swipe and scrollTo only, not ${action.kind}; act on a node`); } if (deterministic) await this.waitOutTransition(operation, input); const before = this.latestScreen; if (action.kind === 'scrollTo') { try { await raceAbort(() => this.track(this.scrollToEdge(undefined, action.edge, operation, input)), operation.signal, 'perform scrollTo'); } catch (cause) { throw staleOr(cause, 'perform scrollTo', this.where); } } else { const stabilization = gestureStabilization(operation); await this.command( 'swipe', (client) => input.send(() => client.interactions.scroll({ direction: action.direction, ...settle, ...stabilization })), operation.signal, ); this.noteGesture(operation); } this.markAction(before); return; } const entry = this.resolveRef(ref); const filling = action.kind === 'fill' || action.kind === 'clear'; const refuseFill = (binding: NodeBinding): EngineError => unsupported(`agent-device can only ${action.kind} editable fields; node ${binding.id} is ${binding.node.role ?? 'unknown'}`); if (filling && !entry.takesText) throw refuseFill(entry); if (action.kind === 'multiTap' && action.count > MAX_TAP_COUNT) { throw unsupported(`agent-device presses at most ${MAX_TAP_COUNT} times in a row; got a count of ${action.count}`); } const label = `perform ${action.kind}`; const client = this.requireClient(); // A toggle already in the wanted state sends nothing, so it neither waits // for a transition nor counts as an action the next control must wait on. if ((action.kind === 'check' || action.kind === 'uncheck') && entry.node.states?.checked === (action.kind === 'check')) { return; } const before = this.latestScreen; const run = async (): Promise => { let target = entry; if (filling) { if (deterministic) await this.waitForTransition(entry, operation, input); target = await this.relocated(entry, operation, input, true); if (!target.takesText) throw refuseFill(target); } else if (deterministic) { target = await this.settled(entry, operation, input); } if (deterministic) { target = await this.steadied(target, operation, input, filling); if (filling && !target.takesText) throw refuseFill(target); } switch (action.kind) { case 'tap': return input.press(client, { ...this.actionTarget(target, true), ...settle }); case 'focus': // A touch surface focuses by tapping, and a tap on anything but an // editable field activates it; focus is offered for fields only. if (target.node.role !== 'textbox') { throw unsupported(`agent-device can only focus editable fields; node ${target.id} is ${target.node.role ?? 'unknown'}`); } return input.press(client, { ...this.actionTarget(target), ...settle }); case 'doubleTap': return input.press(client, { ...this.actionTarget(target), count: 2, ...settle }); case 'multiTap': return input.press(client, { ...this.actionTarget(target), count: action.count, ...settle }); case 'longPress': return input.send( () => client.interactions.longPress({ ...this.actionTarget(target), ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }), action.durationMs ?? DEFAULT_LONG_PRESS_MS, ); case 'hover': return input.send(() => client.interactions.hover(this.actionTarget(target))); case 'fill': // oxlint-disable-next-line unicorn/no-array-fill-with-reference-type -- agent-device fill, not Array#fill return input.send(() => client.interactions.fill({ ...this.actionTarget(target), text: action.value, ...settle })); case 'clear': // oxlint-disable-next-line unicorn/no-array-fill-with-reference-type -- agent-device fill, not Array#fill return input.send(() => client.interactions.fill({ ...this.actionTarget(target), text: '', ...settle })); case 'check': case 'uncheck': { const wanted = action.kind === 'check'; const checked = target.node.states?.checked; // A toggle whose state the tree does not expose (a radio or checkbox // the app gives no checked state) // cannot be set, only flipped; flipping blind could undo a correct state. if (checked === undefined) { throw unsupported(`agent-device cannot read whether node ${target.id} is checked; tap it instead`); } if (checked === wanted) return undefined; return input.press(client, { ...this.actionTarget(target, true), ...settle }); } case 'press': return this.pressKey(client, target, action.key, settle, input); case 'swipe': { const rect = target.node.rect; if (rect === undefined) throw notActionable(`node ${target.id} has no bounds to swipe within`); if (target.originUnknown) { throw notActionable( `${label} failed: the ${ORIGIN_UNKNOWN_BOUNDS} Nothing was sent. Swipe the screen with screen.swipe({ direction }), or between screen points with screen.swipe({ from, to }) not taken from those bounds.`, ); } const stabilization = gestureStabilization(operation); const sent = await input.send(() => client.interactions.swipe({ ...swipeWithin(rect, action.direction, action.momentum), ...stabilization })); this.noteGesture(operation); return sent; } case 'scrollTo': return this.scrollToEdge(target, action.edge, operation, input); case 'dragTo': { // A test locates the drop target in a capture of its own, after the // source's; agent-device takes both refs from the newest one only. const source = this.current(target); const destination = this.current(this.resolveRef(action.target)); return input.send(() => client.interactions.drag({ source: this.actionTarget(source).ref, destination: this.actionTarget(destination).ref, }), ); } case 'scrollIntoView': case 'selectOption': case 'setInputFiles': case 'setInputFilePayloads': case 'blur': // Not in DEVICE_ACTIONS (actions.ts), so the harness never sends them; kept exhaustive. throw unsupported(`agent-device cannot perform "${action.kind}" on a device surface`); } }; try { await raceAbort(() => this.track(run()), operation.signal, label); } catch (cause) { throw staleOr(cause, label, this.where); } this.markAction(before); } /** * `scrollTo` on a device: drags toward `edge` inside a region (the node's * box, else the screen, clipped to the screen and cut off above the soft * keyboard) until a drag leaves what the region shows unchanged * (`dragToEdge`). The region is measured once, before the first drag: a * list's own label can change as it scrolls, and the node is never looked * up again once input went out. Each drag keeps agent-device's post-gesture * stabilization, which holds the next read until the content rests, so a * list still coasting is never read as at its edge. */ private async scrollToEdge(entry: NodeBinding | undefined, edge: ScrollEdge, operation: OperationContext, input: InputBudget): Promise { const client = this.requireClient(); const capture = async (): Promise<{ raw: RawSnapshot; projected: ProjectedScreen }> => { const raw = await this.snapshotOrEmpty(operation, false, input); return { raw, projected: this.project(raw) }; }; const first = await capture(); const region = this.scrollRegion(entry, first.raw, first.projected); // A capture that leaves nodes out never reads as unchanged, so it never ends the scroll. const signature = ({ raw, projected }: { raw: RawSnapshot; projected: ProjectedScreen }): string | undefined => isTruncated(raw) ? undefined : regionSignature(projected.index, region); const gesture = swipeWithin(region, EDGE_DIRECTION[edge], undefined); await dragToEdge({ drag: async (count) => { // A cancel that lands as a read finishes sends no further drag. if (operation.signal.aborted) throw new EngineError('CANCELLED', 'scrollTo cancelled', { retryable: false }); await input.send(() => client.interactions.swipe({ ...gesture, count, pauseMs: 0 })); }, read: async () => signature(await capture()), remainingMs: () => input.remainingMs(), }, signature(first)); } /** * Where `scrollTo` drags: the node's box, or the screen for the root, * clipped to the screen and cut off above the soft keyboard. Refuses, with * nothing sent, a node whose bounds may be window-local, a region with no * area, and a keyboard that is up with bounds the capture does not give. */ private scrollRegion(entry: NodeBinding | undefined, raw: RawSnapshot, projected: ProjectedScreen): Rect { const viewport = projected.viewport ?? this.knownViewport; let rect: Rect | undefined; if (entry === undefined) { rect = viewport === undefined ? undefined : { x: 0, y: 0, width: viewport.width, height: viewport.height }; } else { const found = this.refind(entry, projected.index); if (found === undefined) throw new EngineError('NODE_STALE', `node ${entry.id} is gone from the screen; re-resolve`, { retryable: true }); if (projected.originUnknown) { throw notActionable(`perform scrollTo failed: the ${ORIGIN_UNKNOWN_BOUNDS} Nothing was sent. Scroll the screen with screen.scrollTo(edge).`); } rect = found.node.rect; } const target = entry === undefined ? 'the screen' : `node ${entry.id}`; if (rect !== undefined && viewport !== undefined) rect = clipTo(rect, viewport); if (rect === undefined || rect.width < 1 || rect.height < 1) throw notActionable(`${target} has no bounds on screen to scroll within`); const keyboard = viewport === undefined ? undefined : keyboardTop(raw, viewport); if (keyboard === undefined && keyboardShowing(raw)) { throw notActionable('the soft keyboard is up and its bounds are unknown, so a drag could land on it; dismiss it first'); } const region = above(rect, keyboard); if (region.height < 1) throw notActionable(`the soft keyboard covers ${target}; dismiss it first`); return region; } /** * Keys on a touch surface, in the contract's key grammar: `Enter` submits * through the soft keyboard, `Space` and any single character are typed * into the focused field. agent-device exposes no key event bus, so * modifiers and the other named keys (`Escape`, `Tab`, `Backspace`, the * arrows) have nothing to land on and are refused. */ private async pressKey(client: AgentDeviceClient, entry: NodeBinding, key: string, settle: SettleOptions, input: InputBudget): Promise { const parsed = parseKey(key); if (parsed === undefined) { throw unsupported( `"${key}" is not a key: press takes one key in the form [Modifier+]...Key, a named key (${KEY_NAMES.join(', ')}) or one character`, ); } if (parsed.modifiers.length > 0) { throw unsupported(`agent-device cannot hold ${parsed.modifiers.join('+')} on a device surface; press the key alone`); } const enter = parsed.key.kind === 'named' && parsed.key.name === 'Enter'; if (!enter && parsed.key.kind === 'named' && parsed.key.name !== 'Space') { throw unsupported(`agent-device cannot press ${parsed.key.name} on a device surface; only Enter, Space, and single characters reach the soft keyboard`); } // A key reaches the field through the soft keyboard, which is up only // while the field holds focus. if (entry.node.role === 'textbox' && entry.node.states?.focused !== true) { await input.press(client, { ...this.actionTarget(entry), ...settle }); } if (enter) return input.send(() => client.command.keyboard({ action: 'enter' })); return input.send(() => client.interactions.type({ text: parsed.key.kind === 'char' ? parsed.key.char : ' ' })); } /** * One pointer action at a screen point in logical pixels, the space every * node's bounds are in, with no element resolved behind it. `settle` waits * for the UI to go quiet, as the node taps do. */ async performAt(point: ViewportPoint, action: PointerAction, operation: OperationContext, input: InputBudget): Promise { const settle = operation.origin === 'test' ? {} : this.settleOptions; const before = this.latestScreen; const label = `${action.kind} at point`; await this.command(label, (client) => pointerInteraction(client, point, action, settle, gestureStabilization(operation), input).catch(async (cause: unknown) => { if (action.kind !== 'swipeTo') throw cause; throw await refusedSwipePath(cause, label, action.durationMs !== undefined, () => this.viewport(operation, input)); }), operation.signal); if (action.kind === 'swipeTo') this.noteGesture(operation); this.markAction(before); } /** * Types into whatever holds focus through the device's text-input path; * agent-device's `type` lands on the focused field. `replace` is not a * device primitive without a target, so it is refused rather than faked: * the model clears a listed field by filling it by id. */ async typeText(text: string, options: { readonly replace: boolean }, operation: OperationContext, input: InputBudget): Promise { if (options.replace) { throw unsupported('agent-device cannot clear the focused field without a node; type into a listed field by id to replace its value'); } const before = this.latestScreen; await this.command('keyboard.type', (client) => input.send(() => client.interactions.type({ text })), operation.signal); this.markAction(before); } /** * One key to the focused field, with the same reach as a node press: Enter * submits through the soft keyboard, Space and single characters are typed. * Modifiers and the other named keys have no event bus to land on. */ async pressFocusedKey(key: string, operation: OperationContext, input: InputBudget): Promise { const parsed = parseKey(key); if (parsed === undefined) { throw unsupported( `"${key}" is not a key: press takes one key in the form [Modifier+]...Key, a named key (${KEY_NAMES.join(', ')}) or one character`, ); } if (parsed.modifiers.length > 0) { throw unsupported(`agent-device cannot hold ${parsed.modifiers.join('+')} on a device surface; press the key alone`); } const before = this.latestScreen; if (parsed.key.kind === 'named' && parsed.key.name === 'Enter') { await this.command('keyboard.press', (client) => input.send(() => client.command.keyboard({ action: 'enter' })), operation.signal); } else if (parsed.key.kind === 'char' || parsed.key.name === 'Space') { const text = parsed.key.kind === 'char' ? parsed.key.char : ' '; await this.command('keyboard.press', (client) => input.send(() => client.interactions.type({ text })), operation.signal); } else { throw unsupported(`agent-device cannot press ${parsed.key.name} on a device surface; only Enter, Space, and single characters reach the soft keyboard`); } this.markAction(before); } /** * Whether the soft keyboard is on screen, from a capture taken again while * the tree is sparse or the keyboard is still moving (see * {@link keyboardReading}): see {@link keyboardShownIn}. A capture that * cannot answer fails, with the reason, instead of guessing. * Changes nothing on the device. */ async keyboardShown(signal: AbortSignal, input: InputBudget): Promise { const { shown } = await this.keyboardReading(signal, input); if (typeof shown === 'boolean') return shown; throw new EngineError(shown.code, shown.message, { retryable: false }); } /** * A capture and what {@link keyboardShownIn} reads in it, captured again * while the keyboard reads as moving, as long as the budget allows. The * last reading is answered, settled or not. */ private async keyboardReading(signal: AbortSignal, input: InputBudget): Promise<{ readonly raw: RawSnapshot; readonly shown: boolean | KeyboardUnknown }> { let reading: { readonly raw: RawSnapshot; readonly shown: boolean | KeyboardUnknown } | undefined; let captureMs = 0; for (const backoffMs of KEYBOARD_SETTLE_BACKOFF_MS) { if (reading !== undefined) { // Another look must fit its wait and a capture as long as the last one, or it would time the call out. if (input.remainingMs() <= backoffMs + captureMs) return reading; await sleep(backoffMs, signal); } const startedAt = Date.now(); const raw = await this.snapshot(signal, false, input); captureMs = Date.now() - startedAt; reading = { raw, shown: keyboardShownIn(raw, isTruncated(raw)) }; if (typeof reading.shown === 'boolean' || reading.shown.settling !== true) return reading; } return reading!; } /** * Hides the soft keyboard, so a control it covered can be reached. * agent-device hides an Android keyboard itself and refuses every visible * iOS one, because a touch on the screen is a guess about it that * agent-device never makes on a caller's behalf. The engine * makes that guess, the way a user does and Maestro's `hideKeyboard` does, * in {@link dismissKeyboardByGesture}. */ async dismissKeyboard(signal: AbortSignal, input: InputBudget): Promise { const before = this.latestScreen; try { await this.command('keyboard.dismiss', (client) => input.send(() => client.command.keyboard({ action: 'dismiss' })), signal); } catch (cause) { if (!(cause instanceof EngineError && cause.code === 'UNSUPPORTED_CAPABILITY')) throw cause; await this.dismissKeyboardByGesture(signal, input); } this.markAction(before); } /** * A keyboard agent-device refuses goes the way a user sends it away: a short * drag on the screen, which a scroll view turns into a dismissal, each * followed by a fresh look at whether the keyboard is still there. * Horizontal first: on a vertical scroll view it is no scroll, so React * Native's scroll view takes it as the touch outside the keyboard that * dismisses by default, where a vertical drag scrolls the content and * dismisses only under `keyboardDismissMode="on-drag"`. Vertical second, * for the scroll views that dismiss on a drag alone. Maestro's * `hideKeyboard` drags in the other order, and on a React Native screen * that costs a drag plus the settle after it. The simulator's "Speed up * your typing" tip, which sits over a keyboard the first time it appears, * goes through its Continue button first. A drag that starts on a control * presses it (a horizontal one is no scroll, so the control keeps the * touch), so each drag starts where the latest capture shows none, inside * a scroll view when the screen has one, see {@link keyboardDragStart}, and * a screen with no such point is refused rather than touched. The sequence stops the moment the keyboard is gone, * and a keyboard that outlives both drags fails naming what does work. * Each look is the observation's own capture, sparse-tree retries * included: a one-node tree has no keys and would pass for a dismissed * keyboard. */ private async dismissKeyboardByGesture(signal: AbortSignal, input: InputBudget): Promise { let reading = await this.keyboardReading(signal, input); if (await this.dismissKeyboardTip(reading.raw, signal, input)) reading = await this.keyboardReading(signal, input); if (reading.shown !== true) return; for (const axis of ['horizontal', 'vertical'] as const) { const { raw } = reading; const projected = projectSnapshot(raw.nodes ?? [], { mintId: () => 'keyboard', viewport: raw.viewport }); const viewport = await this.viewportFor(projected.viewport, signal, input); const top = keyboardTop(raw, viewport); if (top === undefined) { throw new EngineError( 'UNSUPPORTED_CAPABILITY', `keyboard dismissal failed: agent-device reports the keyboard up without a frame or any keyboard element on screen, so a drag could start on the keyboard. ${KEYBOARD_ALTERNATIVES}`, { retryable: false }, ); } const from = keyboardDragStart(projected, viewport, top); if (from === undefined) { throw new EngineError( 'UNSUPPORTED_CAPABILITY', `keyboard dismissal failed: every point above the keyboard (in a scroll view, when the screen has one) is on a control, so a drag would press one. ${KEYBOARD_ALTERNATIVES}`, { retryable: false }, ); } const to = axis === 'horizontal' ? { x: from.x - viewport.width * KEYBOARD_DRAG_RATIO, y: from.y } : { x: from.x, y: from.y - viewport.height * KEYBOARD_DRAG_RATIO }; await this.command('keyboard.dismiss', (client) => input.send(() => client.interactions.swipe({ from, to })), signal); reading = await this.keyboardReading(signal, input); if (reading.shown !== true) return; } throw new EngineError( 'UNSUPPORTED_CAPABILITY', `keyboard dismissal failed: the keyboard stayed up through a horizontal and a vertical drag. ${KEYBOARD_ALTERNATIVES}`, { retryable: false }, ); } /** * The simulator shows a "Speed up your typing" tip over the keyboard the * first time it appears; its Continue button is the only way past it, and * Maestro's `hideKeyboard` presses it too. Answers whether it pressed. */ private async dismissKeyboardTip(raw: RawSnapshot, signal: AbortSignal, input: InputBudget): Promise { const nodes = raw.nodes ?? []; const tip = nodes.find((node) => (node.label ?? node.value ?? '').startsWith('Speed up your typing')); if (tip?.rect === undefined) return false; const tipTop = tip.rect.y; const button = nodes.find((node) => node.label === 'Continue' && node.rect !== undefined && node.rect.y > tipTop); if (button?.rect === undefined) return false; await this.command('keyboard.dismiss', (client) => input.press(client, centreOf(button.rect!)), signal); return true; } async back(operation: OperationContext, input: InputBudget): Promise { const settle = operation.origin === 'test' ? {} : this.settleOptions; const before = this.latestScreen; await this.command('back', (client) => input.send(() => client.command.back({ ...settle })), operation.signal); this.markAction(before); } async restart(operation: OperationContext): Promise { const app = this.pinnedApp; if (app === undefined) throw unsupported(`launching the app needs the target's \`app.bundleId\`, or ${UNINSTALLED_BUILD}`); await this.openApp(app, { relaunch: true }, operation.signal); } /** Clears the pinned app's persisted state and relaunches it: the device equivalent of a fresh context. */ async reset(operation: OperationContext): Promise { const app = this.pinnedApp; if (app === undefined) throw unsupported(`app.clearState needs the target's \`app.bundleId\`, or ${UNINSTALLED_BUILD}`); await this.command( 'clear app state', (client) => client.settings.update({ ...this.selection(), setting: 'clear-app-state', state: 'clear', app }), operation.signal, ); await this.openApp(app, { relaunch: true }, operation.signal); } /** * Sends a foldable simulator's or emulator's hinge to a pose; agent-device * confirms it before it answers: the hinge angle through CoreDevice on iOS, * the device state the guest commits on Android. The pose moves the app to * another panel, so it counts as an action like a rotation. A device * without a hinge comes back from agent-device as `UNSUPPORTED_OPERATION`. */ async fold(pose: FoldPose, signal: AbortSignal): Promise { await this.screenCommand('device.fold', (client) => client.command.fold({ ...this.selection(), pose }), signal); } /** * Resets the simulator's keychain through agent-device. simctl resets the * whole simulator's, not one app's, and only a simulator has one to reset: * Android is refused before any device command. */ async clearKeychain(signal: AbortSignal): Promise { if (this.options.platform !== 'ios') { throw unsupported('device.clearKeychain resets an iOS simulator keychain; Android has none to reset'); } await this.command( 'device.clearKeychain', (client) => client.settings.update({ ...this.selection(), setting: 'reset-keychain', state: 'clear' }), signal, ); } /** * A redacted screenshot artifact. The device paints secure fields as dots, * but the last typed character shows in clear, so every secure node's * bounds are painted over before the file is kept. A secure node without * bounds cannot be masked, so the screenshot is refused with POLICY_DENIED, * and an image that cannot be redacted is not written at all. */ async screenshot(label: string | undefined, operation: OperationContext, budget: InputBudget): Promise { const attempt = this.attempt; if (attempt === undefined) throw invalidState('screenshot outside an attempt'); const masked = await this.maskedScreenshot(operation, budget); attempt.screenshots += 1; const name = `${String(attempt.screenshots).padStart(3, '0')}-${sanitizeFilename(label ?? 'screenshot')}.png`; const relative = path.join('screenshots', name); mkdirSync(path.join(attempt.artifactsDir, 'screenshots'), { recursive: true }); writeFileSync(path.join(attempt.artifactsDir, relative), masked.data); return relative; } /** Raw device pixels; cleanup follows the capture even when its caller abandons it. */ private rawScreenshot(signal: AbortSignal, capture: ScreenshotCapture, budget: InputBudget): Promise { return this.captureScreenshot(signal, async (shot, file) => new Uint8Array(readFileSync(shot.path ?? file)), capture, budget); } /** * One screenshot into a temp directory that is removed once `read` has * taken what it needs from the response or the file, even when the caller * abandons the capture. */ private captureScreenshot( signal: AbortSignal, read: (shot: RawScreenshotResult, file: string) => Promise, capture: ScreenshotCapture, budget: InputBudget, ): Promise { return budget.read(() => this.command('screenshot', async (client) => { const directory = mkdtempSync(path.join(tmpdir(), 'e2e-agent-device-')); const file = path.join(directory, 'screenshot.png'); try { return await read(await client.capture.screenshot({ path: file, ...(capture.normalizeStatusBar === true ? { normalizeStatusBar: true } : {}) }), file); } finally { rmSync(directory, { recursive: true, force: true }); } }, signal), ); } /** * Screenshot with every secure node on the current screen painted over. * Observes first so the regions describe the screen the pixels show; * throws when a secure field cannot be covered, because an image that may * hold a credential must not leave the engine. */ private async maskedScreenshot(operation: OperationContext, budget: InputBudget): Promise<{ data: Uint8Array; masked: number }> { const secure = secureBounds(this.project(await this.snapshotOrEmpty(operation, false, budget))); if (secure === undefined) { throw new ConfigurationError('POLICY_DENIED', 'a secure field on screen has no bounds to mask, so the screenshot is withheld'); } const data = await this.rawScreenshot(operation.signal, {}, budget); const masked = redactSecure(data, secure, this.knownViewport); if (masked === undefined) { throw new EngineError('ENGINE_FAILURE', 'the screenshot could not be read to mask the secure fields on screen; screenshot withheld', { retryable: false, }); } return masked; } /** * Viewport pixels for an observation. Best-effort: a screenshot that cannot * be produced or redacted costs the observation its image, not the step, * unless the operation's budget ran out. A screen with a secure field that * has no bounds to mask takes none and reports no regions masked, so the * harness knows the pixels were withheld. */ private async capturePixels( operation: OperationContext, projected: ProjectedSnapshot, viewport: ViewportSize, capture: ScreenshotCapture, budget: InputBudget, ): Promise<{ pixels?: ObservationPixels; masked: number } | undefined> { const secure = secureBounds(projected); if (secure === undefined) return { masked: 0 }; let raw: Uint8Array; try { raw = await this.rawScreenshot(operation.signal, capture, budget); } catch (cause) { if (cause instanceof EngineError && cause.code === 'OPERATION_TIMEOUT') throw cause; return undefined; } const redacted = redactSecure(raw, secure, viewport); if (redacted === undefined) return undefined; const size = readPngSize(redacted.data); if (size === undefined) return undefined; const scale = viewport.width > 0 ? size.width / viewport.width : 1; return { pixels: { data: redacted.data, mediaType: 'image/png', width: size.width, height: size.height, scale }, masked: redacted.masked, }; } } /** * The bounds of every secure node on the screen, in logical points, or * undefined when one has none: no screenshot of that screen can be masked. */ function secureBounds(projected: ProjectedSnapshot): readonly Rect[] | undefined { const bounds: Rect[] = []; for (const entry of projected.index) { if (entry.node.states?.secure !== true) continue; if (entry.node.rect === undefined) return undefined; bounds.push(entry.node.rect); } return bounds; } /** * Paints the secure bounds black on a screenshot of the same screen. * Returns the masked bytes and how many regions were covered, or undefined * when the image cannot be read or edited: the caller then withholds the * image rather than ship one it could not prove redacted. Bounds are in * logical points; the image may be at device scale, so they are scaled by * the image-to-viewport ratio. */ function redactSecure( data: Uint8Array, secure: readonly Rect[], viewport: ViewportSize | undefined, ): { data: Uint8Array; masked: number } | undefined { if (secure.length === 0) return { data, masked: 0 }; const size = readPngSize(data); if (size === undefined) return undefined; const scale = viewport !== undefined && viewport.width > 0 ? size.width / viewport.width : 1; const rects = secure.map((rect) => ({ x: rect.x * scale, y: rect.y * scale, width: rect.width * scale, height: rect.height * scale })); try { return { data: maskPng(data, rects), masked: rects.length }; } catch { return undefined; } }