Repository navigation
Expand file tree
/
Copy pathinteractions.ts
More file actions
482 lines (459 loc) · 14.7 KB
/
Copy pathinteractions.ts
File metadata and controls
482 lines (459 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime';
import type { BackMode } from '@agent-device/contracts/back-mode';
import { singlePointerPlanEndpoints } from '@agent-device/contracts/gesture-plan';
import type { GesturePlan } from '@agent-device/contracts/gesture-plan-types';
import {
type Interactor,
type PressPointOptions,
type RunnerCallOptions,
type RunnerContext,
TEXT_ENTRY_ROUTES,
type TextEntryRoute,
type TypeTextBackendResult,
} from '@agent-device/contracts/interactor-types';
import { macOsHelperSurface, type MacOsHelperSurface } from '@agent-device/contracts/session';
import {
SCROLL_DURATION_MAX_MS,
normalizeScrollDurationMs,
} from '@agent-device/contracts/scroll-command';
import {
type ScrollDirection,
assertScrollGestureInput,
} from '@agent-device/contracts/scroll-gesture';
import { assertAppleMultiTouchSupported } from './multitouch-support.ts';
import {
isMacOs,
isTvOsDevice,
runnerSynthesizesTap,
type DeviceInfo,
} from '@agent-device/kernel/device';
import { isAppleApplicationState } from '@agent-device/kernel/snapshot';
import { AppError } from '@agent-device/kernel/errors';
import { runAppleRunnerCommand, runApplePressSeries } from './core/runner-client.ts';
import {
buildRunnerSequenceCommand,
parseRunnerSequenceResult,
type RunnerCommand,
} from './runner/index.ts';
import {
materializeIosScrollOptions,
normalizeAppleScrollResult,
normalizeAppleScrollResultWithResolvedFrame,
scrollRunnerFields,
withAppleScrollKeyboardOcclusion,
type AppleScrollOptions,
} from './core/scroll.ts';
import { runMacosDesktopScroll } from './os/macos/desktop-scroll.ts';
import { appleRemotePressCommand } from './os/tvos/remote.ts';
export type AppleBackRunnerCommand = 'backInApp' | 'backSystem';
type RunAppleRunnerCommand = typeof runAppleRunnerCommand;
type RunnerOpts = RunnerCallOptions;
type IosRunnerOverrides = Pick<
Interactor,
| 'tap'
| 'pressPoint'
| 'tapElementSelector'
| 'doubleTap'
| 'longPress'
| 'appState'
| 'focus'
| 'type'
| 'fill'
| 'scroll'
| 'performGesture'
| 'gestureViewport'
>;
export function resolveAppleBackRunnerCommand(mode?: BackMode): AppleBackRunnerCommand {
if (mode === 'system') return 'backSystem';
return 'backInApp';
}
export function iosRunnerOverrides(
device: DeviceInfo,
ctx: RunnerContext,
): {
overrides: IosRunnerOverrides;
runnerOpts: RunnerOpts;
} {
const runnerOpts = {
signal: ctx.signal,
verbose: ctx.verbose,
logPath: ctx.logPath,
traceLogPath: ctx.traceLogPath,
requestId: ctx.requestId,
iosXctestrunFile: ctx.iosXctestrunFile,
iosXctestDerivedDataPath: ctx.iosXctestDerivedDataPath,
iosXctestEnvDir: ctx.iosXctestEnvDir,
runnerLeaseContext: ctx.runnerLeaseContext,
};
return {
runnerOpts,
overrides: {
tap: async (x, y) => {
return await runAppleRunnerCommand(device, iosTapCommand(device, ctx, x, y), runnerOpts);
},
pressPoint: async (point, options) =>
await runApplePressPoint(device, ctx, runnerOpts, point, options),
tapElementSelector: async (selector) => {
return await runAppleRunnerCommand(
device,
{
command: 'tap',
selectorKey: selector.key,
selectorValue: selector.value,
allowNonHittableCoordinateFallback: selector.allowNonHittableCoordinateFallback,
...(selector.expectedPoint
? { x: selector.expectedPoint.x, y: selector.expectedPoint.y }
: {}),
...(runnerSynthesizesTap(device) ? { synthesized: true } : {}),
appBundleId: ctx.appBundleId,
},
runnerOpts,
);
},
doubleTap: async (x, y) => {
// One-step `sequence` replaced the retired `tapSeries` double-tap vehicle; parsing the
// result surfaces a failed step as an AppError instead of an ok-shaped payload.
const runnerResult = await runAppleRunnerCommand(
device,
buildRunnerSequenceCommand([{ kind: 'doubleTap', x, y }], ctx.appBundleId),
runnerOpts,
);
parseRunnerSequenceResult(runnerResult);
return runnerResult;
},
appState: async () =>
readAppStateResult(
await runAppleRunnerCommand(
device,
{ command: 'appState', appBundleId: ctx.appBundleId },
runnerOpts,
),
),
longPress: async (x, y, durationMs) => {
return await runAppleRunnerCommand(
device,
{ command: 'longPress', x, y, durationMs, appBundleId: ctx.appBundleId },
runnerOpts,
);
},
focus: async (x, y) => {
return await runAppleRunnerCommand(device, iosTapCommand(device, ctx, x, y), runnerOpts);
},
type: async (text, delayMs) => {
return readTypeTextBackendResult(
await runAppleRunnerCommand(
device,
{
command: 'type',
text,
delayMs,
textEntryMode: text === '\n' ? undefined : 'append',
appBundleId: ctx.appBundleId,
},
runnerOpts,
),
);
},
fill: async (x, y, text, delayMs, options) => {
return await runAppleRunnerCommand(
device,
{
command: 'type',
x,
y,
text,
delayMs,
textEntryMode: 'replace',
...(options?.allowNonHittableCoordinateFallback
? { allowNonHittableCoordinateFallback: true }
: {}),
appBundleId: ctx.appBundleId,
},
runnerOpts,
);
},
scroll: async (direction, options) => {
return await runAppleScroll(
runAppleRunnerCommand,
device,
ctx,
runnerOpts,
direction,
options,
);
},
performGesture: async (plan) => await performGestureApple(device, ctx, runnerOpts, plan),
gestureViewport: async () => {
const result = await runAppleRunnerCommand(
device,
{ command: 'gestureViewport', appBundleId: ctx.appBundleId },
runnerOpts,
);
return readGestureViewport(result);
},
},
};
}
async function runApplePressPoint(
device: DeviceInfo,
context: RunnerContext,
runnerOpts: RunnerOpts,
point: { x: number; y: number },
options: PressPointOptions,
): Promise<Record<string, unknown>> {
// The runner owner's routing: an app session reaches here only on the XCTest backend.
const helper = isMacOs(device) ? macOsHelperSurface(options.surface, 'xctest') : undefined;
if (helper) {
return await runMacOsSurfacePress(context, point, options, helper);
}
if (options.button !== 'primary') {
return await runAppleAlternateClick(device, context, runnerOpts, point, options.button);
}
if (options.count === 1) {
return await runSingleApplePress(device, context, runnerOpts, point, options);
}
return await runApplePressSeries(
device,
point,
options,
context.appBundleId,
async (command) => await runAppleRunnerCommand(device, command, runnerOpts),
);
}
async function runMacOsSurfacePress(
context: RunnerContext,
point: { x: number; y: number },
options: PressPointOptions,
surface: MacOsHelperSurface,
): Promise<Record<string, unknown>> {
if (options.button !== 'primary') {
throw new AppError(
'UNSUPPORTED_OPERATION',
`${options.button} click is not supported on macOS ${surface} sessions.`,
);
}
const { runMacOsPressAction } = await import('./os/macos/helper.ts');
// `count` is independent presses and `doubleTap` raises the click state inside each one,
// the same reading every other platform gives the two flags.
const posted = await runMacOsPressAction(point.x, point.y, {
bundleId: context.appBundleId,
surface,
holdMs: options.holdMs,
clicks: options.count,
doubleClick: options.doubleTap,
intervalMs: options.intervalMs,
signal: context.signal,
});
// A hold shorter than what macOS delivers is raised before it is posted, so the
// response carries the hold the helper actually used rather than the request.
return posted.holdMs === undefined ? {} : { holdMs: posted.holdMs };
}
async function runAppleAlternateClick(
device: DeviceInfo,
context: RunnerContext,
runnerOpts: RunnerOpts,
point: { x: number; y: number },
button: 'secondary' | 'middle',
) {
return await runAppleRunnerCommand(
device,
{
command: 'mouseClick',
x: point.x,
y: point.y,
button,
appBundleId: context.appBundleId,
},
runnerOpts,
);
}
async function runSingleApplePress(
device: DeviceInfo,
context: RunnerContext,
runnerOpts: RunnerOpts,
point: { x: number; y: number },
options: PressPointOptions,
) {
if (options.doubleTap) {
const result = await runAppleRunnerCommand(
device,
buildRunnerSequenceCommand(
[{ kind: 'doubleTap', x: point.x, y: point.y }],
context.appBundleId,
),
runnerOpts,
);
parseRunnerSequenceResult(result);
return result;
}
if (options.holdMs > 0) {
return await runAppleRunnerCommand(
device,
{
command: 'longPress',
x: point.x,
y: point.y,
durationMs: options.holdMs,
appBundleId: context.appBundleId,
},
runnerOpts,
);
}
return await runAppleRunnerCommand(
device,
iosTapCommand(device, context, point.x, point.y),
runnerOpts,
);
}
/**
* The runner wire payload is untrusted JSON; this is the one place a `type`
* response becomes the typed {@link TypeTextBackendResult} its only consumer
* (the bound type-text runtime operation) reads.
*/
function readTypeTextBackendResult(result: Record<string, unknown>): TypeTextBackendResult {
const route = result.textEntryRoute;
return isTextEntryRoute(route) ? { textEntryRoute: route } : {};
}
/** The runner's `appState` payload is untrusted JSON; only a declared state name passes. */
function readAppStateResult(result: Record<string, unknown>): AppStateRuntimeResult {
const state = result.applicationState;
return isAppleApplicationState(state) ? { applicationState: state } : {};
}
function isTextEntryRoute(value: unknown): value is TextEntryRoute {
return typeof value === 'string' && (TEXT_ENTRY_ROUTES as readonly string[]).includes(value);
}
function readGestureViewport(result: Record<string, unknown>) {
const x = finiteNumber(result.x);
const y = finiteNumber(result.y);
const width = finiteNumber(result.x2);
const height = finiteNumber(result.y2);
if (
x === undefined ||
y === undefined ||
width === undefined ||
height === undefined ||
width <= 0 ||
height <= 0
) {
throw new AppError('COMMAND_FAILED', 'Apple runner returned an invalid gesture viewport');
}
return { x, y, width, height };
}
function finiteNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}
/** Executes the portable pointer plan without regenerating platform geometry. */
export async function performGestureApple(
device: DeviceInfo,
ctx: RunnerContext,
runnerOpts: RunnerOpts,
plan: GesturePlan,
): Promise<Record<string, unknown>> {
if (plan.topology === 'two') assertAppleMultiTouchSupported(device, plan.intent);
if (plan.topology === 'single' && isMacOs(device)) {
const { start: first, end: last } = singlePointerPlanEndpoints(plan);
return await runAppleRunnerCommand(
device,
{
command: 'drag',
x: first.x,
y: first.y,
x2: last.x,
y2: last.y,
durationMs: plan.durationMs,
appBundleId: ctx.appBundleId,
},
runnerOpts,
);
}
if (plan.topology === 'single' && isTvOsDevice(device)) {
const { start: first, end: last } = singlePointerPlanEndpoints(plan);
return await runAppleRunnerCommand(
device,
{ command: 'swipe', direction: dominantDirection(first, last), appBundleId: ctx.appBundleId },
runnerOpts,
);
}
return await runAppleRunnerCommand(
device,
{ command: 'gesture', gesturePlan: plan, appBundleId: ctx.appBundleId },
runnerOpts,
);
}
function dominantDirection(from: { x: number; y: number }, to: { x: number; y: number }) {
const dx = to.x - from.x;
const dy = to.y - from.y;
if (Math.abs(dx) >= Math.abs(dy)) return dx >= 0 ? ('right' as const) : ('left' as const);
return dy >= 0 ? ('down' as const) : ('up' as const);
}
function iosTapCommand(
device: DeviceInfo,
ctx: RunnerContext,
x: number,
y: number,
): RunnerCommand {
return {
command: 'tap',
x,
y,
...(runnerSynthesizesTap(device) ? { synthesized: true } : {}),
appBundleId: ctx.appBundleId,
};
}
async function runAppleScroll(
runRunnerCommand: RunAppleRunnerCommand,
device: DeviceInfo,
ctx: RunnerContext,
runnerOpts: RunnerOpts,
direction: ScrollDirection,
options?: AppleScrollOptions,
): Promise<Record<string, unknown>> {
normalizeScrollDurationMs(options?.durationMs, {
invalidMessage: `scroll durationMs must be a non-negative integer at most ${SCROLL_DURATION_MAX_MS}`,
});
if (isTvOsDevice(device)) {
const runnerResult = await runRunnerCommand(
device,
appleRemotePressCommand(direction, ctx.appBundleId, options?.durationMs),
runnerOpts,
);
return normalizeAppleScrollResult(runnerResult, {
amount: options?.amount,
durationMs: options?.durationMs,
});
}
// Validate amount/pixels up front so bad inputs throw INVALID_ARGS before any runner command
// is sent (previously validation ran between the frame request and the drag, so a bad amount
// could cost one runner request first).
assertScrollGestureInput(options ?? {});
if (isMacOs(device)) {
return await runMacosDesktopScroll(
runRunnerCommand,
device,
ctx,
runnerOpts,
direction,
options,
);
}
const iosOptions = materializeIosScrollOptions(options);
// Single fused lifecycle command: the runner resolves the interaction frame and runs the drag.
// The runner is also the only party holding the live keyboard frame, so a surface it refuses to
// swipe under the keys arrives here as its typed runner code and leaves as a typed reason (#2500).
let runnerResult: Record<string, unknown>;
try {
runnerResult = await runRunnerCommand(
device,
{
command: 'scroll',
direction,
...scrollRunnerFields(iosOptions),
appBundleId: ctx.appBundleId,
},
runnerOpts,
);
} catch (error) {
throw withAppleScrollKeyboardOcclusion(error);
}
return normalizeAppleScrollResultWithResolvedFrame(runnerResult, direction, iosOptions);
}