-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathindex.ts
More file actions
1011 lines (933 loc) · 31.2 KB
/
index.ts
File metadata and controls
1011 lines (933 loc) · 31.2 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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { promises as fs } from 'node:fs';
import { runCmd, whichCmd } from '../../utils/exec.ts';
import { withRetry } from '../../utils/retry.ts';
import { AppError } from '../../utils/errors.ts';
import type { DeviceInfo } from '../../utils/device.ts';
import type { RawSnapshotNode, SnapshotOptions } from '../../utils/snapshot.ts';
import { isDeepLinkTarget } from '../../core/open-target.ts';
import { waitForAndroidBoot } from './devices.ts';
import { findBounds, parseBounds, parseUiHierarchy, readNodeAttributes } from './ui-hierarchy.ts';
import {
parsePermissionAction,
parsePermissionTarget,
type PermissionSettingOptions,
} from '../permission-utils.ts';
const ALIASES: Record<string, { type: 'intent' | 'package'; value: string }> = {
settings: { type: 'intent', value: 'android.settings.SETTINGS' },
};
function adbArgs(device: DeviceInfo, args: string[]): string[] {
return ['-s', device.id, ...args];
}
export async function resolveAndroidApp(
device: DeviceInfo,
app: string,
): Promise<{ type: 'intent' | 'package'; value: string }> {
const trimmed = app.trim();
if (trimmed.includes('.')) return { type: 'package', value: trimmed };
const alias = ALIASES[trimmed.toLowerCase()];
if (alias) return alias;
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 { type: 'package', value: matches[0] };
}
if (matches.length > 1) {
throw new AppError('INVALID_ARGS', `Multiple packages matched "${app}"`, { matches });
}
throw new AppError('APP_NOT_INSTALLED', `No package found matching "${app}"`);
}
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 result = await runCmd(
'adb',
adbArgs(device, [
'shell',
'cmd',
'package',
'query-activities',
'--brief',
'-a',
'android.intent.action.MAIN',
'-c',
'android.intent.category.LAUNCHER',
]),
{ allowFailure: true },
);
if (result.exitCode !== 0 || result.stdout.trim().length === 0) {
return new Set<string>();
}
const packages = new Set<string>();
for (const line of result.stdout.split('\n')) {
const trimmed = line.trim();
if (!trimmed) continue;
const firstToken = trimmed.split(/\s+/)[0];
const pkg = firstToken.includes('/') ? firstToken.split('/')[0] : firstToken;
if (pkg) packages.add(pkg);
}
return packages;
}
async function listAndroidUserInstalledPackages(device: DeviceInfo): Promise<string[]> {
const result = await runCmd('adb', adbArgs(device, ['shell', 'pm', 'list', 'packages', '-3']));
return result.stdout
.split('\n')
.map((line: string) => line.replace('package:', '').trim())
.filter(Boolean);
}
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<{ package?: string; activity?: string }> {
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<{ package?: string; activity?: string } | null> {
for (const args of commands) {
const result = await runCmd('adb', adbArgs(device, args), { allowFailure: true });
const text = result.stdout ?? '';
const parsed = parseAndroidFocus(text);
if (parsed) return parsed;
}
return null;
}
function parseAndroidFocus(text: string): { package?: string; activity?: string } | null {
const patterns = [
/mCurrentFocus=Window\{[^}]*\s([\w.]+)\/([\w.$]+)/,
/mFocusedApp=AppWindowToken\{[^}]*\s([\w.]+)\/([\w.$]+)/,
/mResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/,
/ResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/,
];
for (const pattern of patterns) {
const match = pattern.exec(text);
if (match) {
return { package: match[1], activity: match[2] };
}
}
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);
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}`}`;
await runCmd(
'adb',
adbArgs(device, [
'shell',
'am',
'start',
'-W',
'-a',
'android.intent.action.MAIN',
'-c',
'android.intent.category.DEFAULT',
'-c',
'android.intent.category.LAUNCHER',
'-n',
component,
]),
);
return;
}
const primaryResult = await runCmd(
'adb',
adbArgs(device, [
'shell',
'am',
'start',
'-W',
'-a',
'android.intent.action.MAIN',
'-c',
'android.intent.category.DEFAULT',
'-c',
'android.intent.category.LAUNCHER',
'-p',
resolved.value,
]),
{ allowFailure: true },
);
if (primaryResult.exitCode === 0 && !isAmStartError(primaryResult.stdout, primaryResult.stderr)) {
return;
}
const component = await resolveAndroidLaunchComponent(device, resolved.value);
if (!component) {
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.intent.category.DEFAULT',
'-c',
'android.intent.category.LAUNCHER',
'-n',
component,
]),
);
}
async function resolveAndroidLaunchComponent(
device: DeviceInfo,
packageName: string,
): Promise<string | null> {
const result = await runCmd(
'adb',
adbArgs(device, [
'shell',
'cmd',
'package',
'resolve-activity',
'--brief',
'-a',
'android.intent.action.MAIN',
'-c',
'android.intent.category.LAUNCHER',
packageName,
]),
{ allowFailure: true },
);
if (result.exitCode !== 0) return null;
return parseAndroidLaunchComponent(result.stdout);
}
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', 'reinstall 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 };
}
async function installAndroidApp(device: DeviceInfo, appPath: string): Promise<void> {
await runCmd('adb', adbArgs(device, ['install', appPath]));
}
export async function reinstallAndroidApp(
device: DeviceInfo,
app: string,
appPath: string,
): Promise<{ package: string }> {
if (!device.booted) {
await waitForAndroidBoot(device.id);
}
const { package: pkg } = await uninstallAndroidApp(device, app);
await installAndroidApp(device, appPath);
return { package: pkg };
}
export async function pressAndroid(device: DeviceInfo, x: number, y: number): Promise<void> {
await runCmd('adb', adbArgs(device, ['shell', 'input', 'tap', String(x), String(y)]));
}
export async function swipeAndroid(
device: DeviceInfo,
x1: number,
y1: number,
x2: number,
y2: number,
durationMs = 250,
): Promise<void> {
await runCmd(
'adb',
adbArgs(device, [
'shell',
'input',
'swipe',
String(x1),
String(y1),
String(x2),
String(y2),
String(durationMs),
]),
);
}
export async function backAndroid(device: DeviceInfo): Promise<void> {
await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '4']));
}
export async function homeAndroid(device: DeviceInfo): Promise<void> {
await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '3']));
}
export async function appSwitcherAndroid(device: DeviceInfo): Promise<void> {
await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '187']));
}
export async function longPressAndroid(
device: DeviceInfo,
x: number,
y: number,
durationMs = 800,
): Promise<void> {
await runCmd(
'adb',
adbArgs(device, [
'shell',
'input',
'swipe',
String(x),
String(y),
String(x),
String(y),
String(durationMs),
]),
);
}
export async function typeAndroid(device: DeviceInfo, text: string): Promise<void> {
if (shouldUseClipboardTextInjection(text)) {
const clipboardResult = await typeAndroidViaClipboard(device, text);
if (clipboardResult === 'ok') return;
}
try {
const encoded = text.replace(/ /g, '%s');
await runCmd('adb', adbArgs(device, ['shell', 'input', 'text', encoded]));
} catch (error) {
if (shouldUseClipboardTextInjection(text) && isAndroidInputTextUnsupported(error)) {
throw new AppError(
'COMMAND_FAILED',
'Non-ASCII text input is not supported on this Android shell. Install an ADB keyboard IME or use ASCII input.',
{ textPreview: text.slice(0, 32) },
error instanceof Error ? error : undefined,
);
}
throw error;
}
}
export async function focusAndroid(device: DeviceInfo, x: number, y: number): Promise<void> {
await pressAndroid(device, x, y);
}
export async function fillAndroid(
device: DeviceInfo,
x: number,
y: number,
text: string,
): Promise<void> {
const textCodePointLength = Array.from(text).length;
const attempts = [
{ clearPadding: 12, minClear: 8, maxClear: 48, chunkSize: 4, delayMs: 0 },
{ clearPadding: 24, minClear: 16, maxClear: 96, chunkSize: 1, delayMs: 15 },
] as const;
await focusAndroid(device, x, y);
let lastActual: string | null = null;
for (const attempt of attempts) {
const clearCount = clampCount(
textCodePointLength + attempt.clearPadding,
attempt.minClear,
attempt.maxClear,
);
await clearFocusedText(device, clearCount);
await typeAndroidChunked(device, text, attempt.chunkSize, attempt.delayMs);
lastActual = await readInputValueAtPoint(device, x, y);
if (lastActual === text) return;
}
throw new AppError('COMMAND_FAILED', 'Android fill verification failed', {
expected: text,
actual: lastActual ?? null,
});
}
export async function scrollAndroid(
device: DeviceInfo,
direction: string,
amount = 0.6,
): Promise<void> {
const size = await getAndroidScreenSize(device);
const { width, height } = size;
const distanceX = Math.floor(width * amount);
const distanceY = Math.floor(height * amount);
const centerX = Math.floor(width / 2);
const centerY = Math.floor(height / 2);
let x1 = centerX;
let y1 = centerY;
let x2 = centerX;
let y2 = centerY;
switch (direction) {
case 'up':
// Content moves up -> swipe down.
y1 = centerY - Math.floor(distanceY / 2);
y2 = centerY + Math.floor(distanceY / 2);
break;
case 'down':
// Content moves down -> swipe up.
y1 = centerY + Math.floor(distanceY / 2);
y2 = centerY - Math.floor(distanceY / 2);
break;
case 'left':
// Content moves left -> swipe right.
x1 = centerX - Math.floor(distanceX / 2);
x2 = centerX + Math.floor(distanceX / 2);
break;
case 'right':
// Content moves right -> swipe left.
x1 = centerX + Math.floor(distanceX / 2);
x2 = centerX - Math.floor(distanceX / 2);
break;
default:
throw new AppError('INVALID_ARGS', `Unknown direction: ${direction}`);
}
await runCmd(
'adb',
adbArgs(device, [
'shell',
'input',
'swipe',
String(x1),
String(y1),
String(x2),
String(y2),
'300',
]),
);
}
export async function scrollIntoViewAndroid(device: DeviceInfo, text: string): Promise<void> {
const maxAttempts = 8;
for (let i = 0; i < maxAttempts; i += 1) {
let xml = '';
try {
xml = await dumpUiHierarchy(device);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
throw new AppError('UNSUPPORTED_OPERATION', `uiautomator dump failed: ${message}`);
}
if (findBounds(xml, text)) return;
await scrollAndroid(device, 'down', 0.5);
}
throw new AppError(
'COMMAND_FAILED',
`Could not find element containing "${text}" after scrolling`,
);
}
export async function screenshotAndroid(device: DeviceInfo, outPath: string): Promise<void> {
const result = await runCmd('adb', adbArgs(device, ['exec-out', 'screencap', '-p']), {
binaryStdout: true,
});
if (!result.stdoutBuffer) {
throw new AppError('COMMAND_FAILED', 'Failed to capture screenshot');
}
await fs.writeFile(outPath, result.stdoutBuffer);
}
export async function setAndroidSetting(
device: DeviceInfo,
setting: string,
state: string,
appPackage?: string,
options?: PermissionSettingOptions,
): Promise<void> {
const normalized = setting.toLowerCase();
switch (normalized) {
case 'wifi': {
const enabled = parseSettingState(state);
await runCmd('adb', adbArgs(device, ['shell', 'svc', 'wifi', enabled ? 'enable' : 'disable']));
return;
}
case 'airplane': {
const enabled = parseSettingState(state);
const flag = enabled ? '1' : '0';
const bool = enabled ? 'true' : 'false';
await runCmd('adb', adbArgs(device, ['shell', 'settings', 'put', 'global', 'airplane_mode_on', flag]));
await runCmd('adb', adbArgs(device, ['shell', 'am', 'broadcast', '-a', 'android.intent.action.AIRPLANE_MODE', '--ez', 'state', bool]));
return;
}
case 'location': {
const enabled = parseSettingState(state);
const mode = enabled ? '3' : '0';
await runCmd('adb', adbArgs(device, ['shell', 'settings', 'put', 'secure', 'location_mode', mode]));
return;
}
case 'permission': {
if (!appPackage) {
throw new AppError(
'INVALID_ARGS',
'permission setting requires an active app in session',
);
}
const action = parsePermissionAction(state);
const target = parseAndroidPermissionTarget(options?.permissionTarget, options?.permissionMode);
if (target.kind === 'notifications') {
await setAndroidNotificationPermission(device, appPackage, action, target);
return;
}
const pmAction = action === 'grant' ? 'grant' : 'revoke';
if (target.type === 'photos') {
await setAndroidPhotoPermission(device, appPackage, pmAction);
return;
}
await runCmd('adb', adbArgs(device, ['shell', 'pm', pmAction, appPackage, target.value]));
return;
}
default:
throw new AppError('INVALID_ARGS', `Unsupported setting: ${setting}`);
}
}
export async function snapshotAndroid(
device: DeviceInfo,
options: SnapshotOptions = {},
): Promise<{
nodes: RawSnapshotNode[];
truncated?: boolean;
}> {
const xml = await dumpUiHierarchy(device);
return parseUiHierarchy(xml, 800, options);
}
export async function ensureAdb(): Promise<void> {
const adbAvailable = await whichCmd('adb');
if (!adbAvailable) throw new AppError('TOOL_MISSING', 'adb not found in PATH');
}
async function getAndroidScreenSize(
device: DeviceInfo,
): Promise<{ width: number; height: number }> {
const result = await runCmd('adb', adbArgs(device, ['shell', 'wm', 'size']));
const match = result.stdout.match(/Physical size:\s*(\d+)x(\d+)/);
if (!match) throw new AppError('COMMAND_FAILED', 'Unable to read screen size');
return { width: Number(match[1]), height: Number(match[2]) };
}
async function dumpUiHierarchy(device: DeviceInfo): Promise<string> {
return withRetry(() => dumpUiHierarchyOnce(device), {
shouldRetry: isRetryableAdbError,
});
}
async function dumpUiHierarchyOnce(device: DeviceInfo): Promise<string> {
// Preferred: stream XML directly to stdout, avoiding file I/O race conditions.
const streamed = await runCmd(
'adb',
adbArgs(device, ['exec-out', 'uiautomator', 'dump', '/dev/tty']),
{ allowFailure: true },
);
if (streamed.exitCode === 0) {
const fromStream = extractUiDumpXml(streamed.stdout, streamed.stderr);
if (fromStream) return fromStream;
}
// Fallback: dump to file and read back.
// If `cat` fails with "no such file", the outer withRetry (via isRetryableAdbError) handles it.
const dumpPath = '/sdcard/window_dump.xml';
const dumpResult = await runCmd(
'adb',
adbArgs(device, ['shell', 'uiautomator', 'dump', dumpPath]),
);
const actualPath = resolveDumpPath(dumpPath, dumpResult.stdout, dumpResult.stderr);
const result = await runCmd('adb', adbArgs(device, ['shell', 'cat', actualPath]));
const xml = extractUiDumpXml(result.stdout, result.stderr);
if (!xml) {
throw new AppError('COMMAND_FAILED', 'uiautomator dump did not return XML', {
stdout: result.stdout,
stderr: result.stderr,
});
}
return xml;
}
function resolveDumpPath(defaultPath: string, stdout: string, stderr: string): string {
const text = `${stdout}\n${stderr}`;
const match = /dumped to:\s*(\S+)/i.exec(text);
return match?.[1] ?? defaultPath;
}
function extractUiDumpXml(stdout: string, stderr: string): string | null {
const text = `${stdout}\n${stderr}`;
const start = text.indexOf('<?xml');
const hierarchyStart = start >= 0 ? start : text.indexOf('<hierarchy');
if (hierarchyStart < 0) return null;
const end = text.lastIndexOf('</hierarchy>');
if (end < 0 || end < hierarchyStart) return null;
const xml = text.slice(hierarchyStart, end + '</hierarchy>'.length).trim();
return xml.length > 0 ? xml : null;
}
function isRetryableAdbError(err: unknown): boolean {
if (!(err instanceof AppError)) return false;
if (err.code !== 'COMMAND_FAILED') return false;
const stderr = `${(err.details as any)?.stderr ?? ''}`.toLowerCase();
if (stderr.includes('device offline')) return true;
if (stderr.includes('device not found')) return true;
if (stderr.includes('transport error')) return true;
if (stderr.includes('connection reset')) return true;
if (stderr.includes('broken pipe')) return true;
if (stderr.includes('timed out')) return true;
if (stderr.includes('no such file or directory')) return true;
return false;
}
function parseSettingState(state: string): boolean {
const normalized = state.toLowerCase();
if (normalized === 'on' || normalized === 'true' || normalized === '1') return true;
if (normalized === 'off' || normalized === 'false' || normalized === '0') return false;
throw new AppError('INVALID_ARGS', `Invalid setting state: ${state}`);
}
function parseAndroidPermissionTarget(
permissionTarget: string | undefined,
permissionMode: string | undefined,
):
| { kind: 'pm'; value: string; type: 'camera' | 'microphone' | 'photos' | 'contacts' }
| { kind: 'notifications'; appOps: string; permission: string } {
const normalized = parsePermissionTarget(permissionTarget);
if (permissionMode?.trim()) {
throw new AppError(
'INVALID_ARGS',
`Permission mode is only supported for photos. Received: ${permissionMode}.`,
);
}
if (normalized === 'camera') return { kind: 'pm', value: 'android.permission.CAMERA', type: 'camera' };
if (normalized === 'microphone') {
return { kind: 'pm', value: 'android.permission.RECORD_AUDIO', type: 'microphone' };
}
if (normalized === 'photos') {
return { kind: 'pm', value: 'android.permission.READ_MEDIA_IMAGES', type: 'photos' };
}
if (normalized === 'contacts') {
return { kind: 'pm', value: 'android.permission.READ_CONTACTS', type: 'contacts' };
}
if (normalized === 'notifications') {
return {
kind: 'notifications',
appOps: 'POST_NOTIFICATION',
permission: 'android.permission.POST_NOTIFICATIONS',
};
}
throw new AppError(
'INVALID_ARGS',
`Unsupported permission target on Android: ${permissionTarget}. Use camera|microphone|photos|contacts|notifications.`,
);
}
async function setAndroidPhotoPermission(
device: DeviceInfo,
appPackage: string,
pmAction: 'grant' | 'revoke',
): Promise<void> {
const sdkInt = await getAndroidSdkInt(device);
const candidates =
sdkInt !== null && sdkInt >= 33
? ['android.permission.READ_MEDIA_IMAGES', 'android.permission.READ_EXTERNAL_STORAGE']
: ['android.permission.READ_EXTERNAL_STORAGE', 'android.permission.READ_MEDIA_IMAGES'];
const failures: Array<{ permission: string; stderr: string; exitCode: number }> = [];
for (const permission of candidates) {
const result = await runCmd(
'adb',
adbArgs(device, ['shell', 'pm', pmAction, appPackage, permission]),
{ allowFailure: true },
);
if (result.exitCode === 0) return;
failures.push({ permission, stderr: result.stderr, exitCode: result.exitCode });
}
throw new AppError('COMMAND_FAILED', `Failed to ${pmAction} Android photos permission`, {
appPackage,
sdkInt,
attempts: failures,
});
}
async function setAndroidNotificationPermission(
device: DeviceInfo,
appPackage: string,
action: 'grant' | 'deny' | 'reset',
target: { appOps: string; permission: string },
): Promise<void> {
const appOpsMode = action === 'grant' ? 'allow' : action === 'deny' ? 'deny' : 'default';
if (action === 'grant') {
await runCmd(
'adb',
adbArgs(device, ['shell', 'pm', 'grant', appPackage, target.permission]),
{ allowFailure: true },
);
} else {
await runCmd(
'adb',
adbArgs(device, ['shell', 'pm', 'revoke', appPackage, target.permission]),
{ allowFailure: true },
);
if (action === 'reset') {
await runCmd(
'adb',
adbArgs(device, ['shell', 'pm', 'clear-permission-flags', appPackage, target.permission, 'user-set']),
{ allowFailure: true },
);
await runCmd(
'adb',
adbArgs(device, ['shell', 'pm', 'clear-permission-flags', appPackage, target.permission, 'user-fixed']),
{ allowFailure: true },
);
}
}
await runCmd('adb', adbArgs(device, ['shell', 'appops', 'set', appPackage, target.appOps, appOpsMode]));
}
async function getAndroidSdkInt(device: DeviceInfo): Promise<number | null> {
const result = await runCmd('adb', adbArgs(device, ['shell', 'getprop', 'ro.build.version.sdk']), {
allowFailure: true,
});
if (result.exitCode !== 0) return null;
const value = Number.parseInt(result.stdout.trim(), 10);
if (!Number.isFinite(value) || value <= 0) return null;
return value;
}
async function typeAndroidChunked(
device: DeviceInfo,
text: string,
chunkSize: number,
delayMs: number,
): Promise<void> {
const size = Math.max(1, Math.floor(chunkSize));
const chars = Array.from(text);
for (let i = 0; i < chars.length; i += size) {
const chunk = chars.slice(i, i + size).join('');
await typeAndroid(device, chunk);
if (delayMs > 0 && i + size < chars.length) {
await sleep(delayMs);
}
}
}
function shouldUseClipboardTextInjection(text: string): boolean {
for (const char of text) {
const code = char.codePointAt(0);
if (code === undefined) continue;
if (code < 0x20 || code > 0x7e) return true;
}
return false;
}
async function typeAndroidViaClipboard(
device: DeviceInfo,
text: string,
): Promise<'ok' | 'unsupported' | 'failed'> {
const setClipboard = await runCmd(
'adb',
adbArgs(device, ['shell', 'cmd', 'clipboard', 'set', 'text', text]),
{ allowFailure: true },
);
if (setClipboard.exitCode !== 0) return 'failed';
if (isClipboardShellUnsupported(setClipboard.stdout, setClipboard.stderr)) return 'unsupported';
const pasteByName = await runCmd(
'adb',
adbArgs(device, ['shell', 'input', 'keyevent', 'KEYCODE_PASTE']),
{ allowFailure: true },
);
if (pasteByName.exitCode === 0) return 'ok';
const pasteByCode = await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', '279']), {
allowFailure: true,
});
return pasteByCode.exitCode === 0 ? 'ok' : 'failed';
}
function isClipboardShellUnsupported(stdout: string, stderr: string): boolean {
const haystack = `${stdout}\n${stderr}`.toLowerCase();
return haystack.includes('no shell command implementation') || haystack.includes('unknown command');
}
function isAndroidInputTextUnsupported(error: unknown): boolean {
if (!(error instanceof AppError)) return false;
if (error.code !== 'COMMAND_FAILED') return false;
const stderr = String((error.details as any)?.stderr ?? '').toLowerCase();
if (stderr.includes("exception occurred while executing 'text'")) return true;
if (stderr.includes('nullpointerexception') && stderr.includes('inputshellcommand.sendtext')) return true;
return false;
}
async function clearFocusedText(device: DeviceInfo, count: number): Promise<void> {
const deletes = Math.max(0, count);
await runCmd('adb', adbArgs(device, ['shell', 'input', 'keyevent', 'KEYCODE_MOVE_END']), {
allowFailure: true,
});
const batchSize = 24;
for (let i = 0; i < deletes; i += batchSize) {
const size = Math.min(batchSize, deletes - i);
await runCmd(
'adb',
adbArgs(device, ['shell', 'input', 'keyevent', ...Array(size).fill('KEYCODE_DEL')]),
{
allowFailure: true,
},
);
}
}
async function readInputValueAtPoint(
device: DeviceInfo,
x: number,
y: number,
): Promise<string | null> {
const xml = await dumpUiHierarchy(device);
const nodeRegex = /<node\b[^>]*>/g;
let match: RegExpExecArray | null;
let focusedEdit: { text: string; area: number } | null = null;
let editAtPoint: { text: string; area: number } | null = null;
let anyAtPoint: { text: string; area: number } | null = null;
while ((match = nodeRegex.exec(xml)) !== null) {
const node = match[0];
const attrs = readNodeAttributes(node);
const rect = parseBounds(attrs.bounds);
if (!rect) continue;
const className = attrs.className ?? '';
const text = decodeXmlEntities(attrs.text ?? '');
const focused = attrs.focused ?? false;
if (!text) continue;
const area = Math.max(1, rect.width * rect.height);
const containsPoint =
x >= rect.x &&
x <= rect.x + rect.width &&
y >= rect.y &&
y <= rect.y + rect.height;
if (focused && isEditTextClass(className)) {
if (!focusedEdit || area <= focusedEdit.area) {
focusedEdit = { text, area };
}
continue;
}
if (containsPoint && isEditTextClass(className)) {
if (!editAtPoint || area <= editAtPoint.area) {
editAtPoint = { text, area };
}
continue;
}
if (containsPoint) {
if (!anyAtPoint || area <= anyAtPoint.area) {
anyAtPoint = { text, area };
}
}
}
return focusedEdit?.text ?? editAtPoint?.text ?? anyAtPoint?.text ?? null;
}
function isEditTextClass(className: string): boolean {
const lower = className.toLowerCase();
return lower.includes('edittext') || lower.includes('textfield');
}
function decodeXmlEntities(value: string): string {
return value
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')