Repository navigation
Expand file tree
/
Copy pathsnapshot-runtime-binding.ts
More file actions
422 lines (402 loc) · 15 KB
/
Copy pathsnapshot-runtime-binding.ts
File metadata and controls
422 lines (402 loc) · 15 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
import type { RuntimeOperationFact } from '@agent-device/contracts/platform-runtime';
import {
type SelectorCaptureRuntimePlan,
type SnapshotRuntimePlan,
resolveSnapshotRuntimePlan,
} from '@agent-device/contracts/platform-runtime-operations';
import type {
CaptureSnapshotInput,
SnapshotResult,
SnapshotRuntimeOperations,
} from '@agent-device/contracts/snapshot-runtime';
import { buildIosOpenCommandHint } from './ios-app-session-hint.ts';
import { buildRuntimeCaptureInput } from './snapshot-runtime-capture-input.ts';
import {
ensureBoundDeviceReady,
type BindDeviceRuntime,
type InspectDeviceRuntimeFacts,
} from './request-runtime-binding.ts';
import type { PlatformResourceCleanup } from './platform-resource-cleanup.ts';
import { SessionStore } from './session-store.ts';
import type { DaemonRequest, DaemonResponse } from './daemon-request.ts';
import type { SessionRef, SessionState } from './session-state.ts';
import {
admitRuntimePlan,
requireRuntimeBinding,
unavailableRuntimeOperationResponse,
unwrapAdmittedRuntimePlan,
type AdmittedRuntimePlan,
} from './session-runtime-admission.ts';
import { resolveSnapshotScope } from './snapshot-capture.ts';
import { resolveSessionDevice } from './snapshot-session.ts';
import {
selectElementTextOperation,
selectFindMutatingOperations,
selectWaitObservationOperations,
type BoundElementRead,
type BoundNativeTextRead,
} from './selector-operation-binding.ts';
import { errorResponse } from '@agent-device/kernel/contracts';
import { AppError } from '@agent-device/kernel/errors';
import { isHandheldAppleDevice } from '@agent-device/kernel/device';
export type SnapshotRuntimeRouteParams = {
req: DaemonRequest;
sessionName: string;
sessionRef?: SessionRef;
logPath: string;
sessionStore: SessionStore;
inspectFacts?: InspectDeviceRuntimeFacts;
bindDevice?: BindDeviceRuntime;
platformResourceCleanup?: PlatformResourceCleanup;
};
type ResolvedSnapshotCaptureRuntime =
| Readonly<{
ok: true;
ref: SessionRef | undefined;
session: SessionState | undefined;
device: SessionState['device'];
snapshotScope: string | undefined;
captureSnapshot: () => Promise<SnapshotResult>;
}>
| Readonly<{ ok: false; response: DaemonResponse }>;
/** A capture operation parametrized by intent, so a polling caller can capture repeatedly
* under the one binding it was admitted for. */
export type BoundSnapshotCapture = (input: CaptureSnapshotInput) => Promise<SnapshotResult>;
/** The owner's live element read, when its facts advertise one. */
export type AdmittedSnapshotCapture =
| Readonly<{
ok: true;
capture: BoundSnapshotCapture;
/**
* The owner's live element read, present only when the caller's plan declared it preferred
* and the admitted owner advertised it. `snapshot`/`diff` plans declare no read, so this is
* simply absent for them — the member is additive and they are unchanged.
*/
readTextAtPoint?: BoundElementRead;
/** A fact-conditional native text observation, present when the owner advertises it. */
findText?: BoundNativeTextRead;
/** A fact-conditional one-sided simple-selector observation. */
/** find's directly-executed mutating legs, present for the find-focus / find-type plans. */
focusPoint?: (
input: import('@agent-device/contracts/focus-runtime').FocusPointInput,
) => Promise<void>;
typeText?: (
input: import('@agent-device/contracts/type-text-runtime').TypeTextInput,
) => Promise<import('@agent-device/contracts/interactor-types').TypeTextBackendResult | void>;
}>
| Readonly<{ ok: false; response: DaemonResponse }>;
/**
* The ONE admit-then-bind path for every request-bound snapshot capture (ADR 0019 §9):
* side-effect-free facts inspection, refusal before any binding, then exactly one bind on
* the admitted device. `snapshot`/`diff` supply the four-way custom-actions plan and the
* selector family the active-app plan; a new consumer supplies a plan and a command name.
*/
export async function admitAndBindSnapshotCapture(
params: Readonly<{
command: string;
device: SessionState['device'];
session: SessionState | undefined;
plan: SnapshotRuntimePlan | SelectorCaptureRuntimePlan;
inspectFacts?: InspectDeviceRuntimeFacts;
bindDevice?: BindDeviceRuntime;
readiness?: boolean;
}>,
): Promise<AdmittedSnapshotCapture> {
const { command, device, session, plan } = params;
const admission = await admitRuntimePlan({ device, plan, inspectFacts: params.inspectFacts });
if (!admission.admitted) {
return {
ok: false,
response: await snapshotPlanUnavailableResponse({
operation: admission.operation,
fact: admission.fact,
session,
device,
command,
}),
};
}
const bound = await bindSnapshotCaptureRuntime(params.bindDevice, admission, params.readiness);
return Object.freeze({
ok: true,
capture: async (input: CaptureSnapshotInput) => await bound.captureSnapshot(input),
...(bound.readTextAtPoint ? { readTextAtPoint: bound.readTextAtPoint } : {}),
...(bound.findText ? { findText: bound.findText } : {}),
...(bound.focusPoint ? { focusPoint: bound.focusPoint } : {}),
...(bound.typeText ? { typeText: bound.typeText } : {}),
});
}
/** Resolves one plan, inspects its owner facts once, then returns one bound capture closure. */
export async function resolveBoundSnapshotCaptureRuntime(
params: SnapshotRuntimeRouteParams,
command: 'snapshot' | 'diff',
): Promise<ResolvedSnapshotCaptureRuntime> {
const { req, sessionName, sessionStore } = params;
const { ref, session, device } = await resolveSessionDevice(
sessionStore,
sessionName,
req.flags,
params.sessionRef,
);
if (
req.flags?.snapshotObserveOnly === true &&
(command !== 'snapshot' || !isHandheldAppleDevice(device) || !session?.appBundleId)
) {
throw new AppError(
'UNSUPPORTED_OPERATION',
'observe-only snapshot requires an iOS or iPadOS app session.',
);
}
const resolvedScope = resolveSnapshotScope(req.flags?.snapshotScope, session);
if (!resolvedScope.ok) return { ok: false, response: resolvedScope };
const bound = await admitAndBindSnapshotCapture({
command,
device,
session,
plan: resolveSnapshotRuntimePlan({
customActions: req.flags?.snapshotCustomActions === true,
hasActiveApp: session?.appBundleId !== undefined,
}),
inspectFacts: params.inspectFacts,
bindDevice: params.bindDevice,
readiness: !session,
});
if (!bound.ok) return bound;
const captureInput = buildRuntimeCaptureInput({
flags: req.flags,
logPath: params.logPath,
meta: req.meta,
session,
snapshotScope: resolvedScope.scope,
});
return Object.freeze({
ok: true,
ref,
session,
device,
snapshotScope: resolvedScope.scope,
captureSnapshot: async () => await bound.capture(captureInput),
});
}
/**
* Binds only an admitted plan, on the device it was admitted for: the token is minted by
* `admitRuntimePlan` alone and unwrapped by exact identity, so nothing that was not admitted —
* a bare plan, a separate device, a look-alike or Proxy — can reach the capture operations.
*/
async function bindSnapshotCaptureRuntime(
bindDevice: BindDeviceRuntime | undefined,
admission: AdmittedRuntimePlan<SnapshotRuntimePlan | SelectorCaptureRuntimePlan>,
readiness: boolean | undefined,
): Promise<
Readonly<{
captureSnapshot(input: CaptureSnapshotInput): Promise<SnapshotResult>;
readTextAtPoint?: BoundElementRead;
findText?: BoundNativeTextRead;
focusPoint?: (
input: import('@agent-device/contracts/focus-runtime').FocusPointInput,
) => Promise<void>;
typeText?: (
input: import('@agent-device/contracts/type-text-runtime').TypeTextInput,
) => Promise<import('@agent-device/contracts/interactor-types').TypeTextBackendResult | void>;
}>
> {
const bind = requireRuntimeBinding(bindDevice);
const bindReady: BindDeviceRuntime = async (device, use) => {
const runtime = await bind(device, use);
if (readiness) await ensureBoundDeviceReady(runtime);
return runtime;
};
const { device, plan } = unwrapAdmittedRuntimePlan(admission);
// One switch, one set of operation selectors. The selector arms reuse the SAME
// `selectActiveAppSnapshot` / `selectSnapshotWithoutActiveApp` the snapshot arms use and only
// add selector operation projection; the discriminants differ solely so the compiler can narrow
// `plan.use` per family. No parallel plan-to-operation dispatch is introduced.
switch (plan.kind) {
case 'active-app': {
const runtime = await bindReady(device, plan.use);
return selectActiveAppSnapshot(runtime);
}
case 'selector-active-app': {
return await bindActiveAppSelectorRuntime(bindReady, device, plan);
}
case 'custom-actions-active-app': {
const runtime = await bindReady(device, plan.use);
return selectCustomActionsSnapshot(runtime);
}
case 'without-active-app': {
const runtime = await bindReady(device, plan.use);
return selectSnapshotWithoutActiveApp(runtime);
}
case 'selector-without-active-app': {
return await bindSelectorRuntimeWithoutActiveApp(bindReady, device, plan);
}
case 'custom-actions-without-active-app': {
const runtime = await bindReady(device, plan.use);
return selectCustomActionsSnapshot(runtime);
}
}
}
type ActiveAppSelectorRuntimePlan = Extract<
SelectorCaptureRuntimePlan,
{ kind: 'selector-active-app' }
>;
async function bindActiveAppSelectorRuntime(
bind: BindDeviceRuntime,
device: SessionState['device'],
plan: ActiveAppSelectorRuntimePlan,
) {
switch (plan.intent) {
case 'capture-only': {
const runtime = await bind(device, plan.use);
return selectActiveAppSnapshot(runtime);
}
case 'element-text': {
const runtime = await bind(device, plan.use);
return {
...selectActiveAppSnapshot(runtime),
...selectElementTextOperation(runtime),
};
}
case 'wait-observation': {
const runtime = await bind(device, plan.use);
return {
...selectActiveAppSnapshot(runtime),
...selectWaitObservationOperations(runtime),
};
}
case 'find-focus': {
const runtime = await bind(device, plan.use);
return {
...selectActiveAppSnapshot(runtime),
...selectFindMutatingOperations(runtime),
};
}
case 'find-type': {
const runtime = await bind(device, plan.use);
return {
...selectActiveAppSnapshot(runtime),
...selectFindMutatingOperations(runtime),
};
}
}
}
type SelectorRuntimePlanWithoutActiveApp = Extract<
SelectorCaptureRuntimePlan,
{ kind: 'selector-without-active-app' }
>;
async function bindSelectorRuntimeWithoutActiveApp(
bind: BindDeviceRuntime,
device: SessionState['device'],
plan: SelectorRuntimePlanWithoutActiveApp,
) {
switch (plan.intent) {
case 'capture-only': {
const runtime = await bind(device, plan.use);
return selectSnapshotWithoutActiveApp(runtime);
}
case 'element-text': {
const runtime = await bind(device, plan.use);
return {
...selectSnapshotWithoutActiveApp(runtime),
...selectElementTextOperation(runtime),
};
}
case 'wait-observation': {
const runtime = await bind(device, plan.use);
return {
...selectSnapshotWithoutActiveApp(runtime),
...selectWaitObservationOperations(runtime),
};
}
case 'find-focus': {
const runtime = await bind(device, plan.use);
return {
...selectSnapshotWithoutActiveApp(runtime),
...selectFindMutatingOperations(runtime),
};
}
case 'find-type': {
const runtime = await bind(device, plan.use);
return {
...selectSnapshotWithoutActiveApp(runtime),
...selectFindMutatingOperations(runtime),
};
}
}
}
type BoundSnapshotOperation<Operation extends keyof SnapshotRuntimeOperations> = Readonly<{
operations: Readonly<Pick<SnapshotRuntimeOperations, Operation>>;
}>;
function selectActiveAppSnapshot(runtime: BoundSnapshotOperation<'captureSnapshot'>) {
return Object.freeze({
captureSnapshot: async (input: CaptureSnapshotInput) =>
await runtime.operations.captureSnapshot(input),
});
}
function selectCustomActionsSnapshot(
runtime: BoundSnapshotOperation<'captureSnapshotWithCustomActions'>,
) {
return Object.freeze({
captureSnapshot: async (input: CaptureSnapshotInput) =>
await runtime.operations.captureSnapshotWithCustomActions(input),
});
}
function selectSnapshotWithoutActiveApp(
runtime: BoundSnapshotOperation<'captureSnapshotWithoutActiveApp'>,
) {
return Object.freeze({
captureSnapshot: async (input: CaptureSnapshotInput) =>
await runtime.operations.captureSnapshotWithoutActiveApp(input),
});
}
type SnapshotPlanUnavailableParams = {
operation: (SnapshotRuntimePlan | SelectorCaptureRuntimePlan)['use']['required'][number];
fact: RuntimeOperationFact;
session: SessionState | undefined;
device: SessionState['device'];
command: string;
};
async function snapshotPlanUnavailableResponse(
params: SnapshotPlanUnavailableParams,
): Promise<DaemonResponse> {
// find's combined plans add the mutating-leg operations: their refusal is the same
// owner-fact wording every runtime admission produces, not the session hint below.
if (
params.operation === 'captureSnapshot' ||
params.operation === 'focusPoint' ||
params.operation === 'typeText'
) {
return unavailableRuntimeOperationResponse(params.command, params.fact)!;
}
if (params.operation === 'captureSnapshotWithCustomActions') {
return snapshotCustomActionsUnavailableResponse(params);
}
const openCommandHint = await buildIosOpenCommandHint(params.device);
return errorResponse(
'SESSION_NOT_FOUND',
`iOS ${params.command} requires an active app session on the target device. Run open first (for example: open --session ${params.session?.name ?? 'sim'} --platform ios --device "<name>" <app>).`,
{
reason: 'ios_app_session_required',
...(openCommandHint ? { hint: openCommandHint } : {}),
},
);
}
function snapshotCustomActionsUnavailableResponse(
params: SnapshotPlanUnavailableParams,
): DaemonResponse {
const unavailableMessage =
params.command === 'diff'
? `--actions requires an iOS simulator: custom actions are read through the private accessibility snapshot backend, which ${params.device.platform}/${params.device.kind} targets do not have.`
: `--actions requires an iOS simulator: custom actions are unavailable on this ${params.device.platform}/${params.device.kind} target.`;
return errorResponse(
'UNSUPPORTED_OPERATION',
unavailableMessage,
{ reason: params.fact.available ? undefined : params.fact.reason },
{
hint:
params.command === 'diff' || params.fact.available || !params.fact.hint
? 'Re-run without --actions, or target an iOS simulator.'
: params.fact.hint,
},
);
}