@e2edev/mobile 0.8.0-canary-20260921180210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +149 -0
  4. package/dist/.build.json +1 -0
  5. package/dist/actions.d.ts +29 -0
  6. package/dist/actions.d.ts.map +1 -0
  7. package/dist/actions.js +62 -0
  8. package/dist/actions.js.map +1 -0
  9. package/dist/bindings.d.ts +57 -0
  10. package/dist/bindings.d.ts.map +1 -0
  11. package/dist/bindings.js +79 -0
  12. package/dist/bindings.js.map +1 -0
  13. package/dist/device.d.ts +77 -0
  14. package/dist/device.d.ts.map +1 -0
  15. package/dist/device.js +101 -0
  16. package/dist/device.js.map +1 -0
  17. package/dist/engine.d.ts +17 -0
  18. package/dist/engine.d.ts.map +1 -0
  19. package/dist/engine.js +92 -0
  20. package/dist/engine.js.map +1 -0
  21. package/dist/errors.d.ts +30 -0
  22. package/dist/errors.d.ts.map +1 -0
  23. package/dist/errors.js +95 -0
  24. package/dist/errors.js.map +1 -0
  25. package/dist/index.d.ts +21 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +14 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/locate.d.ts +11 -0
  30. package/dist/locate.d.ts.map +1 -0
  31. package/dist/locate.js +115 -0
  32. package/dist/locate.js.map +1 -0
  33. package/dist/nodes.d.ts +86 -0
  34. package/dist/nodes.d.ts.map +1 -0
  35. package/dist/nodes.js +315 -0
  36. package/dist/nodes.js.map +1 -0
  37. package/dist/options.d.ts +93 -0
  38. package/dist/options.d.ts.map +1 -0
  39. package/dist/options.js +7 -0
  40. package/dist/options.js.map +1 -0
  41. package/dist/png.d.ts +4 -0
  42. package/dist/png.d.ts.map +1 -0
  43. package/dist/png.js +25 -0
  44. package/dist/png.js.map +1 -0
  45. package/dist/pool.d.ts +72 -0
  46. package/dist/pool.d.ts.map +1 -0
  47. package/dist/pool.js +185 -0
  48. package/dist/pool.js.map +1 -0
  49. package/dist/provider.d.ts +105 -0
  50. package/dist/provider.d.ts.map +1 -0
  51. package/dist/provider.js +98 -0
  52. package/dist/provider.js.map +1 -0
  53. package/dist/selector.d.ts +17 -0
  54. package/dist/selector.d.ts.map +1 -0
  55. package/dist/selector.js +84 -0
  56. package/dist/selector.js.map +1 -0
  57. package/dist/support.d.ts +58 -0
  58. package/dist/support.d.ts.map +1 -0
  59. package/dist/support.js +82 -0
  60. package/dist/support.js.map +1 -0
  61. package/dist/surface.d.ts +243 -0
  62. package/dist/surface.d.ts.map +1 -0
  63. package/dist/surface.js +837 -0
  64. package/dist/surface.js.map +1 -0
  65. package/dist/tools.d.ts +24 -0
  66. package/dist/tools.d.ts.map +1 -0
  67. package/dist/tools.js +90 -0
  68. package/dist/tools.js.map +1 -0
  69. package/package.json +83 -0
@@ -0,0 +1,837 @@
1
+ /**
2
+ * The agent-device surface: one simulator or emulator session, driven through
3
+ * agent-device's typed client, exposed to the runner as the contract's
4
+ * observe/locate/perform members. It owns the id space (one fresh generation
5
+ * per observation), the attempt state (artifact directory, screenshot
6
+ * counter), and every translation between the contract's vocabulary and
7
+ * agent-device's commands. Its device and session come from the target's
8
+ * `DevicePool`, by worker slot. The runner owns everything else.
9
+ *
10
+ * Every observation is reported under one root of a stable id (`ROOT_ID`)
11
+ * wrapping the device's top-level elements; a `swipe` performed on that root
12
+ * scrolls the whole screen.
13
+ */
14
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
15
+ import { tmpdir } from 'node:os';
16
+ import path from 'node:path';
17
+ import { EngineError, KEY_NAMES, parseKey, raceAbort, withinCleanupBudget, ConfigurationError, } from 'e2e/engine';
18
+ import { runCommand, staleOr } from './errors.js';
19
+ import { pointerInteraction } from './actions.js';
20
+ import { resolveExpression } from './locate.js';
21
+ import { isWithin, projectSnapshot, ROOT_ID, screenRoot, screenTitle, } from './nodes.js';
22
+ import { maskPng } from './png.js';
23
+ import { pinnedApp } from './bindings.js';
24
+ import { DevicePool, deviceSelection } from './pool.js';
25
+ import { invalidState, notActionable, logicalScreenSize, readPngSize, sanitizeFilename, screenLocation, swipeWithin, unsupported, } from './support.js';
26
+ /**
27
+ * How long a control that appeared or moved with the last action is given to
28
+ * finish arriving before a test acts on it. Accessibility frames come from
29
+ * the model layer, which jumps to the final position the moment a transition
30
+ * starts, so the tree cannot tell a sliding control from a landed one; a
31
+ * modal or pushed screen keeps sliding for about half a second after the
32
+ * action that opened it, and a tap at a point the control has not reached
33
+ * yet lands on whatever is behind it. Controls that were already on screen
34
+ * at the same place before the action are acted on at once.
35
+ */
36
+ const DEFAULT_TRANSITION_MS = 500;
37
+ /** The centre of a rect in logical pixels. */
38
+ function centreOf(rect) {
39
+ return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
40
+ }
41
+ /** Whether two rects are the same to the pixel; a missing rect never matches, so a target must be measurable to be stable. */
42
+ function sameRect(a, b) {
43
+ if (a === undefined || b === undefined)
44
+ return false;
45
+ 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;
46
+ }
47
+ const MAX_LOCATED_REFS = 2048;
48
+ /**
49
+ * The Apple runner defers a full snapshot after slow accessibility work and
50
+ * returns a sparse one-node tree. Retrying device-side costs under a second;
51
+ * returning the sparse tree costs the model a confused turn.
52
+ */
53
+ const SPARSE_RETRY_BACKOFF_MS = [0, 1_200, 3_000];
54
+ /** Number of parent hops from `entry` up to `ancestor`. */
55
+ function depthBelow(entry, ancestor) {
56
+ let hops = 0;
57
+ for (let current = entry.parent; current !== undefined; current = current.parent) {
58
+ hops += 1;
59
+ if (current === ancestor)
60
+ return hops;
61
+ }
62
+ return hops;
63
+ }
64
+ function sleep(ms, signal) {
65
+ return new Promise((resolve) => {
66
+ const timer = setTimeout(done, ms);
67
+ function done() {
68
+ clearTimeout(timer);
69
+ signal.removeEventListener('abort', done);
70
+ resolve();
71
+ }
72
+ signal.addEventListener('abort', done, { once: true });
73
+ });
74
+ }
75
+ const DEFAULT_SETTLE_QUIET_MS = 150;
76
+ /** Resolves the `transition` option: the default budget or a custom one. */
77
+ function transitionMs(transition) {
78
+ const budget = transition ?? DEFAULT_TRANSITION_MS;
79
+ if (!Number.isInteger(budget) || budget < 0) {
80
+ throw new ConfigurationError('INVALID_CONFIG', 'mobile: `transition` must be a non-negative integer of milliseconds');
81
+ }
82
+ return budget;
83
+ }
84
+ /** Resolves the `settle` option: the default window, a custom one, or no wait at all. */
85
+ function settleOptions(settle) {
86
+ if (settle === false)
87
+ return {};
88
+ const quietMs = settle ?? DEFAULT_SETTLE_QUIET_MS;
89
+ if (!Number.isInteger(quietMs) || quietMs < 0) {
90
+ throw new ConfigurationError('INVALID_CONFIG', 'mobile: `settle` must be a non-negative integer of milliseconds, or false');
91
+ }
92
+ return { settle: true, settleQuietMs: quietMs };
93
+ }
94
+ export class AgentDeviceSurface {
95
+ options;
96
+ createClient;
97
+ client;
98
+ attempt;
99
+ /** The device this worker drives, the pool's entry for its slot; undefined leaves the choice to agent-device. */
100
+ device;
101
+ generation = new Map();
102
+ located = new Map();
103
+ idCounter = 0;
104
+ appIdentity;
105
+ /** The app the build `appPath` installed, once `init` has, itself or through a lease. */
106
+ installedApp;
107
+ /** Where relative build paths resolve; the run's project root once init has told us. */
108
+ projectRoot = process.cwd();
109
+ /**
110
+ * Commands still running on the device. agent-device takes no abort
111
+ * signal, so a cancelled or timed-out call is only abandoned by its
112
+ * caller; it keeps executing. The next attempt waits for these to settle
113
+ * before it opens anything, so a ghost tap can never land in a retry.
114
+ */
115
+ inflight = new Set();
116
+ /** The target's devices, one per worker slot; `init` takes this worker's from it. */
117
+ pool;
118
+ /** The settle wait every action carries: quiet window from the `settle` option, or nothing when it is `false`. */
119
+ settleOptions;
120
+ /** When this surface last acted on the device (an input or an app launch); the screen may be in transition for a while after. */
121
+ lastActionAt = 0;
122
+ /** The screen as last projected before that action, to tell controls that were already there from ones that came with it. */
123
+ indexBeforeAction;
124
+ /** The most recent projection of the screen, from any observe or locate. */
125
+ latestIndex;
126
+ /** Budget a control that came with the last action gets to finish arriving; see DEFAULT_TRANSITION_MS. */
127
+ transitionMs;
128
+ /**
129
+ * The screen's logical size as last learned from a snapshot with geometry
130
+ * or from the device itself, so a snapshot without geometry (an empty
131
+ * screen before any app is open, a sparse tree) still reports the viewport
132
+ * every observation must carry.
133
+ */
134
+ knownViewport;
135
+ constructor(options, createClient) {
136
+ this.options = options;
137
+ this.createClient = createClient;
138
+ this.pool = new DevicePool(options, createClient);
139
+ this.settleOptions = settleOptions(options.settle);
140
+ this.transitionMs = transitionMs(options.transition);
141
+ }
142
+ /** Whether the manifest declares app restart and state clearing. */
143
+ get managesApp() {
144
+ return this.options.app !== undefined || this.options.appPath !== undefined;
145
+ }
146
+ /** The app opened fresh per attempt: the `app` option, else the build `appPath` installed. */
147
+ get pinnedApp() {
148
+ return pinnedApp(this.options, this.installedApp);
149
+ }
150
+ /** Whether an attempt is running on this surface right now. */
151
+ get attemptRunning() {
152
+ return this.attempt !== undefined;
153
+ }
154
+ /** The live client; INVALID_STATE before init or after dispose. */
155
+ requireClient() {
156
+ if (this.client === undefined)
157
+ throw invalidState('the agent-device engine is not initialized');
158
+ return this.client;
159
+ }
160
+ /**
161
+ * Runs one agent-device command under an operation budget and translates
162
+ * its failure. Contributed-fixture methods route through here too, so the
163
+ * device fixture never carries its own error mapping.
164
+ */
165
+ async command(label, run, signal) {
166
+ const client = this.requireClient();
167
+ return runCommand(label, () => this.track(run(client)), signal ?? new AbortController().signal);
168
+ }
169
+ /** Registers one device command as in flight until it settles. */
170
+ track(pending) {
171
+ this.inflight.add(pending);
172
+ pending.then(() => this.inflight.delete(pending), () => this.inflight.delete(pending));
173
+ return pending;
174
+ }
175
+ /**
176
+ * Waits for every abandoned command to settle, within the caller's
177
+ * budget. A command that never settles fails the attempt launch instead of
178
+ * racing it: the launch timeout is the honest bound on a stuck device.
179
+ */
180
+ async settleInflight(signal) {
181
+ while (this.inflight.size > 0) {
182
+ await raceAbort(Promise.allSettled(this.inflight), signal, 'settling in-flight device commands');
183
+ }
184
+ }
185
+ /** The device selection this worker's commands take. */
186
+ selection() {
187
+ return deviceSelection(this.options.platform, this.device);
188
+ }
189
+ async init(info) {
190
+ this.projectRoot = info.projectRoot;
191
+ const binding = this.pool.binding(info.targetName, info.workerSlot, info.env);
192
+ this.device = binding?.device;
193
+ this.client ??= this.createClient(this.pool.session(info.targetName, info.workerSlot), binding?.daemon);
194
+ await this.command('boot', (client) => client.devices.boot(this.selection()), info.signal);
195
+ if (this.options.appPath === undefined)
196
+ return;
197
+ // A provider that installed the build itself says so on the binding; the worker then installs nothing.
198
+ this.installedApp =
199
+ binding?.installedApp ??
200
+ (await this.installApp(this.options.appPath, this.options.app === undefined ? {} : { app: this.options.app }, info.signal)).app;
201
+ }
202
+ async startAttempt(context) {
203
+ if (this.attempt !== undefined) {
204
+ throw invalidState('an attempt is already running on this agent-device engine');
205
+ }
206
+ await this.settleInflight(context.signal);
207
+ this.attempt = { artifactsDir: context.artifactsDir, screenshots: 0, video: undefined };
208
+ this.generation = new Map();
209
+ this.located.clear();
210
+ const app = this.pinnedApp;
211
+ if (app === undefined)
212
+ return;
213
+ await this.openApp(app, true, context.signal);
214
+ }
215
+ async endAttempt(context) {
216
+ const dangling = this.attempt?.video;
217
+ this.attempt = undefined;
218
+ this.generation = new Map();
219
+ this.located.clear();
220
+ // The harness stops the video before it ends the attempt; a recording still
221
+ // marked here belongs to an attempt cut short, or to a stop that failed,
222
+ // and the device must not keep recording into the next one. A start that
223
+ // outlived its budget may still be landing: it settles first, so the stop
224
+ // cannot overtake it.
225
+ if (dangling !== undefined) {
226
+ await this.settleInflight(context.signal).catch(() => undefined);
227
+ await this.command('stop video recording', (client) => client.recording.record({ action: 'stop' }), context.signal).catch(() => undefined);
228
+ }
229
+ }
230
+ // --- video ---
231
+ /**
232
+ * Asks the device to record its screen into the attempt directory. Taps stay
233
+ * visible in the recording (agent-device's touch indicator), which is the
234
+ * closest a phone comes to a cursor.
235
+ */
236
+ async startVideo(operation) {
237
+ const attempt = this.attempt;
238
+ if (attempt === undefined)
239
+ throw invalidState('startVideo outside an attempt');
240
+ if (attempt.video !== undefined)
241
+ throw invalidState('a video is already recording');
242
+ const relative = path.join('video', 'video.mp4');
243
+ const absolute = path.join(attempt.artifactsDir, relative);
244
+ mkdirSync(path.dirname(absolute), { recursive: true });
245
+ // Marked before the device is asked: a start that outlives its budget
246
+ // still records, and `endAttempt` must be able to stop it.
247
+ const recording = { relative, absolute, startedAt: new Date().toISOString() };
248
+ attempt.video = recording;
249
+ await this.command('start video recording', (client) => client.recording.record({ action: 'start', path: absolute, quality: 'medium' }), operation.signal);
250
+ // The device confirmed: it is recording from about now.
251
+ recording.startedAt = new Date().toISOString();
252
+ }
253
+ /** Stops the recording and returns its one segment, or none when the device wrote nothing. */
254
+ async stopVideo(operation) {
255
+ const attempt = this.attempt;
256
+ if (attempt === undefined)
257
+ throw invalidState('stopVideo outside an attempt');
258
+ const video = attempt.video;
259
+ if (video === undefined)
260
+ return [];
261
+ const result = await this.command('stop video recording', (client) => client.recording.record({ action: 'stop' }), operation.signal);
262
+ // Cleared only now: a stop that failed leaves the recording for `endAttempt`.
263
+ attempt.video = undefined;
264
+ // The device may finalize the file under a path of its own choosing; the
265
+ // artifact must live where the attempt directory expects it.
266
+ const written = typeof result.outPath === 'string' ? result.outPath : video.absolute;
267
+ if (written !== video.absolute && existsSync(written))
268
+ renameSync(written, video.absolute);
269
+ if (!existsSync(video.absolute))
270
+ return [];
271
+ return [{ path: video.relative, startedAt: video.startedAt }];
272
+ }
273
+ async dispose(context) {
274
+ const client = this.client;
275
+ this.client = undefined;
276
+ this.attempt = undefined;
277
+ this.generation = new Map();
278
+ this.located.clear();
279
+ this.appIdentity = undefined;
280
+ this.installedApp = undefined;
281
+ this.knownViewport = undefined;
282
+ if (client === undefined)
283
+ return;
284
+ await withinCleanupBudget(client.sessions.close().catch(() => undefined), context);
285
+ }
286
+ /** Opens an app in the session, remembering its identity for the path anchor. */
287
+ async openApp(app, relaunch, signal) {
288
+ const result = await this.command(`open ${app}`, (client) => client.apps.open({
289
+ app,
290
+ ...this.selection(),
291
+ ...(relaunch ? { relaunch: true } : {}),
292
+ }), signal);
293
+ // A launch has no screen before it worth matching against: every control
294
+ // of the new screen is arriving, whatever the previous one looked like.
295
+ this.markAction(undefined);
296
+ this.appIdentity = result.appBundleId ?? result.appName ?? app;
297
+ this.generation = new Map();
298
+ this.located.clear();
299
+ }
300
+ /**
301
+ * Installs a build on the session's device. `reinstall` removes the app
302
+ * named by `options.app` (else the pinned app) first, so the build starts
303
+ * with no data; a plain install replaces the binary and keeps its data.
304
+ */
305
+ async installApp(appPath, options, signal) {
306
+ const resolved = path.resolve(this.projectRoot, appPath);
307
+ const selection = this.selection();
308
+ const app = options.app ?? (options.reinstall === true ? this.pinnedApp : undefined);
309
+ if (options.reinstall === true && app === undefined) {
310
+ throw invalidState('reinstall needs an app: pass `app`, or pin one with the engine option `app` or `appPath`');
311
+ }
312
+ const result = (await this.command(`install ${resolved}`, (client) => options.reinstall === true && app !== undefined
313
+ ? client.apps.reinstall({ ...selection, app, appPath: resolved })
314
+ : client.apps.install({ ...selection, ...(app === undefined ? {} : { app }), appPath: resolved }), signal));
315
+ const identity = result.bundleId ?? result.package ?? result.appId;
316
+ return { app: identity ?? result.app, ...(identity === undefined ? {} : { bundleId: identity }) };
317
+ }
318
+ async snapshot(operation, interactiveOnly) {
319
+ let last = {};
320
+ for (const backoffMs of SPARSE_RETRY_BACKOFF_MS) {
321
+ if (backoffMs > 0)
322
+ await sleep(backoffMs, operation.signal);
323
+ if (operation.signal.aborted)
324
+ throw new EngineError('CANCELLED', 'snapshot cancelled', { retryable: false });
325
+ last = (await this.command('snapshot', (client) => client.capture.snapshot({ interactiveOnly }), operation.signal));
326
+ if (last.appBundleId !== undefined || last.appName !== undefined) {
327
+ this.appIdentity = last.appBundleId ?? last.appName;
328
+ }
329
+ if (last.snapshotQuality?.state !== 'sparse')
330
+ return last;
331
+ }
332
+ return last;
333
+ }
334
+ /**
335
+ * Snapshot for an observation. Without a pinned app, an observation before
336
+ * anything is open is an empty screen rather than a fault: the model's next
337
+ * move is the open tool, and failing the step would take that move away.
338
+ */
339
+ async snapshotOrEmpty(operation, interactiveOnly) {
340
+ try {
341
+ return await this.snapshot(operation, interactiveOnly);
342
+ }
343
+ catch (cause) {
344
+ if (!this.managesApp && cause instanceof EngineError && cause.code === 'INVALID_STATE')
345
+ return { nodes: [] };
346
+ throw cause;
347
+ }
348
+ }
349
+ project(raw) {
350
+ const projected = projectSnapshot(raw.nodes ?? [], {
351
+ mintId: () => {
352
+ this.idCounter += 1;
353
+ return `n${this.idCounter}`;
354
+ },
355
+ });
356
+ this.latestIndex = projected.index;
357
+ if (projected.viewport !== undefined)
358
+ this.knownViewport = projected.viewport;
359
+ return projected;
360
+ }
361
+ /**
362
+ * The viewport of a snapshot: its own geometry, else the last one this
363
+ * session learned, else the device's logical screen size read off one
364
+ * screenshot. A device whose size cannot be learned fails the observation:
365
+ * the harness measures every rect and point against the viewport, so an
366
+ * invented one would misplace every tap.
367
+ */
368
+ async viewportFor(projected, operation) {
369
+ const known = projected.viewport ?? this.knownViewport;
370
+ if (known !== undefined)
371
+ return known;
372
+ const probed = await this.probeViewport(operation.signal);
373
+ if (probed === undefined) {
374
+ 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 });
375
+ }
376
+ this.knownViewport = probed;
377
+ return probed;
378
+ }
379
+ /** The device's logical screen size as its screenshot reports it; undefined when it reports none. */
380
+ async probeViewport(signal) {
381
+ const result = await this.captureScreenshot(signal, async (shot) => shot);
382
+ return logicalScreenSize(result);
383
+ }
384
+ async observe(operation, options) {
385
+ const raw = await this.snapshotOrEmpty(operation, this.options.snapshot === 'interactive');
386
+ const projected = this.project(raw);
387
+ this.generation = new Map(projected.index.map((entry) => [entry.id, this.bind(entry, projected.index)]));
388
+ const viewport = await this.viewportFor(projected, operation);
389
+ const location = screenLocation(raw.appBundleId ?? raw.appName ?? this.appIdentity, screenTitle(projected));
390
+ const capture = options?.pixels === true ? await this.capturePixels(operation, projected, viewport) : undefined;
391
+ return {
392
+ root: screenRoot(projected.roots, viewport),
393
+ viewport,
394
+ ...(location === undefined ? {} : { location }),
395
+ ...(capture === undefined ? {} : { pixels: capture.pixels, maskedRegionCount: capture.masked }),
396
+ };
397
+ }
398
+ /** Retains only action bindings for matches, independently of the observation generation. */
399
+ async locate(expression, operation) {
400
+ const raw = await this.snapshotOrEmpty(operation, false);
401
+ const projected = this.project(raw);
402
+ const matches = resolveExpression(expression, projected.index);
403
+ for (const entry of matches)
404
+ this.located.set(entry.id, this.bind(entry, projected.index));
405
+ for (const oldest of this.located.keys()) {
406
+ if (this.located.size <= MAX_LOCATED_REFS)
407
+ break;
408
+ this.located.delete(oldest);
409
+ }
410
+ return matches.map((entry) => entry.node);
411
+ }
412
+ resolveRef(ref) {
413
+ const entry = this.located.get(ref.id) ?? this.generation.get(ref.id);
414
+ if (entry === undefined) {
415
+ throw new EngineError('NODE_STALE', `node ${ref.id} is not part of the newest observation`, { retryable: true });
416
+ }
417
+ return entry;
418
+ }
419
+ actionTarget(entry, control = false) {
420
+ const ref = control ? entry.controlRef : entry.ref;
421
+ if (ref === '')
422
+ throw notActionable(`node ${entry.id} has no agent-device ref to act on`);
423
+ return { ref: `@${ref}` };
424
+ }
425
+ /**
426
+ * The node a toggle press must land on. UIKit reports a settings row as a
427
+ * labelled `Switch` spanning the whole row with the real control as an
428
+ * unlabelled `Switch` child at its trailing edge; a press at the row's
429
+ * centre hits the label and changes nothing. The innermost same-role
430
+ * descendant with a ref is the control; a node without one is its own.
431
+ */
432
+ controlOf(entry, snapshot) {
433
+ const role = entry.node.role;
434
+ if (role !== 'switch' && role !== 'checkbox')
435
+ return entry;
436
+ let control = entry;
437
+ let depth = 0;
438
+ for (const candidate of snapshot) {
439
+ if (candidate.ref === '' || candidate.node.role !== role || !isWithin(candidate, entry))
440
+ continue;
441
+ const candidateDepth = depthBelow(candidate, entry);
442
+ if (candidateDepth > depth) {
443
+ control = candidate;
444
+ depth = candidateDepth;
445
+ }
446
+ }
447
+ return control;
448
+ }
449
+ /** Copies the fields actions use and pre-resolves a toggle's inner control. */
450
+ bind(entry, snapshot) {
451
+ const { children: _children, ...node } = entry.node;
452
+ const control = this.controlOf(entry, snapshot);
453
+ return { id: entry.id, ref: entry.ref, node, controlRef: control.ref };
454
+ }
455
+ /**
456
+ * The node a binding stands for, in a fresh snapshot: same role, same test
457
+ * id, same name and text, and of those the one closest to where it was.
458
+ */
459
+ refind(entry, index) {
460
+ const candidates = index.filter((candidate) => candidate.node.role === entry.node.role &&
461
+ candidate.node.testId === entry.node.testId &&
462
+ candidate.node.name === entry.node.name &&
463
+ candidate.node.text === entry.node.text);
464
+ if (candidates.length <= 1 || entry.node.rect === undefined)
465
+ return candidates[0];
466
+ const was = centreOf(entry.node.rect);
467
+ let best = candidates[0];
468
+ let bestDistance = Number.POSITIVE_INFINITY;
469
+ for (const candidate of candidates) {
470
+ if (candidate.node.rect === undefined)
471
+ continue;
472
+ const at = centreOf(candidate.node.rect);
473
+ const distance = Math.hypot(at.x - was.x, at.y - was.y);
474
+ if (distance < bestDistance) {
475
+ best = candidate;
476
+ bestDistance = distance;
477
+ }
478
+ }
479
+ return best;
480
+ }
481
+ /**
482
+ * Lets a control that came with the last action finish arriving before a
483
+ * test acts on it. A control already present at the same place in the
484
+ * snapshot the last action was resolved from is not in transition and is
485
+ * acted on at once; anything else waits out the remainder of the
486
+ * transition budget since that action. Nothing is observed here: the
487
+ * budget is the only signal, because the tree reports final frames.
488
+ */
489
+ async awaitTransition(entry, operation) {
490
+ const since = Date.now() - this.lastActionAt;
491
+ const remaining = this.transitionMs - since;
492
+ if (remaining <= 0)
493
+ return;
494
+ const before = this.indexBeforeAction;
495
+ if (before !== undefined) {
496
+ const prior = this.refind(entry, before);
497
+ if (prior !== undefined && sameRect(prior.node.rect, entry.node.rect))
498
+ return;
499
+ }
500
+ await sleep(remaining, operation.signal);
501
+ // The sleep resolves on abort; the action behind it must not go out once
502
+ // the caller has already been told the operation was cancelled.
503
+ if (operation.signal.aborted) {
504
+ throw new EngineError('CANCELLED', 'transition wait cancelled', { retryable: false });
505
+ }
506
+ }
507
+ /**
508
+ * Records an action the device received: the screen as it was projected
509
+ * before it, and when it returned. The transition budget counts from the
510
+ * return, since the input lands late in the command's own round trip.
511
+ */
512
+ markAction(before) {
513
+ this.indexBeforeAction = before;
514
+ this.lastActionAt = Date.now();
515
+ }
516
+ async perform(ref, action, operation) {
517
+ // The observation root is the screen: a swipe on it scrolls the whole
518
+ // viewport, which is the one action a screen takes.
519
+ if (ref.id === ROOT_ID) {
520
+ if (action.kind !== 'swipe')
521
+ throw notActionable(`the screen root takes swipe only, not ${action.kind}; act on a node`);
522
+ const before = this.latestIndex;
523
+ await this.command('swipe', (client) => client.interactions.scroll({ direction: action.direction }), operation.signal);
524
+ this.markAction(before);
525
+ return;
526
+ }
527
+ const entry = this.resolveRef(ref);
528
+ const label = `perform ${action.kind}`;
529
+ const client = this.requireClient();
530
+ // A test's step verifies its outcome with `expect`, so it never waits for
531
+ // the screen to settle afterwards; it only lets a control that came with
532
+ // the last action finish arriving. The agent reads the screen right after
533
+ // acting, so its actions settle first.
534
+ const deterministic = operation.origin === 'test';
535
+ const settle = deterministic ? {} : this.settleOptions;
536
+ // A toggle already in the wanted state sends nothing, so it neither waits
537
+ // for a transition nor counts as an action the next control must wait on.
538
+ if ((action.kind === 'check' || action.kind === 'uncheck') && entry.node.states?.checked === (action.kind === 'check')) {
539
+ return;
540
+ }
541
+ const before = this.latestIndex;
542
+ const run = async () => {
543
+ if (deterministic)
544
+ await this.awaitTransition(entry, operation);
545
+ switch (action.kind) {
546
+ case 'tap':
547
+ return client.interactions.press({ ...this.actionTarget(entry, true), ...settle });
548
+ case 'focus':
549
+ // A touch surface focuses by tapping, and a tap on anything but an
550
+ // editable field activates it; focus is offered for fields only.
551
+ if (entry.node.role !== 'textbox') {
552
+ throw unsupported(`agent-device can only focus editable fields; node ${entry.id} is ${entry.node.role ?? 'unknown'}`);
553
+ }
554
+ return client.interactions.press({ ...this.actionTarget(entry), ...settle });
555
+ case 'doubleTap':
556
+ return client.interactions.press({ ...this.actionTarget(entry), doubleTap: true, ...settle });
557
+ case 'longPress':
558
+ return client.interactions.longPress({
559
+ ...this.actionTarget(entry),
560
+ ...settle,
561
+ ...(action.durationMs === undefined ? {} : { durationMs: action.durationMs }),
562
+ });
563
+ case 'hover':
564
+ return client.interactions.hover(this.actionTarget(entry));
565
+ case 'fill':
566
+ // oxlint-disable-next-line unicorn/no-array-fill-with-reference-type -- agent-device fill, not Array#fill
567
+ return client.interactions.fill({ ...this.actionTarget(entry), text: action.value, ...settle });
568
+ case 'clear':
569
+ // oxlint-disable-next-line unicorn/no-array-fill-with-reference-type -- agent-device fill, not Array#fill
570
+ return client.interactions.fill({ ...this.actionTarget(entry), text: '', ...settle });
571
+ case 'check':
572
+ case 'uncheck': {
573
+ const wanted = action.kind === 'check';
574
+ const checked = entry.node.states?.checked;
575
+ // A toggle whose state the tree does not expose (Android switches)
576
+ // cannot be set, only flipped; flipping blind could undo a correct state.
577
+ if (checked === undefined) {
578
+ throw unsupported(`agent-device cannot read whether node ${entry.id} is checked; tap it instead`);
579
+ }
580
+ if (checked === wanted)
581
+ return undefined;
582
+ return client.interactions.press({ ...this.actionTarget(entry, true), ...settle });
583
+ }
584
+ case 'press':
585
+ return this.pressKey(client, entry, action.key, settle);
586
+ case 'swipe': {
587
+ const rect = entry.node.rect;
588
+ if (rect === undefined)
589
+ throw notActionable(`node ${entry.id} has no bounds to swipe within`);
590
+ return client.interactions.swipe(swipeWithin(rect, action.direction, action.momentum));
591
+ }
592
+ case 'dragTo': {
593
+ const destination = this.resolveRef(action.target);
594
+ return client.interactions.drag({
595
+ source: this.actionTarget(entry).ref,
596
+ destination: this.actionTarget(destination).ref,
597
+ });
598
+ }
599
+ case 'scrollIntoView':
600
+ case 'selectOption':
601
+ case 'setInputFiles':
602
+ // Not in DEVICE_ACTIONS (actions.ts), so the harness never sends them; kept exhaustive.
603
+ throw unsupported(`agent-device cannot perform "${action.kind}" on a device surface`);
604
+ }
605
+ };
606
+ try {
607
+ await raceAbort(() => this.track(run()), operation.signal, label);
608
+ }
609
+ catch (cause) {
610
+ throw staleOr(cause, label);
611
+ }
612
+ this.markAction(before);
613
+ }
614
+ /**
615
+ * Keys on a touch surface, in the contract's key grammar: `Enter` submits
616
+ * through the soft keyboard, `Space` and any single character are typed
617
+ * into the focused field. agent-device exposes no key event bus, so
618
+ * modifiers and the other named keys (`Escape`, `Tab`, `Backspace`, the
619
+ * arrows) have nothing to land on and are refused.
620
+ */
621
+ async pressKey(client, entry, key, settle) {
622
+ const parsed = parseKey(key);
623
+ if (parsed === undefined) {
624
+ 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`);
625
+ }
626
+ if (parsed.modifiers.length > 0) {
627
+ throw unsupported(`agent-device cannot hold ${parsed.modifiers.join('+')} on a device surface; press the key alone`);
628
+ }
629
+ if (parsed.key.kind === 'named' && parsed.key.name === 'Enter') {
630
+ return client.command.keyboard({ action: 'enter' });
631
+ }
632
+ if (parsed.key.kind === 'char' || parsed.key.name === 'Space') {
633
+ const text = parsed.key.kind === 'char' ? parsed.key.char : ' ';
634
+ if (entry.node.role === 'textbox' && entry.node.states?.focused !== true) {
635
+ await client.interactions.press({ ...this.actionTarget(entry), ...settle });
636
+ }
637
+ return client.interactions.type({ text });
638
+ }
639
+ throw unsupported(`agent-device cannot press ${parsed.key.name} on a device surface; only Enter, Space, and single characters reach the soft keyboard`);
640
+ }
641
+ /**
642
+ * One pointer action at a screen point in logical pixels, the space every
643
+ * node's bounds are in, with no element resolved behind it. `settle` waits
644
+ * for the UI to go quiet, as the node taps do.
645
+ */
646
+ async performAt(point, action, operation) {
647
+ const settle = operation.origin === 'test' ? {} : this.settleOptions;
648
+ const before = this.latestIndex;
649
+ await this.command(`${action.kind} at point`, (client) => pointerInteraction(client, point, action, settle), operation.signal);
650
+ this.markAction(before);
651
+ }
652
+ /**
653
+ * Types into whatever holds focus through the device's text-input path;
654
+ * agent-device's `type` lands on the focused field. `replace` is not a
655
+ * device primitive without a target, so it is refused rather than faked:
656
+ * the model clears a listed field by filling it by id.
657
+ */
658
+ async typeText(text, options, operation) {
659
+ if (options.replace) {
660
+ throw unsupported('agent-device cannot clear the focused field without a node; type into a listed field by id to replace its value');
661
+ }
662
+ const before = this.latestIndex;
663
+ await this.command('keyboard.type', (client) => client.interactions.type({ text }), operation.signal);
664
+ this.markAction(before);
665
+ }
666
+ /**
667
+ * One key to the focused field, with the same reach as a node press: Enter
668
+ * submits through the soft keyboard, Space and single characters are typed.
669
+ * Modifiers and the other named keys have no event bus to land on.
670
+ */
671
+ async pressFocusedKey(key, operation) {
672
+ const parsed = parseKey(key);
673
+ if (parsed === undefined) {
674
+ 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`);
675
+ }
676
+ if (parsed.modifiers.length > 0) {
677
+ throw unsupported(`agent-device cannot hold ${parsed.modifiers.join('+')} on a device surface; press the key alone`);
678
+ }
679
+ const before = this.latestIndex;
680
+ if (parsed.key.kind === 'named' && parsed.key.name === 'Enter') {
681
+ await this.command('keyboard.press', (client) => client.command.keyboard({ action: 'enter' }), operation.signal);
682
+ }
683
+ else if (parsed.key.kind === 'char' || parsed.key.name === 'Space') {
684
+ const text = parsed.key.kind === 'char' ? parsed.key.char : ' ';
685
+ await this.command('keyboard.press', (client) => client.interactions.type({ text }), operation.signal);
686
+ }
687
+ else {
688
+ throw unsupported(`agent-device cannot press ${parsed.key.name} on a device surface; only Enter, Space, and single characters reach the soft keyboard`);
689
+ }
690
+ this.markAction(before);
691
+ }
692
+ /** Hides the soft keyboard, so a control it covered can be reached. */
693
+ async dismissKeyboard(operation) {
694
+ const before = this.latestIndex;
695
+ await this.command('keyboard.dismiss', (client) => client.command.keyboard({ action: 'dismiss' }), operation.signal);
696
+ this.markAction(before);
697
+ }
698
+ async back(operation) {
699
+ const settle = operation.origin === 'test' ? {} : this.settleOptions;
700
+ const before = this.latestIndex;
701
+ await this.command('back', (client) => client.command.back({ ...settle }), operation.signal);
702
+ this.markAction(before);
703
+ }
704
+ async restart(operation) {
705
+ const app = this.pinnedApp;
706
+ if (app === undefined)
707
+ throw unsupported('app.restart needs the engine option `app` or `appPath`');
708
+ await this.openApp(app, true, operation.signal);
709
+ }
710
+ /** Clears the pinned app's persisted state and relaunches it: the device equivalent of a fresh context. */
711
+ async reset(operation) {
712
+ const app = this.pinnedApp;
713
+ if (app === undefined)
714
+ throw unsupported('app.clearState needs the engine option `app` or `appPath`');
715
+ await this.command('clear app state', (client) => client.settings.update({ setting: 'clear-app-state', state: 'clear', app }), operation.signal);
716
+ await this.openApp(app, true, operation.signal);
717
+ }
718
+ /**
719
+ * A redacted screenshot artifact. The device paints secure fields as dots,
720
+ * but the last typed character shows in clear, so every secure node's
721
+ * bounds are painted over before the file is kept. A secure node without
722
+ * bounds cannot be masked, and an image that cannot be redacted is not
723
+ * written at all.
724
+ */
725
+ async screenshot(label, operation) {
726
+ const attempt = this.attempt;
727
+ if (attempt === undefined)
728
+ throw invalidState('screenshot outside an attempt');
729
+ const masked = await this.maskedScreenshot(operation.signal);
730
+ attempt.screenshots += 1;
731
+ const name = `${String(attempt.screenshots).padStart(3, '0')}-${sanitizeFilename(label ?? 'screenshot')}.png`;
732
+ const relative = path.join('screenshots', name);
733
+ mkdirSync(path.join(attempt.artifactsDir, 'screenshots'), { recursive: true });
734
+ writeFileSync(path.join(attempt.artifactsDir, relative), masked.data);
735
+ return relative;
736
+ }
737
+ /** Raw device pixels; cleanup follows the capture even when its caller abandons it. */
738
+ rawScreenshot(signal) {
739
+ return this.captureScreenshot(signal, async (shot, file) => new Uint8Array(readFileSync(shot.path ?? file)));
740
+ }
741
+ /**
742
+ * One screenshot into a temp directory that is removed once `read` has
743
+ * taken what it needs from the response or the file, even when the caller
744
+ * abandons the capture.
745
+ */
746
+ captureScreenshot(signal, read) {
747
+ return this.command('screenshot', async (client) => {
748
+ const directory = mkdtempSync(path.join(tmpdir(), 'e2e-agent-device-'));
749
+ const file = path.join(directory, 'screenshot.png');
750
+ try {
751
+ return await read((await client.capture.screenshot({ path: file })), file);
752
+ }
753
+ finally {
754
+ rmSync(directory, { recursive: true, force: true });
755
+ }
756
+ }, signal);
757
+ }
758
+ /**
759
+ * Screenshot with every secure node on the current screen painted over.
760
+ * Observes first so the regions describe the screen the pixels show;
761
+ * throws when a secure field cannot be covered, because an image that may
762
+ * hold a credential must not leave the engine.
763
+ */
764
+ async maskedScreenshot(signal) {
765
+ const operation = {
766
+ signal: signal ?? new AbortController().signal,
767
+ timeoutMs: 30_000,
768
+ runId: '',
769
+ attemptId: '',
770
+ origin: 'test',
771
+ };
772
+ const projected = this.project(await this.snapshotOrEmpty(operation, false));
773
+ const data = await this.rawScreenshot(signal);
774
+ const masked = redactSecure(data, projected, projected.viewport ?? this.knownViewport);
775
+ if (masked === undefined) {
776
+ throw new EngineError('ENGINE_FAILURE', 'a secure field on screen could not be masked; screenshot withheld', {
777
+ retryable: false,
778
+ });
779
+ }
780
+ return masked;
781
+ }
782
+ /**
783
+ * Viewport pixels for an observation. Best-effort: a screenshot that cannot
784
+ * be produced or redacted costs the observation its image, not the step.
785
+ */
786
+ async capturePixels(operation, projected, viewport) {
787
+ let raw;
788
+ try {
789
+ raw = await this.rawScreenshot(operation.signal);
790
+ }
791
+ catch {
792
+ return undefined;
793
+ }
794
+ const redacted = redactSecure(raw, projected, viewport);
795
+ if (redacted === undefined)
796
+ return undefined;
797
+ const size = readPngSize(redacted.data);
798
+ if (size === undefined)
799
+ return undefined;
800
+ const scale = viewport.width > 0 ? size.width / viewport.width : 1;
801
+ return {
802
+ pixels: { data: redacted.data, mediaType: 'image/png', width: size.width, height: size.height, scale },
803
+ masked: redacted.masked,
804
+ };
805
+ }
806
+ }
807
+ /**
808
+ * Paints every secure node's bounds black on a screenshot of the same
809
+ * screen. Returns the masked bytes and how many regions were covered, or
810
+ * undefined when a secure node has no bounds or the image format cannot be
811
+ * edited: the caller then withholds the image rather than ship one it could
812
+ * not prove redacted. Bounds are in logical points; the image may be at
813
+ * device scale, so they are scaled by the image-to-viewport ratio.
814
+ */
815
+ function redactSecure(data, projected, viewport) {
816
+ const secure = projected.index.filter((entry) => entry.node.states?.secure === true);
817
+ if (secure.length === 0)
818
+ return { data, masked: 0 };
819
+ const size = readPngSize(data);
820
+ if (size === undefined)
821
+ return undefined;
822
+ const scale = viewport !== undefined && viewport.width > 0 ? size.width / viewport.width : 1;
823
+ const rects = [];
824
+ for (const entry of secure) {
825
+ const rect = entry.node.rect;
826
+ if (rect === undefined)
827
+ return undefined;
828
+ rects.push({ x: rect.x * scale, y: rect.y * scale, width: rect.width * scale, height: rect.height * scale });
829
+ }
830
+ try {
831
+ return { data: maskPng(data, rects), masked: rects.length };
832
+ }
833
+ catch {
834
+ return undefined;
835
+ }
836
+ }
837
+ //# sourceMappingURL=surface.js.map