Repository navigation
Expand file tree
/
Copy pathsnapshot.ts
More file actions
448 lines (415 loc) · 16.2 KB
/
Copy pathsnapshot.ts
File metadata and controls
448 lines (415 loc) · 16.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
import {
copySnapshotClickabilityEvidence,
publicSnapshotCaptureAnnotations,
snapshotCaptureAnnotationsFrom,
type DiffSnapshotCommandResult,
type PublicSnapshotCaptureAnnotations,
type SnapshotCaptureAnnotations,
type SnapshotDiagnosticsSummary,
} from '@agent-device/contracts/capture';
import { AppError } from '@agent-device/kernel/errors';
import { normalizeType } from '@agent-device/contracts/snapshot';
import type {
SnapshotKeyboardBandFact,
SnapshotNode,
SnapshotState,
SnapshotUnchanged,
SnapshotVisibility,
} from '@agent-device/kernel/snapshot';
import type { BackendSnapshotResult } from '../../../backend.ts';
import type { AgentDeviceRuntime, CommandSessionRecord } from '../../../runtime-contract.ts';
import {
buildSnapshotDiff,
countSnapshotComparableLines,
} from '@agent-device/capture-kit/snapshot-diff';
import {
renderSnapshotQualityWarnings,
truncatedCaptureWarning,
} from '@agent-device/capture-kit/quality-warnings';
import { formatPostGestureOutcomeWarning } from '@agent-device/capture-kit/post-gesture-stability';
import { buildSnapshotVisibility } from '@agent-device/capture-kit/snapshot-visibility';
import { ANDROID_SYSTEM_SURFACE_DISCLOSURE } from '@agent-device/contracts/android-system-surface-disclosure';
import { formatReactNativeOverlayWarning } from '../../react-native/overlay.ts';
import { now } from '../../runtime-common.ts';
import { iosSnapshotTruncationEvidence } from '@agent-device/capture-kit/ios-snapshot-acquisition';
import type {
DiffSnapshotCommandOptions,
RuntimeCommand,
SnapshotCommandOptions,
} from '../../runtime-types.ts';
import {
buildUnchangedSnapshotMetadata,
ensureSnapshotPresentationKey,
} from './snapshot-unchanged.ts';
export type SnapshotCommandResult = {
nodes: SnapshotNode[];
truncated?: boolean;
appName?: string;
appBundleId?: string;
visibility?: SnapshotVisibility;
unchanged?: SnapshotUnchanged;
snapshotDiagnostics?: SnapshotDiagnosticsSummary;
/**
* The keyboard band this capture's producer measured (#2660). The acting commands read it off the
* session state they act with; it is published here so a caller can see why a tap behind the
* keyboard was refused without reconstructing the band from the tree.
*/
keyboard?: SnapshotKeyboardBandFact;
} & PublicSnapshotCaptureAnnotations;
type SnapshotCapture = {
snapshot: SnapshotState;
result: BackendSnapshotResult;
session: CommandSessionRecord | undefined;
annotations: SnapshotCaptureAnnotations;
warnings: string[];
};
export const snapshotCommand: RuntimeCommand<
SnapshotCommandOptions,
SnapshotCommandResult
> = async (runtime, options): Promise<SnapshotCommandResult> => {
const capture = await captureRuntimeSnapshot(runtime, options);
const unchanged = buildUnchangedSnapshotMetadata({
previous: capture.session?.snapshot,
current: capture.snapshot,
options,
identity: {
previousAppBundleId: capture.session?.appBundleId,
currentAppBundleId: capture.result.appBundleId ?? capture.session?.appBundleId,
},
});
await runtime.sessions.set(nextSnapshotSession(options.session, capture));
const truncated = snapshotTruncationForResult(capture.snapshot);
return copySnapshotClickabilityEvidence(capture.snapshot, {
nodes: capture.snapshot.nodes,
...(truncated === undefined ? {} : { truncated }),
visibility: buildSnapshotVisibility({
nodes: capture.snapshot.nodes,
backend: capture.snapshot.backend,
snapshotRaw: options.raw,
}),
...publicSnapshotCaptureAnnotations({
...capture.annotations,
warnings: capture.warnings,
}),
...(unchanged ? { unchanged } : {}),
...(capture.result.snapshotDiagnostics
? { snapshotDiagnostics: capture.result.snapshotDiagnostics }
: {}),
...(capture.snapshot.keyboard ? { keyboard: capture.snapshot.keyboard } : {}),
...snapshotAppFields(capture),
});
};
export const diffSnapshotCommand: RuntimeCommand<
DiffSnapshotCommandOptions,
DiffSnapshotCommandResult
> = async (runtime, options): Promise<DiffSnapshotCommandResult> => {
const capture = await captureRuntimeSnapshot(runtime, options);
const flattenForDiff = options.interactiveOnly === true;
const previousSnapshot = capture.session?.snapshot;
const nextSession = nextSnapshotSession(options.session, capture);
if (!previousSnapshot) {
const unchanged = countSnapshotComparableLines(capture.snapshot.nodes, {
flatten: flattenForDiff,
});
await runtime.sessions.set(nextSession);
return {
mode: 'snapshot',
baselineInitialized: true,
summary: {
additions: 0,
removals: 0,
unchanged,
},
lines: [],
...(capture.warnings.length > 0 ? { warnings: capture.warnings } : {}),
};
}
const diff = buildSnapshotDiff(previousSnapshot.nodes, capture.snapshot.nodes, {
flatten: flattenForDiff,
});
await runtime.sessions.set(nextSession);
return {
mode: 'snapshot',
baselineInitialized: false,
summary: diff.summary,
lines: diff.lines,
...(capture.warnings.length > 0 ? { warnings: capture.warnings } : {}),
};
};
async function captureRuntimeSnapshot(
runtime: AgentDeviceRuntime,
options: SnapshotCommandOptions,
): Promise<SnapshotCapture> {
if (!runtime.backend.captureSnapshot) {
throw new AppError('UNSUPPORTED_OPERATION', 'snapshot is not supported by this backend');
}
const sessionName = options.session ?? 'default';
const session = await runtime.sessions.get(sessionName);
const result = await runtime.backend.captureSnapshot(
{
session: sessionName,
requestId: options.requestId,
appId: session?.appId,
appBundleId: session?.appBundleId,
signal: options.signal ?? runtime.signal,
metadata: options.metadata,
},
{
interactiveOnly: options.interactiveOnly,
depth: options.depth,
scope: options.scope,
raw: options.raw,
customActions: options.customActions,
},
);
const normalizedSnapshot = normalizeBackendSnapshot(result, runtime);
const snapshot = copySnapshotClickabilityEvidence(
normalizedSnapshot,
ensureSnapshotPresentationKey(normalizedSnapshot, options),
);
const annotations = snapshotCaptureAnnotationsFrom(result);
const warningTime = now(runtime);
return {
snapshot,
result,
session,
annotations,
warnings: buildSnapshotWarnings({
result,
annotations,
snapshot,
options,
session,
capturedAt: snapshot.createdAt ?? warningTime,
runtimeNow: warningTime,
}),
};
}
function normalizeBackendSnapshot(
result: BackendSnapshotResult,
runtime: AgentDeviceRuntime,
): SnapshotState {
if (result.snapshot) return result.snapshot;
return {
nodes: result.nodes ?? [],
truncated: result.truncated,
backend: result.backend as SnapshotState['backend'],
createdAt: now(runtime),
...(result.keyboard ? { keyboard: result.keyboard } : {}),
};
}
function nextSnapshotSession(
requestedName: string | undefined,
capture: SnapshotCapture,
): CommandSessionRecord {
const name = capture.session?.name ?? requestedName ?? 'default';
return {
...(capture.session ?? { name }),
name,
snapshot: capture.snapshot,
appName: capture.result.appName ?? capture.session?.appName,
appBundleId: capture.result.appBundleId ?? capture.session?.appBundleId,
};
}
function snapshotAppFields(capture: SnapshotCapture): {
appName?: string;
appBundleId?: string;
} {
const appName = capture.result.appName ?? capture.session?.appName;
const appBundleId = capture.result.appBundleId ?? capture.session?.appBundleId;
return {
...(appName || appBundleId ? { appName: appName ?? appBundleId } : {}),
...(appBundleId ? { appBundleId } : {}),
};
}
/**
* A capture that reported nothing about truncation is only "not truncated" when its producer
* actually observes truncation. Producers that do not (Appium page source, the Limrun element
* tree) leave it unknown rather than having the absence upgraded to `false` (#2188 invariant 5).
*/
function snapshotTruncationForResult(snapshot: SnapshotState): boolean | undefined {
if (snapshot.truncated !== undefined) return snapshot.truncated;
if (snapshot.backend !== 'xctest' || snapshot.producer === undefined) return false;
return iosSnapshotTruncationEvidence(snapshot.producer) === 'unavailable' ? undefined : false;
}
function buildSnapshotWarnings(params: {
result: BackendSnapshotResult;
annotations: SnapshotCaptureAnnotations;
snapshot: SnapshotState;
options: SnapshotCommandOptions;
session: CommandSessionRecord | undefined;
capturedAt: number;
runtimeNow: number;
}): string[] {
const warnings = [...(params.annotations.warnings ?? [])];
if (params.annotations.quality) {
warnings.push(
...renderSnapshotQualityWarnings(params.annotations.quality, params.snapshot.nodes),
);
}
warnings.push(...truncatedCaptureWarning(snapshotTruncationForResult(params.snapshot)));
if (params.snapshot.postGestureOutcome) {
warnings.push(formatPostGestureOutcomeWarning(params.snapshot.postGestureOutcome));
}
warnings.push(...buildEmptyAndroidInteractiveWarnings(params));
if (!params.annotations.quality) {
// Legacy runners without a structured verdict keep the old daemon-side heuristics.
warnings.push(...buildSparseIosInteractiveWarnings(params));
warnings.push(...buildMergedAccessibilityLeafWarnings(params.snapshot.nodes));
}
const reactNativeOverlayWarning = formatReactNativeOverlayWarning(params.snapshot.nodes);
if (reactNativeOverlayWarning) warnings.push(reactNativeOverlayWarning);
const systemSurfaceWarning = formatAndroidSystemSurfaceWarning(params.annotations);
if (systemSurfaceWarning) warnings.push(systemSurfaceWarning);
const recentDropWarning = formatRecentSnapshotDropWarning(params);
if (recentDropWarning) warnings.push(recentDropWarning);
warnings.push(...formatFreshnessWarnings(params.annotations.freshness, params.snapshot.backend));
return Array.from(new Set(warnings));
}
function formatAndroidSystemSurfaceWarning(
annotations: SnapshotCaptureAnnotations,
): string | undefined {
if (annotations.androidSnapshot?.systemSurfaceOnly !== true) return undefined;
return ANDROID_SYSTEM_SURFACE_DISCLOSURE;
}
function buildSparseIosInteractiveWarnings(params: {
snapshot: SnapshotState;
options: SnapshotCommandOptions;
}): string[] {
if (
params.snapshot.backend !== 'xctest' ||
params.options.interactiveOnly !== true ||
params.snapshot.nodes.length !== 1
) {
return [];
}
const root = params.snapshot.nodes[0];
if (!isApplicationRoot(root)) return [];
if (params.snapshot.producer === 'appium-source') {
return [
'Appium page source exposed only the application root. Descendants may be absent from the acquired hierarchy; use snapshot --raw to inspect the source and verify the app accessibility tree.',
];
}
if (params.snapshot.producer !== undefined && params.snapshot.producer !== 'apple-runner') {
return [];
}
return [
'iOS interactive snapshot exposed only the application root. XCTest accessibility queries can fail to enumerate some simulator UI trees even when screenshots and direct gestures still work. Use screenshot as visual truth, try a scoped/full snapshot for diagnostics, and prefer direct selectors when known.',
];
}
function isApplicationRoot(node: SnapshotNode | undefined): boolean {
if (!node) return false;
return normalizeType(node.type ?? '') === 'application';
}
const MERGED_LEAF_MIN_SEGMENTS = 10;
/**
* A leaf whose label joins many short segments is the signature of a container marked as an
* accessibility element: the platform folds every descendant into one merged node, so the
* children exist on screen but cannot be addressed by assistive tech or automation. This is
* an app-side accessibility bug, not a snapshot failure — the same merged element is all
* VoiceOver users get.
*/
function buildMergedAccessibilityLeafWarnings(nodes: SnapshotState['nodes']): string[] {
const parents = new Set(
nodes.map((node) => node.parentIndex).filter((index) => index !== undefined),
);
return nodes
.filter((node) => {
if (parents.has(node.index)) return false;
const type = node.type?.toLowerCase() ?? '';
if (type.includes('text')) return false;
const label = node.label ?? '';
return label.split(', ').length > MERGED_LEAF_MIN_SEGMENTS;
})
.map((node) => {
const segments = (node.label ?? '').split(', ').length;
const name = node.identifier ? ` (${node.identifier})` : '';
return `@${node.ref} [${node.type ?? 'element'}]${name} merges ~${segments} labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`;
});
}
// fallow-ignore-next-line complexity
function buildEmptyAndroidInteractiveWarnings(params: {
annotations: SnapshotCaptureAnnotations;
snapshot: SnapshotState;
options: SnapshotCommandOptions;
}): string[] {
const analysis = params.annotations.analysis;
if (
params.snapshot.backend !== 'android' ||
params.options.interactiveOnly !== true ||
params.snapshot.nodes.length > 0 ||
!analysis ||
(analysis.rawNodeCount ?? 0) < 12
) {
return [];
}
const warnings = [
`Interactive snapshot is empty after filtering ${analysis.rawNodeCount} raw Android nodes. Likely causes: the app content is not accessibility-visible yet, a transient route change, or depth/filter options hid the target.`,
];
if (
typeof params.options.depth === 'number' &&
typeof analysis.maxDepth === 'number' &&
analysis.maxDepth >= params.options.depth + 2
) {
warnings.push(
`Interactive output is empty at depth ${params.options.depth}; retry without -d.`,
);
}
return warnings;
}
function formatRecentSnapshotDropWarning(params: {
annotations: SnapshotCaptureAnnotations;
snapshot: SnapshotState;
session: CommandSessionRecord | undefined;
capturedAt: number;
runtimeNow: number;
}): string | undefined {
const previousSnapshot = params.session?.snapshot;
if (
!params.annotations.freshness &&
previousSnapshot &&
hasSameSnapshotPresentation(previousSnapshot, params.snapshot) &&
isRecentSnapshot(previousSnapshot, params.capturedAt, params.runtimeNow) &&
isLikelyStaleSnapshotDrop(previousSnapshot.nodes.length, params.snapshot.nodes.length)
) {
return STALE_SNAPSHOT_DROP_WARNING;
}
return undefined;
}
function hasSameSnapshotPresentation(
previousSnapshot: Pick<SnapshotState, 'presentationKey'>,
snapshot: Pick<SnapshotState, 'presentationKey'>,
): boolean {
if (previousSnapshot.presentationKey === undefined || snapshot.presentationKey === undefined) {
return true;
}
return previousSnapshot.presentationKey === snapshot.presentationKey;
}
function isRecentSnapshot(
previousSnapshot: Pick<SnapshotState, 'createdAt'>,
capturedAt: number,
runtimeNow: number,
): boolean {
return [capturedAt, runtimeNow].some((timestamp) => {
const elapsed = timestamp - previousSnapshot.createdAt;
return elapsed >= 0 && elapsed <= 2_000;
});
}
const STALE_SNAPSHOT_DROP_WARNING =
'Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once.';
function formatFreshnessWarnings(
freshness: BackendSnapshotResult['freshness'],
backend: SnapshotState['backend'],
): string[] {
if (!freshness?.staleAfterRetries || backend !== 'android') return [];
if (freshness.reason === 'stuck-route') {
return [
`Recent ${freshness.action} was followed by a nearly identical snapshot after ${freshness.retryCount} automatic retr${freshness.retryCount === 1 ? 'y' : 'ies'}. If you expected navigation or submit, the tree may still be stale. Use screenshot as visual truth, wait briefly, then re-snapshot once.`,
];
}
return freshness.reason === 'sharp-drop' ? [STALE_SNAPSHOT_DROP_WARNING] : [];
}
function isLikelyStaleSnapshotDrop(previousCount: number, currentCount: number): boolean {
if (previousCount < 12) return false;
return currentCount <= Math.floor(previousCount * 0.2);
}