Repository navigation
Expand file tree
/
Copy pathios.ts
More file actions
618 lines (574 loc) · 20 KB
/
Copy pathios.ts
File metadata and controls
618 lines (574 loc) · 20 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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
import { isDeepLinkTarget } from '@agent-device/contracts/command';
import {
parseAppearanceAction,
parsePermissionAction,
parseSettingState,
type SettingOptions,
} from '@agent-device/contracts/settings';
import type {
DeviceLease,
DeviceRotation,
ProviderDeviceInstallOptions,
ProviderDeviceInstallResult,
} from '@agent-device/contracts/device';
import type { FillBackendResult, Interactor } from '@agent-device/contracts/interactor-types';
import type { DeviceInfo } from '@agent-device/kernel/device';
import {
AppError,
discloseDispatchAfterSteps,
sessionAppRequiredDetails,
} from '@agent-device/kernel/errors';
import { requireLocationCoordinates } from '@agent-device/kernel/location-coordinates';
import type Limrun from '@limrun/api';
import {
createInstanceClient as createIosInstanceClient,
type InstanceClient as LimrunIosClient,
} from '@limrun/api/ios-client';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as sleep } from 'node:timers/promises';
import { toIosSelector } from './snapshot.ts';
import { normalizeOptionalString } from './strings.ts';
import {
awaitLimrunDeploymentOperation,
type LimrunRequestOperationDrain,
} from './request-cancellation.ts';
import type { LimrunInstanceOwnership } from './instance-access.ts';
import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts';
export type LimrunIosSession = {
platform: 'ios';
lease: DeviceLease;
instanceId: string;
readonly ownership: LimrunInstanceOwnership;
device: DeviceInfo;
client: LimrunIosClient;
/** Instance bearer token; the recording download the SDK would run inline is done by the host instead. */
readonly token: string;
readonly dependencies: Pick<LimrunRuntimeDependencies, 'host' | 'ios'>;
};
export type LimrunIosRemoteInstallOptions = {
md5?: string;
relaunch?: boolean;
appIdentifierHint?: string;
};
export type LimrunIosRemoteInstallResult = {
appId?: string;
};
type LimrunIosApp = Awaited<ReturnType<LimrunIosClient['listApps']>>[number];
export async function createLimrunIosSession(
options: {
lease: DeviceLease;
instanceId: string;
ownership: LimrunInstanceOwnership;
device: DeviceInfo;
apiUrl: string;
token: string;
},
dependencies: Pick<LimrunRuntimeDependencies, 'host' | 'ios'>,
): Promise<LimrunIosSession> {
const client = await createIosInstanceClient({
apiUrl: options.apiUrl,
token: options.token,
logLevel: 'warn',
});
return {
platform: 'ios',
lease: options.lease,
instanceId: options.instanceId,
ownership: options.ownership,
device: options.device,
client,
token: options.token,
dependencies,
};
}
export async function installLimrunIosApp(
limrun: Limrun,
session: LimrunIosSession,
installablePath: string,
options?: ProviderDeviceInstallOptions,
signal?: AbortSignal,
operationDrain?: LimrunRequestOperationDrain,
): Promise<ProviderDeviceInstallResult> {
signal?.throwIfAborted();
const prepared = await prepareLimrunIosAsset(installablePath, session.dependencies);
try {
signal?.throwIfAborted();
const asset = await awaitLimrunDeploymentOperation(
operationDrain,
limrun.assets.getOrUpload(
{
path: prepared.uploadPath,
name: prepared.assetName,
},
{ signal },
),
signal,
);
const result = await installLimrunIosRemoteApp(
session,
asset.signedDownloadUrl,
{
md5: asset.md5,
relaunch: options?.relaunch,
appIdentifierHint: options?.appIdentifierHint,
},
signal,
operationDrain,
);
const bundleId = result.appId;
return {
...(bundleId ? { bundleId, launchTarget: bundleId } : {}),
...(prepared.appName ? { appName: prepared.appName } : {}),
};
} finally {
await prepared.cleanup();
}
}
export async function installLimrunIosRemoteApp(
session: LimrunIosSession,
url: string,
options?: LimrunIosRemoteInstallOptions,
signal?: AbortSignal,
operationDrain?: LimrunRequestOperationDrain,
): Promise<LimrunIosRemoteInstallResult> {
signal?.throwIfAborted();
const beforeInstallApps = await awaitLimrunDeploymentOperation(
operationDrain,
session.client.listApps(),
signal,
).catch((error: unknown) => {
if (signal?.aborted) throw error;
return undefined;
});
const result = await awaitLimrunDeploymentOperation(
operationDrain,
session.client.installApp(url, {
md5: options?.md5,
launchMode: options?.relaunch ? 'RelaunchIfRunning' : 'ForegroundIfRunning',
}),
signal,
);
const resultBundleId = normalizeOptionalString(result.bundleId);
const requestedBundleId = normalizeOptionalString(options?.appIdentifierHint);
let afterInstallApps: LimrunIosApp[] = [];
for (const delayMs of IOS_APP_INVENTORY_RETRY_DELAYS_MS) {
if (delayMs > 0) await sleep(delayMs, undefined, { signal });
afterInstallApps = await awaitLimrunDeploymentOperation(
operationDrain,
session.client.listApps(),
signal,
);
const verifiedBundleId = resolveInstalledIosAppId({
resultBundleId,
requestedBundleId,
beforeInstallApps,
afterInstallApps,
});
if (verifiedBundleId) return { appId: verifiedBundleId };
}
throw new AppError('COMMAND_FAILED', 'Limrun iOS app installation could not be verified.', {
resultBundleId,
requestedBundleId,
installedUserApps: afterInstallApps
.filter(isUserInstalledIosApp)
.map((app) => app.bundleId)
.sort(),
});
}
export function createLimrunIosInteractor(session: LimrunIosSession): Interactor {
return new LimrunIosInteractor(session);
}
class LimrunIosInteractor implements Interactor {
private readonly session: LimrunIosSession;
constructor(session: LimrunIosSession) {
this.session = session;
}
async open(app: string, options?: { url?: string; launchArgs?: string[] }): Promise<void> {
if (options?.url) {
await this.launch(app, options.launchArgs);
await this.session.client.openUrl(options.url);
return;
}
if (isDeepLinkTarget(app)) {
await this.session.client.openUrl(app);
return;
}
await this.launch(app, options?.launchArgs);
}
private async launch(app: string, launchArgs: string[] = []): Promise<void> {
const bundleId = await this.session.dependencies.ios.resolveAppAlias(app);
if (launchArgs.length === 0) {
await this.session.client.launchApp(bundleId);
return;
}
// Limrun's launchApp takes no arguments, and an app reads them only at process start.
const result = await this.session.client
.simctl(['launch', '--terminate-running-process', 'booted', bundleId, ...launchArgs])
.wait();
if (result.code !== 0) {
throw new AppError(
'COMMAND_FAILED',
`Limrun iOS could not launch ${bundleId} with arguments.`,
{
bundleId,
exitCode: result.code,
stderr: result.stderr.trim(),
},
);
}
}
async openDevice(): Promise<void> {}
async close(app: string): Promise<void> {
if (app) {
await this.session.client
.terminateApp(await this.session.dependencies.ios.resolveAppAlias(app))
.catch(() => {});
}
}
async tap(x: number, y: number): Promise<void> {
await this.session.client.tap(x, y);
}
async tapElementSelector(selector: {
key: 'id' | 'label' | 'text' | 'value';
value: string;
}): Promise<Record<string, unknown> | void> {
await this.session.client.tapElement(toIosSelector(selector));
}
/**
* Both taps travel in one `performActions` batch so the inter-tap gap is enforced on the
* device. Two separate `tap` requests put a network round trip between the taps, which
* exceeds the double-tap recognition window and registers as two slow single taps.
*/
async doubleTap(x: number, y: number): Promise<void> {
await this.session.client.performActions([
{ type: 'tap', x, y },
{ type: 'wait', durationMs: DOUBLE_TAP_INTERVAL_MS },
{ type: 'tap', x, y },
]);
}
/** One held touch as HID primitives; the hold runs on the device, not across the wire. */
async longPress(
x: number,
y: number,
durationMs = DEFAULT_LONG_PRESS_DURATION_MS,
): Promise<void> {
await this.session.client.performActions([
{ type: 'touchDown', x, y },
{ type: 'wait', durationMs },
{ type: 'touchUp', x, y },
]);
}
async focus(x: number, y: number): Promise<void> {
await this.tap(x, y);
}
async type(text: string, delayMs?: number): Promise<void> {
await this.enterText(text, delayMs);
}
async fill(x: number, y: number, text: string, delayMs?: number): Promise<FillBackendResult> {
// Loaded on the fill path to keep this provider's declared import-time closure budget.
const { awaitLimrunTextEntryFocus, readLimrunUnambiguousTapTargets, readLimrunTextEntryFocus } =
await import('./text-entry-focus.ts');
// Read before the tap: the witness needs to know what was under this point.
const targetsAtPoint = readLimrunUnambiguousTapTargets(
await this.session.client.elementTree(),
x,
y,
);
await this.tap(x, y);
const textEntryReadiness = await awaitLimrunTextEntryFocus({
targetsAtPoint,
readFocus: async () => readLimrunTextEntryFocus(await this.session.client.elementTree()),
sleep: (milliseconds) => sleep(milliseconds),
x,
y,
});
// Select first: iOS replaces a selection on the next key, so `fill` replaces and
// an empty fill clears.
await this.session.client.pressKey('a', ['command']);
if (text.length === 0) {
await this.session.client.pressKey('delete');
return { textEntryReadiness };
}
await this.enterText(text, delayMs);
return { textEntryReadiness };
}
/**
* Types into whatever holds text-entry focus, character by character when a delay is
* asked for. Focus targeting belongs to the caller, so the provider's own scan for a
* globally focused element is skipped: an app can expose fields that take keys without
* ever reporting one.
*/
private async enterText(text: string, delayMs?: number): Promise<void> {
if (delayMs && delayMs > 0) {
let dispatchedChars = 0;
try {
for (const char of Array.from(text)) {
await this.session.client.typeText(char, false, { requireFocus: false });
dispatchedChars += 1;
await sleep(delayMs);
}
} catch (error) {
throw discloseDispatchAfterSteps(error, dispatchedChars);
}
return;
}
await this.session.client.typeText(text, false, { requireFocus: false });
}
async scroll(direction: 'up' | 'down' | 'left' | 'right', options?: { pixels?: number }) {
await this.session.client.scroll(direction, options?.pixels ?? 300);
}
/** Limrun serves its capture as JPEG; the PNG-only readers behind `outPath` get a PNG. */
async screenshot(outPath: string): Promise<void> {
// Loaded on the screenshot path to keep this provider's declared import-time closure budget.
const { transcodeScreenshotToPngAsync } =
await import('@agent-device/capture-kit/png-worker-client');
const screenshot = await this.session.client.screenshot();
const png = await transcodeScreenshotToPngAsync(
Buffer.from(screenshot.base64, 'base64'),
'Limrun iOS screenshot',
);
fs.mkdirSync(path.dirname(outPath), { recursive: true });
await fs.promises.writeFile(outPath, png);
}
async snapshot() {
const { captureLimrunIosSnapshot } = await import('./ios-snapshot-adapter.ts');
return await captureLimrunIosSnapshot(this.session);
}
async back(): Promise<void> {
await this.session.client.pressKey('escape');
}
async setOrientation(orientation: DeviceRotation): Promise<void> {
if (orientation === 'portrait-upside-down') {
throw unsupported(
'orientation',
'Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.',
);
}
await this.session.client.setOrientation(orientation === 'portrait' ? 'Portrait' : 'Landscape');
}
async setSetting(
setting: string,
state: string,
appId?: string,
options?: SettingOptions,
): Promise<Record<string, unknown> | void> {
switch (setting.toLowerCase()) {
case 'appearance':
return await this.setAppearance(state);
case 'permission':
return await this.setPermission(state, appId, options);
case 'location':
return await this.setLocation(state, appId, options);
case 'clear-app-state':
return await this.clearAppState(state, appId);
default:
throw unsupported(
'settings',
`Limrun iOS direct sessions support appearance, permission, location, and clear-app-state settings, not ${setting}.`,
);
}
}
private async setAppearance(state: string): Promise<void> {
const action = parseAppearanceAction(state);
const target = action === 'toggle' ? await this.toggledAppearance() : action;
await this.simctl('appearance', ['ui', 'booted', 'appearance', target]);
}
private async setPermission(
state: string,
appId: string | undefined,
options: SettingOptions | undefined,
): Promise<void> {
const bundleId = await this.requireAppId(
appId,
'permission setting requires an active app in session',
);
const { settings } = this.session.dependencies.ios;
const action = settings.privacyAction(parsePermissionAction(state));
const service = settings.parsePrivacyService(
options?.permissionTarget,
options?.permissionMode,
);
try {
await this.simctl('permission', ['privacy', 'booted', action, service, bundleId]);
} catch (error) {
if (!settings.isPrivacyServiceRefusal(error)) throw error;
throw settings.privacyServiceRefusedError({
action,
target: service,
appBundleId: bundleId,
deviceId: this.session.device.id,
cause: error,
});
}
}
private async setLocation(
state: string,
appId: string | undefined,
options: SettingOptions | undefined,
): Promise<Record<string, unknown> | void> {
if (state.toLowerCase() === 'set') {
const { latitude, longitude } = requireLocationCoordinates(options);
await this.simctl('location', ['location', 'booted', 'set', `${latitude},${longitude}`]);
return { latitude, longitude };
}
const enabled = parseSettingState(state);
const bundleId = await this.requireAppId(
appId,
'location setting requires an active app in session',
);
await this.simctl('location', [
'privacy',
'booted',
enabled ? 'grant' : 'revoke',
'location',
bundleId,
]);
}
private async clearAppState(
state: string,
appId: string | undefined,
): Promise<Record<string, unknown>> {
if (state.toLowerCase() !== 'clear') {
throw new AppError('INVALID_ARGS', 'settings clear-app-state only supports clear.');
}
const bundleId = await this.requireAppId(
appId,
'settings clear-app-state requires an app id or an active app session.',
);
try {
await this.session.client.softReset(bundleId, { strategy: 'data' });
// Limrun's reset relaunches the app. A local clear leaves it stopped, so stop it here too.
await this.session.client.terminateApp(bundleId);
} catch (error) {
if (error instanceof AppError) throw error;
throw new AppError(
'COMMAND_FAILED',
'Limrun iOS could not clear app state.',
{ setting: 'clear-app-state', bundleId },
error,
);
}
return { bundleId, cleared: true };
}
private async requireAppId(appId: string | undefined, message: string): Promise<string> {
if (!appId) throw new AppError('INVALID_ARGS', message, sessionAppRequiredDetails());
return await this.session.dependencies.ios.resolveAppAlias(appId);
}
private async toggledAppearance(): Promise<'light' | 'dark'> {
const current = await this.simctl('appearance', ['ui', 'booted', 'appearance']);
const appearance = this.session.dependencies.ios.settings.parseAppearance(
current.stdout,
current.stderr,
);
if (!appearance) {
throw new AppError(
'COMMAND_FAILED',
'Unable to determine current iOS appearance for toggle',
{
stdout: current.stdout,
stderr: current.stderr,
},
);
}
return appearance === 'dark' ? 'light' : 'dark';
}
private async simctl(setting: string, argv: string[]) {
const result = await this.session.client.simctl(argv).wait();
if (result.code !== 0) {
throw new AppError('COMMAND_FAILED', `Limrun iOS could not change the ${setting} setting.`, {
setting,
exitCode: result.code,
stderr: result.stderr.trim(),
});
}
return result;
}
}
async function prepareLimrunIosAsset(
artifactPath: string,
dependencies: Pick<LimrunRuntimeDependencies, 'host' | 'ios'>,
): Promise<{
uploadPath: string;
assetName: string;
appName?: string;
cleanup: () => Promise<void>;
}> {
const stat = await fs.promises.stat(artifactPath);
if (!stat.isDirectory()) {
return {
uploadPath: artifactPath,
assetName: path.basename(artifactPath),
appName: inferAppNameFromPath(artifactPath),
cleanup: async () => {},
};
}
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'agent-device-limrun-ios-app-'));
const zipPath = path.join(tempDir, `${path.basename(artifactPath)}.zip`);
try {
await dependencies.host.archiveDirectory({
sourceDirectory: path.dirname(artifactPath),
entryName: path.basename(artifactPath),
archivePath: zipPath,
});
} catch (error) {
await fs.promises.rm(tempDir, { recursive: true, force: true });
throw error;
}
return {
uploadPath: zipPath,
assetName: path.basename(zipPath),
appName:
(await dependencies.ios.readBundleAppName(artifactPath)) ??
inferAppNameFromPath(artifactPath),
cleanup: async () => {
await fs.promises.rm(tempDir, { recursive: true, force: true });
},
};
}
function inferAppNameFromPath(appPath: string): string | undefined {
const base = path.basename(appPath).replace(/\.(?:app|ipa|apk|aab|zip)$/i, '');
return base || undefined;
}
const IOS_APP_INVENTORY_RETRY_DELAYS_MS = [0, 250] as const;
/** Hold applied when the caller names no duration; matches the Android and Linux interactors. */
const DEFAULT_LONG_PRESS_DURATION_MS = 800;
/** On-device pause between the two taps of a double tap; well inside the recognizer's window. */
const DOUBLE_TAP_INTERVAL_MS = 80;
function resolveInstalledIosAppId(params: {
resultBundleId?: string;
requestedBundleId?: string;
beforeInstallApps: LimrunIosApp[] | undefined;
afterInstallApps: LimrunIosApp[];
}): string | undefined {
const installedBundleIds = new Set(params.afterInstallApps.map((app) => app.bundleId));
return (
(params.resultBundleId && installedBundleIds.has(params.resultBundleId)
? params.resultBundleId
: undefined) ??
(params.requestedBundleId && installedBundleIds.has(params.requestedBundleId)
? params.requestedBundleId
: undefined) ??
inferNewUserInstalledApp(params.beforeInstallApps, params.afterInstallApps)
);
}
function inferNewUserInstalledApp(
beforeInstallApps: LimrunIosApp[] | undefined,
afterInstallApps: LimrunIosApp[],
): string | undefined {
if (!beforeInstallApps) return undefined;
const beforeBundleIds = new Set(beforeInstallApps.map((app) => app.bundleId));
const candidates = afterInstallApps.filter(
(app) => isUserInstalledIosApp(app) && !beforeBundleIds.has(app.bundleId),
);
return candidates.length === 1 ? candidates[0]?.bundleId : undefined;
}
export function isUserInstalledIosApp(app: LimrunIosApp): boolean {
return (
!app.bundleId.startsWith('com.apple.') && !app.installType.toLowerCase().includes('system')
);
}
function unsupported(command: string, message: string): never {
throw new AppError('UNSUPPORTED_OPERATION', message, { command });
}