Repository navigation
Expand file tree
/
Copy pathsnapshot.ts
More file actions
940 lines (894 loc) · 35 KB
/
Copy pathsnapshot.ts
File metadata and controls
940 lines (894 loc) · 35 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
import {
AppError,
normalizeError,
toAppErrorCode,
type NormalizedError,
} from '@agent-device/kernel/errors';
import path from 'node:path';
import { isPositiveFiniteRect, unionRects } from '@agent-device/kernel/rect';
import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics';
import type { SnapshotOptions as InteractorSnapshotOptions } from '@agent-device/contracts/interactor-types';
import type { DeviceInfo } from '@agent-device/kernel/device';
import {
attachRefs,
type HiddenContentHint,
type RawSnapshotNode,
type Rect,
type SnapshotKeyboardBandFact,
type SnapshotOptions,
type SnapshotViewportSize,
} from '@agent-device/kernel/snapshot';
import { deriveMobileSnapshotHiddenContentHints } from '@agent-device/capture-kit/mobile-snapshot-semantics';
import { findProjectRoot, readVersion } from '@agent-device/host-kit/version';
import {
buildUiHierarchySnapshot,
parseUiHierarchyTree,
type AndroidBuiltSnapshot,
type AndroidUiHierarchySnapshotOptions,
type AndroidUiHierarchy,
} from './ui-hierarchy.ts';
import { buildAndroidSnapshotClickabilityEvidence } from './snapshot-clickability.ts';
import { resolveAndroidAdbProvider, type AndroidAdbProvider } from './adb-executor.ts';
import { sleep } from './adb.ts';
import { buildAndroidSnapshotHelperCaptureOptions } from './snapshot-helper-capture.ts';
import {
ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS,
ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS,
type AndroidHelperSessionScope,
} from './snapshot-helper-types.ts';
import {
captureAndroidSnapshotWithHelper,
captureAndroidSnapshotWithHelperSession,
ensureAndroidSnapshotHelper,
forgetAndroidSnapshotHelperInstall,
stopAndroidSnapshotHelperSession,
type AndroidAdbExecutor,
type AndroidSnapshotHelperArtifact,
type AndroidSnapshotHelperInstallPolicy,
type AndroidSnapshotHelperInstallResult,
type AndroidSnapshotHelperOutput,
} from './snapshot-helper.ts';
import { getLiveAndroidSnapshotHelperSession } from './snapshot-helper-session-lifecycle.ts';
import { isAndroidSnapshotHelperNotCurrentError } from './snapshot-helper-install.ts';
import {
getAndroidSnapshotHelperSessionDeviceKey,
isAndroidSnapshotHelperRuntimeOccupiedError,
} from './snapshot-helper-retirement.ts';
import { requireAndroidAdbHost } from './adb-host.ts';
import { parseAndroidSnapshotHelperManifest } from './snapshot-helper-artifact.ts';
import type {
AndroidSnapshotBackendMetadata,
AndroidUiHierarchyCapture,
} from './snapshot-types.ts';
import {
classifyAndroidHelperContent,
type AndroidHelperContentRecoveryDecision,
} from './snapshot-content-recovery.ts';
import {
type AndroidCaptureFailureReason,
type AndroidContentRecoveryReason,
readAndroidCaptureFailureReason,
} from '@agent-device/contracts/android-snapshot-quality';
import {
resetAndroidSnapshotHelperRuntime,
retireAndroidSnapshotHelperAfterContentFailure,
} from './snapshot-helper-runtime.ts';
import {
ANDROID_SNAPSHOT_PRESENTATION_DEFAULT_DEADLINE_MS,
isAndroidSnapshotPresentationFailure,
type AndroidSnapshotPresentationFailure,
type AndroidSnapshotPresentationOptions,
} from './snapshot-presentation.ts';
import { ANDROID_WINDOW_TYPE_INPUT_METHOD, readAndroidSiblingOrder } from './ui-hierarchy-node.ts';
import {
androidSnapshotViewportFromHelperMetadata,
createAndroidSnapshotCapture,
type AndroidSnapshotCapture,
} from './snapshot-capture.ts';
const HELPER_INSTALL_TIMEOUT_MS = 30_000;
/**
* A content verdict means the capture mechanism worked but sampled a screen
* mid-transition, which resolves on its own within a frame or two. Sampling
* once turns that instant into a command failure, so re-capture a bounded
* number of times before reporting the verdict.
*/
const HELPER_CONTENT_CAPTURE_ATTEMPTS = 3;
const HELPER_CONTENT_RECAPTURE_DELAY_MS = 250;
/**
* No re-capture starts this long after the first attempt did. One attempt can spend a session start,
* a timed-out session request, and the whole one-shot command budget, so attempts counted alone let
* a busy screen run a snapshot past the daemon request envelope.
*/
const HELPER_CONTENT_RECAPTURE_WINDOW_MS = 10_000;
export type AndroidSnapshotOptions = SnapshotOptions & {
skipIdleWait?: boolean;
appBundleId?: string;
signal?: AbortSignal;
helperArtifact?: AndroidSnapshotHelperArtifact;
helperInstallPolicy?: AndroidSnapshotHelperInstallPolicy;
helperSessionScope?: AndroidHelperSessionScope;
/** The interactor contract's one-off read: no install, no kept session, no re-capture after `settleBy`. */
transient?: InteractorSnapshotOptions['transient'];
helperAdb?: AndroidAdbExecutor | AndroidAdbProvider;
includeHiddenContentHints?: boolean;
androidPresentation?: AndroidSnapshotPresentationOptions;
};
export async function captureAndroidUiHierarchyXml(
device: DeviceInfo,
options: AndroidSnapshotOptions = {},
): Promise<string> {
return (await captureAndroidUiHierarchy(device, options)).xml;
}
export async function snapshotAndroid(
device: DeviceInfo,
options: AndroidSnapshotOptions = {},
): Promise<AndroidSnapshotCapture> {
const capture = await captureAndroidUiHierarchy(device, options);
// The one place Android answers the viewport question (#3182): the helper's own display read,
// through the shared guard, so both the healthy and the presentation-failed capture below publish
// the same box the tree was measured against, and a display the helper could not address stays
// absent rather than becoming a zero.
const viewport = androidSnapshotViewportFromHelperMetadata(capture.helperMetadata);
const xml = capture.xml;
const tree = parseUiHierarchyTree(xml);
const androidSnapshot = withOcclusionScanDisclosure(capture.metadata, tree);
const keyboard = androidSnapshotKeyboardFromTree(tree, capture.metadata);
const presentationOptions: AndroidUiHierarchySnapshotOptions = {
...options,
androidPresentation: {
...options.androidPresentation,
deadlineAtMs:
options.androidPresentation?.deadlineAtMs ??
Date.now() + ANDROID_SNAPSHOT_PRESENTATION_DEFAULT_DEADLINE_MS,
},
};
try {
const built = buildUiHierarchySnapshot(tree, undefined, presentationOptions);
const truncated = mergeAndroidSnapshotTruncation(built.truncated, capture.metadata);
if (options.interactiveOnly && options.includeHiddenContentHints !== false) {
applyHiddenContentHintsToInteractiveSnapshot({
options: presentationOptions,
tree,
xml,
interactiveSnapshot: built,
});
}
const { sourceNodes: _sourceNodes, occlusionContext, ...snapshot } = built;
const result = {
...snapshot,
...androidSnapshotTruncationFields(truncated),
androidSnapshot,
quality: { state: 'healthy', backend: 'android-helper' } as const,
keyboard,
...(viewport ? { viewport } : {}),
};
return createAndroidSnapshotCapture(result, {
clickability: buildAndroidSnapshotClickabilityEvidence(built),
occlusionContext,
});
} catch (error) {
if (!isAndroidSnapshotPresentationFailure(error)) throw error;
return attachAndroidPresentationFailureEvidence({
failure: error,
androidSnapshot,
keyboard,
...(viewport ? { viewport } : {}),
});
}
}
function attachAndroidPresentationFailureEvidence(params: {
failure: AndroidSnapshotPresentationFailure;
androidSnapshot: AndroidSnapshotBackendMetadata;
keyboard: SnapshotKeyboardBandFact;
viewport?: SnapshotViewportSize;
}): AndroidSnapshotCapture {
return createAndroidSnapshotCapture(
{
nodes: [],
truncated: true,
analysis: params.failure.analysis ?? { rawNodeCount: 0, maxDepth: 0 },
androidSnapshot: {
...params.androidSnapshot,
presentationFailure: {
phase: params.failure.details.phase,
workUnits: params.failure.details.workUnits,
...(params.failure.details.maxWorkUnits !== undefined
? { maxWorkUnits: params.failure.details.maxWorkUnits }
: {}),
},
},
quality: {
state: 'sparse',
backend: 'android-helper',
reason: params.failure.message,
reasonCode: params.failure.qualityReasonCode,
},
keyboard: params.keyboard,
...(params.viewport ? { viewport: params.viewport } : {}),
},
{
clickability: {
kind: 'exact',
provider: 'android-helper',
clickableByNodeIndex: new Map(),
},
},
);
}
function mergeAndroidSnapshotTruncation(
snapshotTruncated: boolean | undefined,
metadata: AndroidSnapshotBackendMetadata,
): boolean | undefined {
return snapshotTruncated === true || metadata.helperTruncated === true ? true : snapshotTruncated;
}
function withOcclusionScanDisclosure(
metadata: AndroidSnapshotBackendMetadata,
tree: AndroidUiHierarchy,
): AndroidSnapshotBackendMetadata {
return androidTreeCarriesDrawingOrder(tree) === false
? { ...metadata, occlusionScanUnavailable: true }
: metadata;
}
function androidTreeCarriesDrawingOrder(root: AndroidUiHierarchy): boolean | undefined {
const pending = [...root.children];
if (pending.length === 0) return undefined;
while (pending.length > 0) {
const node = pending.pop()!;
if (readAndroidSiblingOrder(node) !== undefined) return true;
pending.push(...node.children);
}
return false;
}
function androidSnapshotTruncationFields(
truncated: boolean | undefined,
): { truncated: true } | Record<string, never> {
return truncated === true ? { truncated: true } : {};
}
function applyHiddenContentHintsToInteractiveSnapshot(params: {
options: AndroidSnapshotOptions;
tree: AndroidUiHierarchy;
xml: string;
interactiveSnapshot: AndroidBuiltSnapshot;
}): void {
if (
collectExistingHiddenContentHints(params.interactiveSnapshot.nodes).size > 0 ||
hasAndroidScrollActionAttributes(params.xml)
) {
return;
}
const fullSnapshot = buildUiHierarchySnapshot(params.tree, undefined, {
...params.options,
interactiveOnly: false,
});
const presentationHints = deriveMobileSnapshotHiddenContentHints(attachRefs(fullSnapshot.nodes));
applyHiddenContentHintsToInteractiveNodes(
presentationHints,
fullSnapshot,
params.interactiveSnapshot,
);
}
export async function captureAndroidUiHierarchy(
device: DeviceInfo,
options: AndroidSnapshotOptions = {},
): Promise<AndroidUiHierarchyCapture> {
const adbProvider = resolveAndroidAdbProvider(device, options.helperAdb);
const helper = await withDiagnosticTimer(
'android_snapshot_helper_artifact_resolution',
async () =>
await resolveAndroidSnapshotHelperArtifact(
options.helperArtifact ?? adbProvider.snapshotHelperArtifact,
),
);
if (helper.artifact) {
return await captureAndroidUiHierarchyWithHelper(
device,
options,
adbProvider.exec,
helper.artifact,
);
}
emitDiagnostic({
level: 'error',
phase: 'android_snapshot_helper_unavailable',
data: { reason: helper.errorReason ?? 'artifact_not_found' },
});
throw androidSnapshotHelperUnavailableError(helper.errorReason);
}
async function captureAndroidUiHierarchyWithHelper(
device: DeviceInfo,
options: AndroidSnapshotOptions,
adb: AndroidAdbExecutor,
artifact: AndroidSnapshotHelperArtifact,
): Promise<AndroidUiHierarchyCapture> {
const helperDeviceKey = getAndroidSnapshotHelperSessionDeviceKey(device);
const releaseHelperSession = await releasesHelperSessionAfterCapture(options, helperDeviceKey);
try {
return await captureAndroidHelperContentWithinWindow({
options,
adb,
adbProvider: resolveAndroidAdbProvider(device, options.helperAdb),
artifact,
helperDeviceKey,
});
} finally {
if (releaseHelperSession) {
await stopAndroidSnapshotHelperSession(helperDeviceKey);
}
}
}
/**
* Re-captures unusable content until a capture answers, the attempts run out, or the re-capture
* window has closed by the time the next attempt would start.
*/
async function captureAndroidHelperContentWithinWindow(params: {
options: AndroidSnapshotOptions;
adb: AndroidAdbExecutor;
adbProvider: AndroidAdbProvider;
artifact: AndroidSnapshotHelperArtifact;
helperDeviceKey: string;
}): Promise<AndroidUiHierarchyCapture> {
const { options } = params;
const recaptureDeadlineMs = resolveContentRecaptureDeadlineMs(options);
const rejectContentUnavailable = async (
contentRecovery: AndroidHelperContentRecoveryDecision,
attempts: number,
) =>
await rejectAndroidHelperContentUnavailable({
contentRecovery,
attempts,
helperDeviceKey: params.helperDeviceKey,
artifact: params.artifact,
adb: params.adb,
signal: options.signal,
retireHelper: options.transient === undefined,
});
let previousDecision: AndroidHelperContentRecoveryDecision | undefined;
for (let attempt = 0; ; attempt += 1) {
if (previousDecision) {
await delayBeforeContentRecapture(options.signal);
if (Date.now() >= recaptureDeadlineMs) {
return await rejectContentUnavailable(previousDecision, attempt);
}
}
const settled = await captureAndroidHelperContentAttempt({
...params,
attempt,
previousContentReason: previousDecision?.reason,
});
if (settled.outcome === 'captured') return settled.capture;
if (attempt + 1 >= HELPER_CONTENT_CAPTURE_ATTEMPTS || Date.now() >= recaptureDeadlineMs) {
return await rejectContentUnavailable(settled.decision, attempt + 1);
}
previousDecision = settled.decision;
}
}
/** No re-capture starts after this instant: the end of the window, or a transient read's settle-by. */
function resolveContentRecaptureDeadlineMs(options: AndroidSnapshotOptions): number {
return Math.min(
Date.now() + HELPER_CONTENT_RECAPTURE_WINDOW_MS,
options.transient?.settleBy ?? Number.POSITIVE_INFINITY,
);
}
/** A transient read keeps a session it found running and releases one it had to start. */
async function releasesHelperSessionAfterCapture(
options: AndroidSnapshotOptions,
helperDeviceKey: string,
): Promise<boolean> {
if (options.transient)
return (await getLiveAndroidSnapshotHelperSession(helperDeviceKey)) === undefined;
return options.helperSessionScope !== 'daemon-session';
}
/** A transient read never installs the helper; it uses one that is already current. */
function resolveHelperInstallPolicy(
options: AndroidSnapshotOptions,
): AndroidSnapshotHelperInstallPolicy {
return options.transient
? 'current-only'
: (options.helperInstallPolicy ?? 'missing-or-outdated');
}
async function installAndroidSnapshotHelper(
options: AndroidSnapshotOptions,
adb: AndroidAdbExecutor,
adbProvider: AndroidAdbProvider,
artifact: AndroidSnapshotHelperArtifact,
deviceKey: string,
): Promise<AndroidSnapshotHelperInstallResult> {
const install = await withDiagnosticTimer(
'android_snapshot_helper_install',
async () =>
await ensureAndroidSnapshotHelper({
adb,
adbProvider,
artifact,
deviceKey,
installPolicy: resolveHelperInstallPolicy(options),
timeoutMs: HELPER_INSTALL_TIMEOUT_MS,
signal: options.signal,
}),
{
packageName: artifact.manifest.packageName,
versionCode: artifact.manifest.versionCode,
installPolicy: resolveHelperInstallPolicy(options),
},
);
emitDiagnostic({
phase: 'android_snapshot_helper_install_decision',
data: {
packageName: install.packageName,
versionCode: install.versionCode,
installedVersionCode: install.installedVersionCode,
artifactSha256: artifact.manifest.sha256,
installedSha256: install.installedSha256,
installed: install.installed,
reason: install.reason,
},
});
return install;
}
async function captureAndroidUiHierarchyFromHelper(params: {
skipIdleWait?: boolean;
signal?: AbortSignal;
adb: AndroidAdbExecutor;
adbProvider: AndroidAdbProvider;
artifact: AndroidSnapshotHelperArtifact;
helperDeviceKey: string;
}): Promise<AndroidSnapshotHelperOutput> {
const { signal, adb, adbProvider, artifact, helperDeviceKey } = params;
const captureOptions = buildAndroidSnapshotHelperCaptureOptions({
adb,
adbProvider,
artifact,
deviceKey: helperDeviceKey,
signal,
});
captureOptions.skipIdleWait = params.skipIdleWait;
try {
const sessionCapture = await withDiagnosticTimer(
'android_snapshot_helper_session_capture',
async () => await captureAndroidSnapshotWithHelperSession(captureOptions),
{
packageName: artifact.manifest.packageName,
version: artifact.manifest.version,
timeoutMs: ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS,
},
);
if (sessionCapture) return sessionCapture;
} catch (error) {
signal?.throwIfAborted();
if (isAndroidSnapshotHelperRuntimeOccupiedError(error)) {
throw error;
}
emitDiagnostic({
level: 'warn',
phase: 'android_snapshot_helper_session_fallback',
data: { reason: normalizeError(error).message },
});
await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName);
}
return await withDiagnosticTimer(
'android_snapshot_helper_capture',
async () => await captureAndroidSnapshotWithHelper(captureOptions),
{
packageName: artifact.manifest.packageName,
version: artifact.manifest.version,
timeoutMs: ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS,
commandTimeoutMs: ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS,
},
);
}
function formatAndroidHelperCaptureResult(
capture: AndroidSnapshotHelperOutput,
artifact: AndroidSnapshotHelperArtifact,
installReason: AndroidSnapshotHelperInstallResult['reason'],
): AndroidUiHierarchyCapture {
return {
xml: capture.xml,
helperMetadata: capture.metadata,
metadata: {
backend: 'android-helper',
pixelDensity: capture.metadata.pixelDensity,
helperVersion: artifact.manifest.version,
helperApiVersion: capture.metadata.helperApiVersion,
helperTransport: capture.metadata.transport,
helperSessionReused: capture.metadata.sessionReused,
installReason,
waitForIdleTimeoutMs: capture.metadata.waitForIdleTimeoutMs,
waitForIdleQuietMs: capture.metadata.waitForIdleQuietMs,
timeoutMs: capture.metadata.timeoutMs,
maxDepth: capture.metadata.maxDepth,
maxNodes: capture.metadata.maxNodes,
rootPresent: capture.metadata.rootPresent,
cacheInvalidated: capture.metadata.cacheInvalidated,
captureMode: capture.metadata.captureMode,
windowCount: capture.metadata.windowCount,
missingRootWindowTypes: capture.metadata.missingRootWindowTypes,
nodeCount: capture.metadata.nodeCount,
helperTruncated: capture.metadata.truncated,
elapsedMs: capture.metadata.elapsedMs,
},
};
}
type AndroidHelperContentAttempt =
| { outcome: 'captured'; capture: AndroidUiHierarchyCapture }
| { outcome: 'unusable'; decision: AndroidHelperContentRecoveryDecision };
async function captureAndroidHelperContentAttempt(params: {
options: AndroidSnapshotOptions;
adb: AndroidAdbExecutor;
adbProvider: AndroidAdbProvider;
artifact: AndroidSnapshotHelperArtifact;
helperDeviceKey: string;
attempt: number;
previousContentReason: AndroidContentRecoveryReason | undefined;
}): Promise<AndroidHelperContentAttempt> {
const { options, adb, adbProvider, artifact, helperDeviceKey, attempt } = params;
let helperCapture: AndroidUiHierarchyCapture;
try {
const install = await installAndroidSnapshotHelper(
options,
adb,
adbProvider,
artifact,
helperDeviceKey,
);
if (install.installed) {
await stopAndroidSnapshotHelperSession(helperDeviceKey);
}
const capture = await captureAndroidUiHierarchyFromHelper({
skipIdleWait: options.skipIdleWait,
signal: options.signal,
adb,
adbProvider,
artifact,
helperDeviceKey,
});
helperCapture = formatAndroidHelperCaptureResult(capture, artifact, install.reason);
} catch (error) {
options.signal?.throwIfAborted();
if (isAndroidSnapshotHelperNotCurrentError(error)) throw error;
return {
outcome: 'captured',
capture: await rejectAndroidHelperCaptureFailure({
error,
helperDeviceKey,
artifact,
adb,
}),
};
}
const content = classifyAndroidHelperContent(helperCapture.xml, helperCapture.metadata, {
foregroundAppPackage: options.appBundleId,
});
if (content.outcome === 'unusable') {
return { outcome: 'unusable', decision: content.decision };
}
// Only content the helper cannot answer with is worth another call. A tree holding just the
// system surface is an answer, and `systemSurfaceOnly` on the capture is where it is recorded:
// it travels with the response and becomes the disclosure the caller reads.
const systemSurfaceOnly = content.outcome === 'system-surface-only';
if (!systemSurfaceOnly && attempt > 0) {
emitDiagnostic({
phase: 'android_snapshot_helper_content_recaptured',
data: { attempts: attempt + 1, recoveredFromReason: params.previousContentReason },
});
}
return {
outcome: 'captured',
capture: {
xml: helperCapture.xml,
helperMetadata: helperCapture.helperMetadata,
metadata: systemSurfaceOnly
? { ...helperCapture.metadata, systemSurfaceOnly: true }
: helperCapture.metadata,
},
};
}
async function delayBeforeContentRecapture(signal?: AbortSignal): Promise<void> {
signal?.throwIfAborted();
await sleep(HELPER_CONTENT_RECAPTURE_DELAY_MS);
signal?.throwIfAborted();
}
async function rejectAndroidHelperContentUnavailable(params: {
contentRecovery: AndroidHelperContentRecoveryDecision;
attempts: number;
helperDeviceKey: string;
artifact: AndroidSnapshotHelperArtifact;
adb: AndroidAdbExecutor;
signal?: AbortSignal;
/** A transient capture does not own the helper, so its content verdict leaves the helper alone. */
retireHelper: boolean;
}): Promise<never> {
emitDiagnostic({
level: 'error',
phase: 'android_snapshot_helper_content_invalid',
data: {
reason: params.contentRecovery.reason,
failureReason: params.contentRecovery.failureReason,
attempts: params.attempts,
...params.contentRecovery.diagnostics,
},
});
if (params.retireHelper) {
await retireAndroidSnapshotHelperAfterContentFailure({
adb: params.adb,
deviceKey: params.helperDeviceKey,
packageName: params.artifact.manifest.packageName,
signal: params.signal,
cause: params.contentRecovery.failureReason,
});
}
throw androidHelperContentUnavailableError(params.contentRecovery, params.attempts);
}
/** The retriable content verdict a capture reports once its re-captures still see no content. */
export function androidHelperContentUnavailableError(
contentRecovery: AndroidHelperContentRecoveryDecision,
attempts: number,
): AppError {
return new AppError('COMMAND_FAILED', contentRecovery.failureReason, {
...contentRecovery.diagnostics,
androidSnapshotHelperFailureReason: contentRecovery.reason,
attempts,
retriable: true,
hint: 'Retry after the app UI stabilizes. If this persists, capture a screenshot and report the helper diagnostics; agent-device does not substitute a second snapshot engine.',
});
}
async function rejectAndroidHelperCaptureFailure(params: {
error: unknown;
helperDeviceKey: string;
artifact: AndroidSnapshotHelperArtifact;
adb: AndroidAdbExecutor;
}): Promise<never> {
const failureReason = formatAndroidSnapshotHelperFailureReason(params.error);
emitDiagnostic({
level: 'error',
phase: 'android_snapshot_helper_failed',
data: { reason: failureReason },
});
await stopAndroidSnapshotHelperSession(params.helperDeviceKey);
await resetAndroidSnapshotHelperRuntime(params.adb, params.artifact.manifest.packageName);
forgetAndroidSnapshotHelperInstall({
deviceKey: params.helperDeviceKey,
packageName: params.artifact.manifest.packageName,
versionCode: params.artifact.manifest.versionCode,
});
throw androidSnapshotHelperCaptureError(params.error, failureReason);
}
function formatAndroidSnapshotHelperFailureReason(error: unknown): string {
const normalized = normalizeError(error);
const helperMessage = readHelperMessage(normalized.details?.helper);
if (helperMessage && helperMessage !== normalized.message) {
return `${normalized.message}: ${helperMessage}`;
}
if (helperMessage) return helperMessage;
const stderr =
typeof normalized.details?.stderr === 'string' ? normalized.details.stderr.trim() : '';
const firstLine = stderr.split(/\r?\n/).find((line) => line.trim());
return firstLine ? `${normalized.message}: ${firstLine}` : normalized.message;
}
function androidSnapshotHelperCaptureError(error: unknown, reason: string): AppError {
const normalized = normalizeError(error);
const captureFailureReason = androidCaptureFailureReasonOf(normalized);
return new AppError(
toAppErrorCode(normalized.code),
`Android snapshot helper failed: ${reason}`,
{
...normalized.details,
...liftedWireFields(normalized),
androidSnapshotHelperFailureReason: reason,
...(captureFailureReason ? { androidCaptureFailureReason: captureFailureReason } : {}),
hint: androidSnapshotHelperCaptureHint(normalized, captureFailureReason),
},
error,
);
}
/**
* The typed reason the capture already carries, if its producer named one (#1983).
*
* This rewraps rather than reclassifies. `snapshot-capture-failure-reason.ts` decides at the
* deepest boundary, from machine-defined values — the helper's structured `errorType`, or the
* SIGKILL exit code — so no message shape is consulted here or below. Rewording helper or
* wrapper prose cannot change the reason, and prose that merely reads like a timeout does not
* become one.
*/
function androidCaptureFailureReasonOf(
normalized: NormalizedError,
): AndroidCaptureFailureReason | undefined {
return readAndroidCaptureFailureReason(normalized);
}
// The prose is derived from the typed reason rather than deciding alongside it, so rewording a
// hint can never change what a reader concludes about the failure.
function androidSnapshotHelperCaptureHint(
normalized: NormalizedError,
captureFailureReason: AndroidCaptureFailureReason | undefined,
): string {
if (captureFailureReason === 'accessibility-timeout') {
return 'Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout and report the busy UI if it persists.';
}
if (normalized.details?.androidSnapshotHelperInstallFailure === true) {
return [
normalized.hint,
'This is a device-side install failure (adb rejection or OEM policy) — the helper artifact itself is present, this is not a missing/unbuilt build.',
]
.filter(Boolean)
.join(' ');
}
return (
normalized.hint ??
'Retry once. If the helper still fails, run agent-device doctor and report the diagnostic log; agent-device does not substitute a second snapshot engine.'
);
}
// normalizeError hoists these wire-contract fields out of details (ADR 0010;
// the complete set stripDiagnosticMeta removes, minus hint, which
// androidSnapshotHelperCaptureHint owns). A rewrap must put every one back so
// upstream diagnostics and typed signals like `retriable` survive.
function liftedWireFields(normalized: NormalizedError): Record<string, string | boolean> {
const fields: Record<string, string | boolean> = {};
if (normalized.diagnosticId !== undefined) fields.diagnosticId = normalized.diagnosticId;
if (normalized.logPath !== undefined) fields.logPath = normalized.logPath;
if (normalized.retriable !== undefined) fields.retriable = normalized.retriable;
if (normalized.supportedOn !== undefined) fields.supportedOn = normalized.supportedOn;
return fields;
}
function readHelperMessage(helper: unknown): string | undefined {
if (!helper || typeof helper !== 'object' || !('message' in helper)) return undefined;
const message = String(helper.message).trim();
return message && message !== 'null' ? message : undefined;
}
async function resolveAndroidSnapshotHelperArtifact(
explicitArtifact?: AndroidSnapshotHelperArtifact,
): Promise<{ artifact?: AndroidSnapshotHelperArtifact; errorReason?: string }> {
if (explicitArtifact) {
return { artifact: explicitArtifact };
}
const version = readVersion();
const helperDir = path.join(findProjectRoot(), 'android', 'snapshot-helper', 'dist');
const manifestPath = path.join(
helperDir,
`agent-device-android-snapshot-helper-${version}.manifest.json`,
);
try {
await requireAndroidAdbHost().files.access(manifestPath);
} catch {
return {};
}
try {
const manifest = parseAndroidSnapshotHelperManifest(
JSON.parse(await requireAndroidAdbHost().files.readText(manifestPath)),
);
const apkPath = path.join(
helperDir,
manifest.assetName ?? `agent-device-android-snapshot-helper-${manifest.version}.apk`,
);
await requireAndroidAdbHost().files.access(apkPath);
return { artifact: { apkPath, manifest } };
} catch (error) {
return { errorReason: normalizeError(error).message };
}
}
function androidSnapshotHelperUnavailableError(errorReason: string | undefined): AppError {
const reason = errorReason ?? 'the bundled helper artifact was not found';
return new AppError('COMMAND_FAILED', `Android snapshot helper is unavailable: ${reason}`, {
androidSnapshotHelperFailureReason: reason,
hint: 'Run `pnpm build:android` to build the helper dist for a source checkout — the runtime needs android/snapshot-helper/dist/agent-device-android-snapshot-helper-<version>.manifest.json and the .apk it references. Packaged installs ship these via the prepack script; if they are missing from a packaged install, reinstall agent-device.',
});
}
// The helper emits `can-scroll-*` for exactly the nodes Android reports as scrollable, so their
// absence means nothing on screen scrolls rather than that scroll state is unknown. A true result
// therefore means the hints parsed from those attributes are already authoritative, and callers
// fall back to guessing hidden content from geometry only when the helper reported no scrollable
// node at all.
function hasAndroidScrollActionAttributes(xml: string): boolean {
return xml.includes(' can-scroll-forward=') || xml.includes(' can-scroll-backward=');
}
function collectExistingHiddenContentHints(
nodes: RawSnapshotNode[],
): Map<number, HiddenContentHint> {
const hintsByIndex = new Map<number, HiddenContentHint>();
for (const node of nodes) {
const hint: HiddenContentHint = {};
if (node.hiddenContentAbove) {
hint.hiddenContentAbove = true;
}
if (node.hiddenContentBelow) {
hint.hiddenContentBelow = true;
}
if (hint.hiddenContentAbove || hint.hiddenContentBelow) {
hintsByIndex.set(node.index, hint);
}
}
return hintsByIndex;
}
function applyHiddenContentHintsToInteractiveNodes(
hintsByFullNodeIndex: ReadonlyMap<number, HiddenContentHint>,
fullSnapshot: AndroidBuiltSnapshot,
interactiveSnapshot: AndroidBuiltSnapshot,
): void {
if (hintsByFullNodeIndex.size === 0) {
return;
}
// Both snapshots come from one parsed hierarchy, so source node identity is the stable bridge
// between full geometry context and the pruned interactive output.
const interactiveNodesBySource = new Map<AndroidUiHierarchy, RawSnapshotNode>();
for (const [index, sourceNode] of interactiveSnapshot.sourceNodes.entries()) {
const node = interactiveSnapshot.nodes[index];
if (node) {
interactiveNodesBySource.set(sourceNode, node);
}
}
for (const [fullIndex, hint] of hintsByFullNodeIndex) {
const sourceNode = fullSnapshot.sourceNodes[fullIndex];
if (!sourceNode) {
continue;
}
const interactiveNode = interactiveNodesBySource.get(sourceNode);
if (!interactiveNode) {
continue;
}
if (hint.hiddenContentAbove) {
interactiveNode.hiddenContentAbove = true;
}
if (hint.hiddenContentBelow) {
interactiveNode.hiddenContentBelow = true;
}
}
}
/**
* The keyboard band an Android capture measured, read from the window roots the helper already
* captured: each root carries its `AccessibilityWindowInfo` type and screen bounds, so this costs no
* adb call. Bounds are screen pixels, the same space as every node rect.
*
* An input method that draws nothing (agent-device's test IME) puts no window on screen and reads as
* `absent`, and so does an input method window whose bounds parsed to an empty box. One whose bounds
* did not parse, or parsed to non-finite numbers, was seen but not measured, so the band is
* unmeasurable even when another input method window did measure. The same holds for an input method
* window the helper listed but could not serialize because its root read null or threw: the helper
* names those windows' types in `missingRootWindowTypes`. Absence is only read from a window-list
* capture: the active-window fallback never saw the window list, a root without window metadata
* cannot be ruled out as the input method, and a truncated capture may have stopped before it. A
* helper too old to report `missingRootWindowTypes` is trusted on the roots it serialized.
*
* The bounds are the box around the window's touchable region, and a floating keyboard's region is
* several rects with app content between them, so an input method window whose region the helper
* read as not rectangular is unmeasurable too: the tap guard then falls back to the tree. Below API
* 33 the helper cannot read the region, and the bounds are trusted as the band.
*/
export function androidSnapshotKeyboardFromTree(
tree: AndroidUiHierarchy,
metadata: Pick<
AndroidSnapshotBackendMetadata,
'captureMode' | 'helperTruncated' | 'missingRootWindowTypes'
>,
): SnapshotKeyboardBandFact {
const windows = tree.children;
const inputMethodWindows = windows.filter(
(window) => window.windowType === ANDROID_WINDOW_TYPE_INPUT_METHOD,
);
const inputMethodRects: Rect[] = [];
for (const { windowRect, windowRegionRect } of inputMethodWindows) {
if (windowRegionRect === false) {
return { kind: 'unmeasurable', reason: 'window-region-not-rectangular' };
}
if (isPositiveFiniteRect(windowRect)) inputMethodRects.push(windowRect);
else if (!isEmptyFiniteRect(windowRect)) {
return { kind: 'unmeasurable', reason: 'window-bounds-unavailable' };
}
}
if (metadata.missingRootWindowTypes?.includes(ANDROID_WINDOW_TYPE_INPUT_METHOD)) {
return { kind: 'unmeasurable', reason: 'window-root-unavailable' };
}
if (inputMethodRects.length > 0) return { kind: 'visible', frame: unionRects(inputMethodRects) };
if (
metadata.captureMode !== 'interactive-windows' ||
windows.some((window) => window.windowType === undefined)
) {
return { kind: 'unmeasurable', reason: 'window-list-unavailable' };
}
if (metadata.helperTruncated === true) {
return { kind: 'unmeasurable', reason: 'capture-truncated' };
}
return { kind: 'absent' };
}
function isEmptyFiniteRect(rect: Rect | undefined): boolean {
if (!rect) return false;
if (![rect.x, rect.y, rect.width, rect.height].every(Number.isFinite)) return false;
return rect.width === 0 || rect.height === 0;
}