-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathapp-lifecycle.ts
More file actions
657 lines (608 loc) · 20.1 KB
/
app-lifecycle.ts
File metadata and controls
657 lines (608 loc) · 20.1 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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { resolveFileOverridePath, runCmd, whichCmd } from '../../utils/exec.ts';
import { AppError } from '../../utils/errors.ts';
import type { DeviceInfo } from '../../utils/device.ts';
import { isDeepLinkTarget } from '../../core/open-target.ts';
import { createAppResolutionCache, type AppResolutionCacheScope } from '../app-resolution-cache.ts';
import { waitForAndroidBoot } from './devices.ts';
import { adbArgs } from './adb.ts';
import { classifyAndroidAppTarget } from './open-target.ts';
import { prepareAndroidInstallArtifact } from './install-artifact.ts';
import {
parseAndroidForegroundApp,
parseAndroidLaunchablePackages,
parseAndroidUserInstalledPackages,
type AndroidForegroundApp,
} from './app-parsers.ts';
export {
parseAndroidForegroundApp,
parseAndroidLaunchablePackages,
parseAndroidUserInstalledPackages,
type AndroidForegroundApp,
} from './app-parsers.ts';
const ALIASES: Record<string, { type: 'intent' | 'package'; value: string }> = {
settings: { type: 'intent', value: 'android.settings.SETTINGS' },
};
const ANDROID_LAUNCHER_CATEGORY = 'android.intent.category.LAUNCHER';
const ANDROID_LEANBACK_CATEGORY = 'android.intent.category.LEANBACK_LAUNCHER';
const ANDROID_DEFAULT_CATEGORY = 'android.intent.category.DEFAULT';
const ANDROID_APPS_DISCOVERY_HINT =
'Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.';
const ANDROID_AMBIGUOUS_APP_HINT =
'Run agent-device apps --platform android to see the exact installed package names before retrying open.';
type AndroidAppResolution = { type: 'intent' | 'package'; value: string };
const androidAppResolutionCache = createAppResolutionCache<AndroidAppResolution>();
function androidAppResolutionScope(device: DeviceInfo): AppResolutionCacheScope {
return { platform: 'android', deviceId: device.id, variant: device.target ?? '' };
}
export async function resolveAndroidApp(
device: DeviceInfo,
app: string,
): Promise<AndroidAppResolution> {
const trimmed = app.trim();
if (classifyAndroidAppTarget(trimmed) === 'package') return { type: 'package', value: trimmed };
const alias = ALIASES[trimmed.toLowerCase()];
if (alias) return alias;
const cacheScope = androidAppResolutionScope(device);
const cached = androidAppResolutionCache.get(cacheScope, trimmed);
if (cached) return cached;
const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'list', 'packages']));
const packages = result.stdout
.split('\n')
.map((line: string) => line.replace('package:', '').trim())
.filter(Boolean);
const matches = packages.filter((pkg: string) =>
pkg.toLowerCase().includes(trimmed.toLowerCase()),
);
if (matches.length === 1) {
return androidAppResolutionCache.set(cacheScope, trimmed, {
type: 'package',
value: matches[0],
});
}
if (matches.length > 1) {
throw new AppError('INVALID_ARGS', `Multiple packages matched "${app}"`, {
matches,
hint: ANDROID_AMBIGUOUS_APP_HINT,
});
}
throw new AppError('APP_NOT_INSTALLED', `No package found matching "${app}"`, {
hint: ANDROID_APPS_DISCOVERY_HINT,
});
}
export async function listAndroidApps(
device: DeviceInfo,
filter: 'user-installed' | 'all' = 'all',
): Promise<Array<{ package: string; name: string }>> {
const launchable = await listAndroidLaunchablePackages(device);
const packageIds =
filter === 'user-installed'
? (await listAndroidUserInstalledPackages(device)).filter((pkg) => launchable.has(pkg))
: Array.from(launchable);
return packageIds
.sort((a, b) => a.localeCompare(b))
.map((pkg) => ({ package: pkg, name: inferAndroidAppName(pkg) }));
}
async function listAndroidLaunchablePackages(device: DeviceInfo): Promise<Set<string>> {
const packages = new Set<string>();
for (const category of resolveAndroidLaunchCategories(device, {
includeFallbackWhenUnknown: true,
})) {
const result = await runCmd(
'adb',
adbArgs(device, [
'shell',
'cmd',
'package',
'query-activities',
'--brief',
'-a',
'android.intent.action.MAIN',
'-c',
category,
]),
{ allowFailure: true },
);
if (result.exitCode !== 0 || result.stdout.trim().length === 0) {
continue;
}
for (const pkg of parseAndroidLaunchablePackages(result.stdout)) {
packages.add(pkg);
}
}
return packages;
}
function resolveAndroidLauncherCategory(device: DeviceInfo): string {
return resolveAndroidLaunchCategories(device)[0] ?? ANDROID_LAUNCHER_CATEGORY;
}
function resolveAndroidLaunchCategories(
device: DeviceInfo,
options: { includeFallbackWhenUnknown?: boolean } = {},
): string[] {
if (device.target === 'tv') {
return [ANDROID_LEANBACK_CATEGORY];
}
if (device.target === 'mobile') {
return [ANDROID_LAUNCHER_CATEGORY];
}
if (options.includeFallbackWhenUnknown) {
return [ANDROID_LAUNCHER_CATEGORY, ANDROID_LEANBACK_CATEGORY];
}
return [ANDROID_LAUNCHER_CATEGORY];
}
async function listAndroidUserInstalledPackages(device: DeviceInfo): Promise<string[]> {
const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'list', 'packages', '-3']));
return parseAndroidUserInstalledPackages(result.stdout);
}
export function inferAndroidAppName(packageName: string): string {
const ignoredTokens = new Set([
'com',
'android',
'google',
'app',
'apps',
'service',
'services',
'mobile',
'client',
]);
const tokens = packageName
.split('.')
.flatMap((segment) => segment.split(/[_-]+/))
.map((token) => token.trim().toLowerCase())
.filter((token) => token.length > 0);
// Fallback to last token if every token is ignored (e.g. "com.android.app.services" → "Services").
let chosen = tokens[tokens.length - 1] ?? packageName;
for (let index = tokens.length - 1; index >= 0; index -= 1) {
const token = tokens[index];
if (!ignoredTokens.has(token)) {
chosen = token;
break;
}
}
return chosen
.split(/[^a-z0-9]+/i)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ');
}
export async function getAndroidAppState(device: DeviceInfo): Promise<AndroidForegroundApp> {
const windowFocus = await readAndroidFocus(device, [
['shell', 'dumpsys', 'window', 'windows'],
['shell', 'dumpsys', 'window'],
]);
if (windowFocus) return windowFocus;
const activityFocus = await readAndroidFocus(device, [
['shell', 'dumpsys', 'activity', 'activities'],
['shell', 'dumpsys', 'activity'],
]);
if (activityFocus) return activityFocus;
return {};
}
async function readAndroidFocus(
device: DeviceInfo,
commands: string[][],
): Promise<AndroidForegroundApp | null> {
for (const args of commands) {
const result = await runCmd('adb', adbArgs(device, args), { allowFailure: true });
const text = result.stdout ?? '';
const parsed = parseAndroidForegroundApp(text);
if (parsed) return parsed;
}
return null;
}
export async function openAndroidApp(
device: DeviceInfo,
app: string,
activity?: string,
): Promise<void> {
if (!device.booted) {
await waitForAndroidBoot(device.id);
}
const deepLinkTarget = app.trim();
if (isDeepLinkTarget(deepLinkTarget)) {
if (activity) {
throw new AppError(
'INVALID_ARGS',
'Activity override is not supported when opening a deep link URL',
);
}
await runCmd(
'adb',
adbArgs(device, [
'shell',
'am',
'start',
'-W',
'-a',
'android.intent.action.VIEW',
'-d',
deepLinkTarget,
]),
);
return;
}
const resolved = await resolveAndroidApp(device, app);
const launchCategory = resolveAndroidLauncherCategory(device);
if (resolved.type === 'intent') {
if (activity) {
throw new AppError(
'INVALID_ARGS',
'Activity override requires a package name, not an intent',
);
}
await runCmd('adb', adbArgs(device, ['shell', 'am', 'start', '-W', '-a', resolved.value]));
return;
}
if (activity) {
const component = activity.includes('/')
? activity
: `${resolved.value}/${activity.startsWith('.') ? activity : `.${activity}`}`;
try {
await runCmd(
'adb',
adbArgs(device, [
'shell',
'am',
'start',
'-W',
'-a',
'android.intent.action.MAIN',
'-c',
ANDROID_DEFAULT_CATEGORY,
'-c',
launchCategory,
'-n',
component,
]),
);
} catch (error) {
await maybeRethrowAndroidMissingPackageError(device, resolved.value, error);
throw error;
}
return;
}
const primaryResult = await runCmd(
'adb',
adbArgs(device, [
'shell',
'am',
'start',
'-W',
'-a',
'android.intent.action.MAIN',
'-c',
ANDROID_DEFAULT_CATEGORY,
'-c',
launchCategory,
'-p',
resolved.value,
]),
{ allowFailure: true },
);
if (primaryResult.exitCode === 0 && !isAmStartError(primaryResult.stdout, primaryResult.stderr)) {
return;
}
const component = await resolveAndroidLaunchComponent(device, resolved.value);
if (!component) {
if (!(await isAndroidPackageInstalled(device, resolved.value))) {
throw buildAndroidPackageNotInstalledError(resolved.value);
}
throw new AppError('COMMAND_FAILED', `Failed to launch ${resolved.value}`, {
stdout: primaryResult.stdout,
stderr: primaryResult.stderr,
});
}
await runCmd(
'adb',
adbArgs(device, [
'shell',
'am',
'start',
'-W',
'-a',
'android.intent.action.MAIN',
'-c',
ANDROID_DEFAULT_CATEGORY,
'-c',
launchCategory,
'-n',
component,
]),
);
}
function buildAndroidPackageNotInstalledError(packageName: string): AppError {
return new AppError('APP_NOT_INSTALLED', `No package found matching "${packageName}"`, {
package: packageName,
hint: ANDROID_APPS_DISCOVERY_HINT,
});
}
async function isAndroidPackageInstalled(
device: DeviceInfo,
packageName: string,
): Promise<boolean> {
const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'path', packageName]), {
allowFailure: true,
});
const output = `${result.stdout}\n${result.stderr}`;
if (result.exitCode === 0 && /\bpackage:/i.test(output)) {
return true;
}
if (looksLikeMissingAndroidPackageOutput(output)) {
return false;
}
return false;
}
async function maybeRethrowAndroidMissingPackageError(
device: DeviceInfo,
packageName: string,
error: unknown,
): Promise<void> {
const output =
error instanceof AppError
? `${String(error.details?.stdout ?? '')}\n${String(error.details?.stderr ?? '')}`
: '';
if (looksLikeMissingAndroidPackageOutput(output)) {
throw buildAndroidPackageNotInstalledError(packageName);
}
if (!(await isAndroidPackageInstalled(device, packageName))) {
throw buildAndroidPackageNotInstalledError(packageName);
}
}
function looksLikeMissingAndroidPackageOutput(output: string): boolean {
return (
/\bunknown package\b/i.test(output) ||
/\bpackage .* (?:was|is) not found\b/i.test(output) ||
/\bpackage .* does not exist\b/i.test(output) ||
/\bcould not find package\b/i.test(output)
);
}
async function resolveAndroidLaunchComponent(
device: DeviceInfo,
packageName: string,
): Promise<string | null> {
const categories = Array.from(
new Set(resolveAndroidLaunchCategories(device, { includeFallbackWhenUnknown: true })),
);
for (const category of categories) {
const result = await runCmd(
'adb',
adbArgs(device, [
'shell',
'cmd',
'package',
'resolve-activity',
'--brief',
'-a',
'android.intent.action.MAIN',
'-c',
category,
packageName,
]),
{ allowFailure: true },
);
if (result.exitCode !== 0) {
continue;
}
const component = parseAndroidLaunchComponent(result.stdout);
if (component) return component;
}
return null;
}
export function isAmStartError(stdout: string, stderr: string): boolean {
const output = `${stdout}\n${stderr}`;
return /Error:.*(?:Activity not started|unable to resolve Intent)/i.test(output);
}
export function parseAndroidLaunchComponent(stdout: string): string | null {
const lines = stdout
.split('\n')
.map((line: string) => line.trim())
.filter(Boolean);
for (let index = lines.length - 1; index >= 0; index -= 1) {
const line = lines[index];
if (!line.includes('/')) continue;
return line.split(/\s+/)[0];
}
return null;
}
export async function openAndroidDevice(device: DeviceInfo): Promise<void> {
if (!device.booted) {
await waitForAndroidBoot(device.id);
}
}
export async function closeAndroidApp(device: DeviceInfo, app: string): Promise<void> {
const trimmed = app.trim();
if (trimmed.toLowerCase() === 'settings') {
await runCmd('adb', adbArgs(device, ['shell', 'am', 'force-stop', 'com.android.settings']));
return;
}
const resolved = await resolveAndroidApp(device, app);
if (resolved.type === 'intent') {
throw new AppError('INVALID_ARGS', 'Close requires a package name, not an intent');
}
await runCmd('adb', adbArgs(device, ['shell', 'am', 'force-stop', resolved.value]));
}
async function uninstallAndroidApp(device: DeviceInfo, app: string): Promise<{ package: string }> {
const resolved = await resolveAndroidApp(device, app);
if (resolved.type === 'intent') {
throw new AppError('INVALID_ARGS', 'App uninstall requires a package name, not an intent');
}
const result = await runCmd('adb', adbArgs(device, ['uninstall', resolved.value]), {
allowFailure: true,
});
if (result.exitCode !== 0) {
const output = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (!output.includes('unknown package') && !output.includes('not installed')) {
throw new AppError('COMMAND_FAILED', `adb uninstall failed for ${resolved.value}`, {
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
});
}
}
return { package: resolved.value };
}
type BundletoolInvocation =
| { cmd: 'bundletool'; prefixArgs: readonly string[] }
| { cmd: 'java'; prefixArgs: readonly string[] };
// Module-level cache for bundletool resolution. Safe for the single-threaded
// Node.js event loop; concurrent async callers may race to populate it but will
// resolve to the same value since the inputs (PATH, env var) are stable per
// process lifetime.
let cachedBundletoolInvocation: { key: string; invocation: BundletoolInvocation } | null = null;
function bundletoolInvocationCacheKey(): string {
return `${process.env.PATH ?? ''}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR ?? ''}`;
}
async function resolveBundletoolInvocation(): Promise<BundletoolInvocation> {
const cacheKey = bundletoolInvocationCacheKey();
if (cachedBundletoolInvocation?.key === cacheKey) {
return cachedBundletoolInvocation.invocation;
}
if (await whichCmd('bundletool')) {
const invocation = { cmd: 'bundletool', prefixArgs: [] } as const;
cachedBundletoolInvocation = { key: cacheKey, invocation };
return invocation;
}
const bundletoolJar = await resolveFileOverridePath(
process.env.AGENT_DEVICE_BUNDLETOOL_JAR,
'AGENT_DEVICE_BUNDLETOOL_JAR',
);
if (!bundletoolJar) {
throw new AppError(
'TOOL_MISSING',
'bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.',
);
}
const invocation = { cmd: 'java', prefixArgs: ['-jar', bundletoolJar] } as const;
cachedBundletoolInvocation = { key: cacheKey, invocation };
return invocation;
}
async function runBundletool(args: string[]): Promise<void> {
const invocation = await resolveBundletoolInvocation();
await runCmd(invocation.cmd, [...invocation.prefixArgs, ...args]);
}
function isAndroidAppBundlePath(appPath: string): boolean {
return path.extname(appPath).toLowerCase() === '.aab';
}
function resolveBundletoolBuildMode(): string {
const mode = process.env.AGENT_DEVICE_ANDROID_BUNDLETOOL_MODE?.trim();
return mode && mode.length > 0 ? mode : 'universal';
}
async function installAndroidAppBundle(device: DeviceInfo, appPath: string): Promise<void> {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'agent-device-aab-'));
const apksPath = path.join(tempDir, 'bundle.apks');
const mode = resolveBundletoolBuildMode();
try {
await runBundletool(['build-apks', '--bundle', appPath, '--output', apksPath, '--mode', mode]);
await runBundletool(['install-apks', '--apks', apksPath, '--device-id', device.id]);
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
}
}
async function installAndroidAppFiles(device: DeviceInfo, appPath: string): Promise<void> {
if (isAndroidAppBundlePath(appPath)) {
await installAndroidAppBundle(device, appPath);
return;
}
await runCmd('adb', adbArgs(device, ['install', '-r', appPath]));
}
async function listInstalledAndroidPackages(device: DeviceInfo): Promise<Set<string>> {
const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'list', 'packages']));
return new Set(
result.stdout
.split('\n')
.map((line: string) => line.replace('package:', '').trim())
.filter(Boolean),
);
}
async function resolveInstalledAndroidPackageName(
device: DeviceInfo,
beforePackages: Set<string>,
): Promise<string | undefined> {
const afterPackages = await listInstalledAndroidPackages(device);
const installedNow = Array.from(afterPackages).filter((pkg) => !beforePackages.has(pkg));
if (installedNow.length === 1) return installedNow[0];
return undefined;
}
export async function installAndroidInstallablePath(
device: DeviceInfo,
installablePath: string,
): Promise<void> {
await androidAppResolutionCache.invalidateWhile(androidAppResolutionScope(device), async () => {
if (!device.booted) {
await waitForAndroidBoot(device.id);
}
await installAndroidAppFiles(device, installablePath);
});
}
export async function installAndroidInstallablePathAndResolvePackageName(
device: DeviceInfo,
installablePath: string,
packageNameHint?: string,
): Promise<string | undefined> {
const beforePackages = packageNameHint ? undefined : await listInstalledAndroidPackages(device);
await installAndroidInstallablePath(device, installablePath);
return (
packageNameHint ??
(beforePackages ? await resolveInstalledAndroidPackageName(device, beforePackages) : undefined)
);
}
export async function installAndroidApp(
device: DeviceInfo,
appPath: string,
): Promise<{
archivePath?: string;
installablePath: string;
packageName?: string;
appName?: string;
launchTarget?: string;
}> {
if (!device.booted) {
await waitForAndroidBoot(device.id);
}
const prepared = await prepareAndroidInstallArtifact({ kind: 'path', path: appPath });
try {
const packageName = await installAndroidInstallablePathAndResolvePackageName(
device,
prepared.installablePath,
prepared.packageName,
);
const appName = packageName ? inferAndroidAppName(packageName) : undefined;
return {
archivePath: prepared.archivePath,
installablePath: prepared.installablePath,
packageName,
appName,
launchTarget: packageName,
};
} finally {
await prepared.cleanup();
}
}
export async function reinstallAndroidApp(
device: DeviceInfo,
app: string,
appPath: string,
): Promise<{ package: string }> {
return await androidAppResolutionCache.invalidateWhile(
androidAppResolutionScope(device),
async () => {
if (!device.booted) {
await waitForAndroidBoot(device.id);
}
const { package: pkg } = await uninstallAndroidApp(device, app);
const prepared = await prepareAndroidInstallArtifact(
{ kind: 'path', path: appPath },
{ resolveIdentity: false },
);
try {
await installAndroidInstallablePath(device, prepared.installablePath);
} finally {
await prepared.cleanup();
}
return { package: pkg };
},
);
}