Repository navigation
Expand file tree
/
Copy pathinteractor.ts
More file actions
501 lines (483 loc) · 19 KB
/
Copy pathinteractor.ts
File metadata and controls
501 lines (483 loc) · 19 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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import { closeIosApp, openIosApp, openIosDevice } from './core/app-launch.ts';
import { readIosClipboardText, writeIosClipboardText } from './core/app-device-io.ts';
import { readIosSetting, setIosSetting } from './core/app-settings.ts';
import { captureScreenshotViaRunner, screenshotIos } from './core/screenshot.ts';
import { iosRunnerOverrides, resolveAppleBackRunnerCommand } from './interactions.ts';
import { appleRemotePressCommand } from './os/tvos/remote.ts';
import { runMacOsScreenshotAction } from './os/macos/helper.ts';
import { actOnAppleAlert, awaitAppleAlert, readAppleAlert } from './alert.ts';
import { runAppleRunnerCommand } from './core/runner-client.ts';
import {
withAppleRunnerProvider,
type AppleRunnerCommandExecutor,
type AppleRunnerProvider,
type RunnerCommand,
} from './runner/index.ts';
import { toAppleTvRemoteButton } from '@agent-device/contracts/tv-remote';
import { SCREENSHOT_FULLSCREEN_REASONS } from '@agent-device/contracts/capture';
import {
macOsHelperSurface,
type MacOsHelperSurface,
type SessionSurface,
} from '@agent-device/contracts/session';
import { DEVICE_ROTATIONS, type DeviceRotation } from '@agent-device/contracts/device';
import { normalizeSnapshotScope } from '@agent-device/contracts/snapshot';
import { withDiagnosticTimer } from '@agent-device/host-kit/diagnostics';
import { isMacOs, isTvOsDevice, type DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { withMethodScope } from '@agent-device/kernel/scoped-provider';
import type { Point, SnapshotQualityVerdict } from '@agent-device/kernel/snapshot';
import type {
Interactor,
RunnerCallOptions,
RunnerContext,
ScreenshotCaptureFacts,
ScreenshotOptions,
SnapshotOptions,
} from '@agent-device/contracts/interactor-types';
import { captureMacOsSurfaceSnapshot } from './os/macos/surface-snapshot.ts';
import { hostMacOsAppBackend } from './os/macos/app-backend.ts';
import { macOsNativeAppInteractor } from './os/macos/native-app-interactor.ts';
import {
presentAppleRunnerSnapshot,
type AppleRunnerSnapshotPresentation,
readAppleSnapshotResult,
type AppleRunnerSnapshotResult,
} from './runner/snapshot-presentation.ts';
import { iosSystemSurfaceDisclosure } from '@agent-device/contracts/ios-system-surface';
import { iosTargetActivationDisclosure } from '@agent-device/contracts/ios-target-activation';
export function createAppleInteractor(
device: DeviceInfo,
runnerContext: RunnerContext,
runnerProvider?: AppleRunnerProvider | AppleRunnerCommandExecutor,
): Interactor {
// watchOS unsupported sentinel: XCUITest cannot drive watchOS UI (no
// XCUIApplication), so a watchOS device has no runner backend. Reject it
// explicitly here rather than letting `appleOs: 'watchos'` silently fall
// through to the iOS runner profile (see resolveRunnerPlatformNameForAppleOs).
if (device.appleOs === 'watchos') {
throw new AppError(
'UNSUPPORTED_PLATFORM',
'watchOS is not supported: XCUITest cannot drive watchOS UI, so this device has no runner backend.',
);
}
const { overrides, runnerOpts } = iosRunnerOverrides(device, runnerContext);
const appBackend = isMacOs(device) ? hostMacOsAppBackend() : 'xctest';
const helperSurface = (surface: SessionSurface | undefined) =>
isMacOs(device) ? macOsHelperSurface(surface, appBackend) : undefined;
const interactor: Interactor = {
open: (app, options) =>
openIosApp(device, app, {
appBundleId: options?.appBundleId,
launchConsole: options?.launchConsole,
launchArgs: options?.launchArgs,
terminateRunningApp: options?.terminateRunningApp,
url: options?.url,
runnerOptions: runnerOpts,
}),
openDevice: () => openIosDevice(device),
close: (app) => closeIosApp(device, app, runnerOpts),
screenshot: (outPath, options) =>
runAppleScreenshot(device, outPath, options, runnerOpts, helperSurface(options?.surface)),
snapshot: async (options) =>
await captureAppleSnapshot(device, options, runnerOpts, helperSurface(options?.surface)),
// The live text at a point: helper for a helper-routed macOS surface, XCTest runner for
// every other Apple leaf.
readTextAtPoint: async (point, options) => {
const helper = helperSurface(options?.surface);
return helper
? await readMacOsSurfaceTextAtPoint(point, helper, options?.appBundleId, options?.signal)
: await readRunnerTextAtPoint(device, point, options, runnerOpts);
},
// The XCTest runner's own text reading: it observes the live accessibility hierarchy
// directly, so it answers without the cost — and without the pruning — of a tree capture.
// Only a positive answer is authoritative; see `FindTextResult`.
findText: async (text, options) => {
const result = (await runAppleRunnerCommand(
device,
{ command: 'findText', text, appBundleId: options?.appBundleId },
options?.signal ? { ...runnerOpts, signal: options.signal } : runnerOpts,
)) as { found?: boolean };
return { found: result?.found === true };
},
back: async (mode) => {
if (isTvOsDevice(device)) {
// tvOS focus-only navigation: the Menu button pops focus, not a coordinate tap.
await runAppleRunnerCommand(
device,
appleRemotePressCommand('menu', runnerContext.appBundleId),
runnerOpts,
);
return;
}
await runAppleRunnerCommand(
device,
{
command: resolveAppleBackRunnerCommand(mode),
appBundleId: runnerContext.appBundleId,
},
runnerOpts,
);
},
home: async () => {
if (isTvOsDevice(device)) {
// tvOS focus-only navigation: the Home button drives the remote, not a tap.
await runAppleRunnerCommand(
device,
appleRemotePressCommand('home', runnerContext.appBundleId),
runnerOpts,
);
return;
}
await runAppleRunnerCommand(
device,
{ command: 'home', appBundleId: runnerContext.appBundleId },
runnerOpts,
);
},
setOrientation: async (orientation) => {
const result = await runAppleRunnerCommand(
device,
// `rotate` is the runner-protocol command name (its own namespace); the
// CLI-facing command/method is `orientation`.
{ command: 'rotate', orientation, appBundleId: runnerContext.appBundleId },
runnerOpts,
);
const observed = readRunnerOrientation(result);
if (observed !== orientation) {
throw new AppError(
'COMMAND_FAILED',
`iOS runner observed ${observed} after requesting ${orientation}`,
{ requestedOrientation: orientation, observedOrientation: observed },
);
}
return { orientation: observed };
},
appSwitcher: async () => {
await runAppleRunnerCommand(
device,
{ command: 'appSwitcher', appBundleId: runnerContext.appBundleId },
runnerOpts,
);
},
actionButton: async () => {
await runAppleRunnerCommand(
device,
{ command: 'actionButton', appBundleId: runnerContext.appBundleId },
runnerOpts,
);
},
tvRemote: async (button, durationMs) => {
await runAppleRunnerCommand(
device,
appleRemotePressCommand(
toAppleTvRemoteButton(button),
runnerContext.appBundleId,
durationMs,
),
runnerOpts,
);
},
keyboardDismiss: async () => {
const result = await runAppleRunnerCommand(
device,
{ command: 'keyboardDismiss', appBundleId: runnerContext.appBundleId },
runnerOpts,
);
return {
kind: 'mechanism',
wasVisible: readRunnerBoolean(result, 'wasVisible'),
dismissed: readRunnerBoolean(result, 'dismissed'),
visible: readRunnerBoolean(result, 'visible'),
mechanism: readRunnerString(result, 'keyboardDismissMechanism'),
};
},
keyboardEnter: async () => {
const result = await runAppleRunnerCommand(
device,
{ command: 'keyboardReturn', appBundleId: runnerContext.appBundleId },
runnerOpts,
);
return {
kind: 'visibility-echo',
visible: readRunnerBoolean(result, 'visible'),
wasVisible: readRunnerBoolean(result, 'wasVisible'),
};
},
readClipboard: () => readIosClipboardText(device),
writeClipboard: (text) => writeIosClipboardText(device, text, runnerOpts),
setSetting: (setting, state, appId, options) =>
setIosSetting(device, setting, state, appId, options),
readSetting: (setting) => readIosSetting(device, setting),
readAlert: (options) => readAppleAlert(device, runnerOpts, options),
awaitAlert: (options) => awaitAppleAlert(device, runnerOpts, options),
acceptAlert: (options) => actOnAppleAlert(device, runnerOpts, 'accept', options),
dismissAlert: (options) => actOnAppleAlert(device, runnerOpts, 'dismiss', options),
...overrides,
};
const served =
appBackend === 'native' ? macOsNativeAppInteractor(interactor, runnerContext) : interactor;
if (!runnerProvider) return served;
return withInjectedAppleRunnerTransport(device, runnerContext, served, runnerProvider);
}
async function captureAppleSnapshot(
device: DeviceInfo,
options: SnapshotOptions | undefined,
runnerOpts: RunnerCallOptions,
helper: MacOsHelperSurface | undefined,
) {
if (helper) {
return await captureMacOsSurfaceSnapshot({ ...options, surface: helper }, options?.signal);
}
return await captureAppleRunnerSnapshot(device, options, runnerOpts);
}
async function captureAppleRunnerSnapshot(
device: DeviceInfo,
options: SnapshotOptions | undefined,
runnerOpts: RunnerCallOptions,
) {
const result = readAppleSnapshotResult(
await withDiagnosticTimer(
'snapshot_capture',
async () =>
await runAppleRunnerCommand(
device,
runnerSnapshotCommand(options),
mergeRunnerCallSignal(runnerOpts, options?.signal),
),
{ backend: 'xctest' },
),
);
assertSnapshotObservationResponse(options, result);
assertReportedRunnerSnapshotNodes(device, options, result);
const warnings = runnerSnapshotWarnings(result);
const presentation = presentRunnerSnapshotForDevice(device, options, result);
return {
nodes: presentation.nodes,
truncated: result.truncated ?? false,
backend: 'xctest' as const,
producer: 'apple-runner' as const,
...(presentation.viewport ? { viewport: presentation.viewport } : {}),
...(result.quality ? { quality: result.quality } : {}),
...(result.systemSurface ? { systemSurface: result.systemSurface } : {}),
...(result.keyboard ? { keyboard: result.keyboard } : {}),
...(result.targetActivation ? { targetActivation: result.targetActivation } : {}),
...(result.observation ? { observation: result.observation } : {}),
...(warnings.length > 0 ? { warnings } : {}),
};
}
function runnerSnapshotCommand(options: SnapshotOptions | undefined): RunnerCommand {
const { appBundleId, interactiveOnly, preferredBackend, customActions, depth, scope, raw } =
options ?? {};
return {
command: 'snapshot',
appBundleId,
interactiveOnly,
preferredBackend,
customActions,
...(options?.observeOnly === true ? { observeOnly: true } : {}),
depth,
scope,
raw,
};
}
function assertSnapshotObservationResponse(
options: SnapshotOptions | undefined,
result: AppleRunnerSnapshotResult,
): void {
if (options?.observeOnly !== true) return;
if (result.observation && !result.targetActivation) return;
throw new AppError('COMMAND_FAILED', 'Runner did not return an observe-only snapshot.', {
reason: 'observation-unavailable',
});
}
/**
* A runner capture reporting no nodes is a failure unless the caller's own scope justifies it: an
* empty scoped capture is what `--scope` asked for, and a sparse-quality capture already says so.
*/
function assertReportedRunnerSnapshotNodes(
device: DeviceInfo,
options: SnapshotOptions | undefined,
result: AppleRunnerSnapshotResult,
) {
if ((result.nodes?.length ?? 0) > 0) return;
if (acceptsEmptyScopedSnapshot(options, result.quality)) return;
if (device.kind !== 'simulator') return;
throw new AppError('COMMAND_FAILED', 'XCTest snapshot returned 0 nodes on iOS simulator.');
}
/**
* Agent-facing warnings for a runner capture: a legacy runner's message text when it carried no
* quality verdict, the shared disclosure when the capture describes an in-place system surface
* (e.g. the web sign-in or Apple Pay sheet) rather than the app itself (#2438), and the disclosure
* when this capture's own command had to bring the session app back to the foreground (#2682).
*/
function runnerSnapshotWarnings(result: AppleRunnerSnapshotResult): string[] {
const warnings: string[] = [];
if (!result.quality && result.message) warnings.push(result.message);
if (result.systemSurface)
warnings.push(iosSystemSurfaceDisclosure(result.systemSurface.bundleId));
if (result.targetActivation)
warnings.push(iosTargetActivationDisclosure(result.targetActivation));
return warnings;
}
function presentRunnerSnapshotForDevice(
device: DeviceInfo,
options: SnapshotOptions | undefined,
result: AppleRunnerSnapshotResult,
): AppleRunnerSnapshotPresentation {
// The desktop runner's nodes are already presented and carry absolute window-space rects, which
// no single box describes (#3182); the macOS surface capture publishes its own space instead.
if (isMacOs(device)) return { nodes: result.nodes ?? [] };
return presentAppleRunnerSnapshot(device.id, options, result);
}
function acceptsEmptyScopedSnapshot(
options: SnapshotOptions | undefined,
quality: SnapshotQualityVerdict | undefined,
): boolean {
return (
normalizeSnapshotScope(options?.scope) !== null &&
quality !== undefined &&
quality.state !== 'sparse'
);
}
function mergeRunnerCallSignal(
options: RunnerCallOptions,
signal: AbortSignal | undefined,
): RunnerCallOptions {
if (!signal) return options;
return {
...options,
signal: options.signal ? AbortSignal.any([options.signal, signal]) : signal,
};
}
function readRunnerBoolean(result: Record<string, unknown>, key: string): boolean | undefined {
const value = result[key];
return typeof value === 'boolean' ? value : undefined;
}
function readRunnerString(result: Record<string, unknown>, key: string): string | undefined {
const value = result[key];
return typeof value === 'string' ? value : undefined;
}
function readRunnerOrientation(result: Record<string, unknown>): DeviceRotation {
const orientation = result.orientation;
if (typeof orientation === 'string' && DEVICE_ROTATIONS.includes(orientation as DeviceRotation)) {
return orientation as DeviceRotation;
}
throw new AppError('COMMAND_FAILED', 'iOS runner returned an invalid orientation result', {
orientation,
});
}
/**
* Partitions the interactor for an injected provider transport. Its unique
* jobs are the local-tooling rejection and in-process scoping for interactors
* composed OUTSIDE a daemon request (on daemon requests the request-boundary
* `appleRunnerProvider` resolver scopes the same transport around everything):
* runner-command methods run inside the provider scope, while methods backed
* by local Apple tooling (simctl/devicectl) have no provider-neutral transport
* and fail fast until the provider session composes its own on top.
*/
function withInjectedAppleRunnerTransport(
device: DeviceInfo,
runnerContext: RunnerContext,
interactor: Interactor,
runnerProvider: AppleRunnerProvider | AppleRunnerCommandExecutor,
): Interactor {
const providerInteractor: Interactor = {
...interactor,
open: async () => rejectLocalAppleToolMethod('open'),
openDevice: async () => rejectLocalAppleToolMethod('openDevice'),
close: async () => rejectLocalAppleToolMethod('close'),
screenshot: async () => rejectLocalAppleToolMethod('screenshot'),
readClipboard: async () => rejectLocalAppleToolMethod('readClipboard'),
setSetting: async () => rejectLocalAppleToolMethod('setSetting'),
readSetting: async () => rejectLocalAppleToolMethod('readSetting'),
};
return withMethodScope(providerInteractor, (task) =>
withAppleRunnerProvider(
runnerProvider,
{ deviceId: device.id, requestId: runnerContext.requestId },
task,
),
);
}
function rejectLocalAppleToolMethod(method: string): never {
throw new AppError(
'UNSUPPORTED_OPERATION',
`${method} uses local Apple tooling (simctl/devicectl), which an injected runner transport cannot reach; the provider session must supply its own ${method} implementation.`,
);
}
async function runAppleScreenshot(
device: DeviceInfo,
outPath: string,
options: ScreenshotOptions = {},
runnerOpts: RunnerCallOptions,
helper: MacOsHelperSurface | undefined,
): Promise<ScreenshotCaptureFacts> {
if (helper) {
if (options.fullscreen) {
throw new AppError(
'INVALID_ARGS',
`screenshot --fullscreen is not accepted on the macOS ${helper} surface: its capture frame is fixed`,
{
reason: SCREENSHOT_FULLSCREEN_REASONS.macOsHelperSurfaceFixedFrame,
surface: helper,
},
);
}
await runMacOsScreenshotAction(outPath, {
surface: helper,
...(helper === 'app' ? { bundleId: options.appBundleId } : {}),
signal: runnerOpts.signal,
});
return {};
}
if (options.captureBackend === 'runner') {
// Runner capture returns the XCTest surface as-is; density and simulator
// status-bar normalization belong only to the simctl capture pipeline.
await captureScreenshotViaRunner(
device,
outPath,
options.appBundleId,
options.fullscreen,
runnerOpts,
);
return {};
}
return await screenshotIos(device, outPath, {
appBundleId: options.appBundleId,
pixelDensity: options.pixelDensity,
fullscreen: options.fullscreen,
runnerOptions: runnerOpts,
normalizeStatusBar: options.normalizeStatusBar,
skipIosSimulatorBootCheck: options.skipIosSimulatorBootCheck,
});
}
async function readMacOsSurfaceTextAtPoint(
point: Point,
surface: MacOsHelperSurface,
appBundleId: string | undefined,
signal: AbortSignal | undefined,
): Promise<string | undefined> {
const { runMacOsReadTextAction } = await import('./os/macos/helper.ts');
const result = await runMacOsReadTextAction(point.x, point.y, {
bundleId: appBundleId,
surface,
signal,
});
return result.text;
}
async function readRunnerTextAtPoint(
device: DeviceInfo,
point: Point,
options: { appBundleId?: string; signal?: AbortSignal } | undefined,
runnerOpts: RunnerCallOptions,
): Promise<string | undefined> {
const result = await runAppleRunnerCommand(
device,
{ command: 'readText', x: point.x, y: point.y, appBundleId: options?.appBundleId },
options?.signal ? { ...runnerOpts, signal: options.signal } : runnerOpts,
);
if (typeof result.text === 'string') return result.text;
// The runner answers `message` when it reached the element but rendered no readable text.
return typeof result.message === 'string' ? result.message : undefined;
}