Repository navigation
Expand file tree
/
Copy pathsnapshot-capture.ts
More file actions
199 lines (189 loc) · 7.32 KB
/
Copy pathsnapshot-capture.ts
File metadata and controls
199 lines (189 loc) · 7.32 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
import type { CommandFlags } from '@agent-device/contracts/command';
import {
copySnapshotClickabilityEvidence,
recordSnapshotTiming,
snapshotCaptureAnnotationsFrom,
type SnapshotCaptureAnnotations,
} from '@agent-device/contracts/capture';
import { publicPlatformString } from '@agent-device/kernel/device';
import {
findNodeByRef,
normalizeRef,
SNAPSHOT_CAPTURE_OPTION_KEYS,
snapshotOptionsFromFlags,
type RawSnapshotNode,
type SnapshotCaptureProvenance,
type SnapshotKeyboardBandFact,
type SnapshotState,
} from '@agent-device/kernel/snapshot';
import { resolveRefLabel } from '@agent-device/capture-kit/snapshot-node-lookup';
import { captureSnapshotWithInteractor } from './snapshot-interactor-capture.ts';
import { buildSnapshotState } from '@agent-device/capture-kit/snapshot-state';
import { clearAndroidSnapshotFreshness } from './session-snapshot-freshness.ts';
import type { SnapshotFreshnessMode } from '@agent-device/capture-kit/snapshot-freshness';
import { contextFromFlags } from './context.ts';
import { resolveDeferredInteractionOutcome } from './deferred-interaction-outcome.ts';
import { createInteractionRetryTap } from './interaction-retry-tap.ts';
import type { SessionState } from './session-state.ts';
import type { BindDeviceRuntime, InspectDeviceRuntimeFacts } from './request-runtime-binding.ts';
import { type DaemonFailureResponse, errorResponse } from '@agent-device/kernel/contracts';
type CaptureSnapshotParams = {
device: SessionState['device'];
session: SessionState | undefined;
flags: CommandFlags | undefined;
includeRects?: boolean;
outPath?: string;
logPath: string;
snapshotScope?: string;
androidFreshnessMode?: SnapshotFreshnessMode;
signal?: AbortSignal;
/**
* Request-bound platform capture. Migrated callers inject the selected
* runtime operation; legacy consumers keep the existing interactor path
* until their own command descriptor cuts over.
*/
captureData?: () => Promise<SnapshotData>;
/**
* The pending-outcome retry re-fires a bound `tapPoint` (R48), so a capture that can settle a
* deferred interaction outcome carries the request's own runtime bindings and builds the retry
* seam from them. A caller that has none simply never retries.
*/
inspectFacts?: InspectDeviceRuntimeFacts;
bindDevice?: BindDeviceRuntime;
};
type SnapshotData = {
nodes?: RawSnapshotNode[];
truncated?: boolean;
quality?: unknown;
/** The keyboard band the capture's producer measured (#2660), carried to the state guards read. */
keyboard?: SnapshotKeyboardBandFact;
} & Omit<SnapshotCaptureAnnotations, 'quality'> &
SnapshotCaptureProvenance;
type SnapshotAttempt = {
data: SnapshotData;
snapshot: SnapshotState;
annotations: SnapshotCaptureAnnotations;
};
type CaptureSnapshotResult = {
snapshot: SnapshotState;
} & SnapshotCaptureAnnotations;
export async function captureSnapshot(
params: CaptureSnapshotParams,
): Promise<CaptureSnapshotResult> {
const deferred = await resolveDeferredInteractionOutcome({
session: params.session,
device: params.device,
logPath: params.logPath,
interactiveOnly: params.flags?.snapshotInteractiveOnly === true,
androidFreshnessMode: params.androidFreshnessMode,
capture: () => captureSnapshotAttempt(params),
retryTap: createInteractionRetryTap(params),
});
if (deferred) return deferred;
const latest = await captureSnapshotAttempt(params);
clearAndroidSnapshotFreshness(params.session);
return {
snapshot: latest.snapshot,
...latest.annotations,
};
}
export async function captureSnapshotData(params: CaptureSnapshotParams): Promise<SnapshotData> {
if (params.captureData) return await params.captureData();
const { device, session, logPath } = params;
const context = contextFromFlags(
logPath,
resolveSnapshotStateFlags(params),
session?.appBundleId,
session?.trace?.outPath,
);
return await captureSnapshotWithInteractor({
device,
runnerContext: {
requestId: context.requestId,
signal: params.signal,
appBundleId: context.appBundleId,
verbose: context.verbose,
logPath: context.logPath,
traceLogPath: context.traceLogPath,
iosXctestrunFile: context.iosXctestrunFile,
iosXctestDerivedDataPath: context.iosXctestDerivedDataPath,
iosXctestEnvDir: context.iosXctestEnvDir,
runnerLeaseContext: context.runnerLeaseContext,
},
options: {
appBundleId: context.appBundleId,
signal: params.signal,
...snapshotOptionsFromFlags(context, SNAPSHOT_CAPTURE_OPTION_KEYS),
includeRects: params.includeRects,
surface: session?.surface,
},
});
}
async function captureSnapshotAttempt(params: CaptureSnapshotParams): Promise<SnapshotAttempt> {
const startedAt = Date.now();
const data = await captureSnapshotData(params);
recordSnapshotTiming(params.session, {
durationMs: Date.now() - startedAt,
backend: data.backend,
// approach (b): emit the PUBLIC leaf platform (ios/macos), never the internal `apple`.
platform: publicPlatformString(params.device),
});
const annotations = snapshotCaptureAnnotationsFrom(data);
const snapshot = copySnapshotClickabilityEvidence(
data,
buildSnapshotState(data, resolveSnapshotStateFlags(params)),
);
// The one seam where snapshot state and capture annotations meet: consumers that only keep the
// SnapshotState (selector-backed find/wait, session-stored snapshots) must still learn that the
// capture is an occluding system surface, so the disclosure is not lost with the annotations.
if (annotations.androidSnapshot?.systemSurfaceOnly === true) {
snapshot.systemSurfaceOnly = true;
}
return { data, snapshot, annotations };
}
/**
* The ONE effective scope of a capture, handed to both the platform capture and
* `buildSnapshotState`. Backends that resolve scope inside their projection (android) get no
* post-wire pass, so the two sides must see the same value: an explicit `snapshotScope` param
* overrides the flag, an absent param must never erase it (#1832 C2).
*/
function resolveSnapshotStateFlags(
params: Pick<CaptureSnapshotParams, 'flags' | 'snapshotScope'>,
): CaptureSnapshotParams['flags'] {
if (params.snapshotScope === undefined) {
return params.flags;
}
return {
...params.flags,
snapshotScope: params.snapshotScope,
};
}
export function resolveSnapshotScope(
snapshotScope: string | undefined,
session: SessionState | undefined,
): { ok: true; scope?: string } | DaemonFailureResponse {
if (!snapshotScope || !snapshotScope.trim().startsWith('@')) {
return { ok: true, scope: snapshotScope };
}
if (!session?.snapshot) {
return errorResponse('INVALID_ARGS', 'Ref scope requires an existing snapshot in session.');
}
const ref = normalizeRef(snapshotScope.trim());
if (!ref) {
return errorResponse('INVALID_ARGS', `Invalid ref scope: ${snapshotScope}`);
}
const candidates = [
session.snapshot,
...(session.snapshotScopeSource ? [session.snapshotScopeSource] : []),
];
let resolved: string | undefined;
for (const snapshot of candidates) {
const node = findNodeByRef(snapshot.nodes, ref);
resolved = node ? resolveRefLabel(node, snapshot.nodes) : undefined;
if (resolved) break;
}
if (!resolved) {
return errorResponse('COMMAND_FAILED', `Ref ${snapshotScope} not found or has no label`);
}
return { ok: true, scope: resolved };
}