Repository navigation
Expand file tree
/
Copy pathgestures.ts
More file actions
355 lines (333 loc) · 12.1 KB
/
Copy pathgestures.ts
File metadata and controls
355 lines (333 loc) · 12.1 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
import type { DragGestureInput } from '@agent-device/contracts/gesture-plan-types';
import type {
HoverCommandResult,
LongPressCommandResult,
ResolutionDisclosure,
} from '@agent-device/contracts/interaction';
import {
buildDragGesturePlan,
singlePointerPlanEndpoints,
} from '@agent-device/contracts/gesture-plan';
import { AppError } from '@agent-device/kernel/errors';
import { SELECTOR_PIPELINE_POLICIES } from '@agent-device/selectors/selector-pipeline-policy';
import type { Point, Rect, SnapshotNode } from '@agent-device/kernel/snapshot';
import type { AgentDeviceRuntime, CommandContext } from '../../../runtime-contract.ts';
import { successText } from '@agent-device/kernel/success-text';
import { requireIntInRange } from '@agent-device/kernel/validation';
import { toBackendContext } from '../../runtime-common.ts';
import {
toBackendResult,
type BackendResultEnvelope,
type RuntimeCommand,
} from '../../runtime-types.ts';
import {
applyPostActionObservation,
planPostActionObservation,
type SettlePostActionObservationOptions,
} from './post-action-observation.ts';
import {
assertSupportedInteractionSurface,
captureInteractionSnapshot,
dispatchNativeRefInteraction,
resolveInteractionTarget,
type ExpectedResolvedTarget,
type InteractionTarget,
type ResolvedInteractionTarget,
} from './resolution.ts';
import { resolveVisibleSnapshotViewport } from './viewport.ts';
type DragRecordingTarget = {
selectorChain: string[];
node: SnapshotNode;
preActionNodes: SnapshotNode[];
};
type DragTargetDisclosure = {
selectorChain?: string[];
resolution: ResolutionDisclosure;
};
export type DragCommandOptions = CommandContext & {
gesture: DragGestureInput;
expectedResolvedTargets?: {
source?: ExpectedResolvedTarget;
destination?: ExpectedResolvedTarget;
};
};
export type DragCommandResult = BackendResultEnvelope & {
kind: 'drag';
durationMs: number;
pointerCount: 1;
from: Point;
to: Point;
recording?: {
sourceSelector?: string;
destinationSelector?: string;
sourceTarget?: DragRecordingTarget;
destinationTarget?: DragRecordingTarget;
};
targets: {
source: DragTargetDisclosure;
destination: DragTargetDisclosure;
};
};
/** Resolves the coordinate frame shared by coordinate- and target-authored gestures. */
export async function resolveGestureViewport(
runtime: AgentDeviceRuntime,
options: CommandContext,
): Promise<Rect> {
const backendViewport = await runtime.backend.resolveGestureViewport?.(
toBackendContext(runtime, options),
);
if (backendViewport) return backendViewport;
const capture = await captureInteractionSnapshot(runtime, options, false);
return resolveVisibleSnapshotViewport(capture.snapshot.nodes, 'gesture');
}
export type FocusCommandOptions = CommandContext & {
target: InteractionTarget;
};
export type FocusCommandResult = ResolvedInteractionTarget & BackendResultEnvelope;
export type LongPressCommandOptions = CommandContext & {
target: InteractionTarget;
durationMs?: number;
/** ADR 0012 step 4: replay-only post-resolution guard; see resolution.ts. */
expectedResolvedTarget?: ExpectedResolvedTarget;
} & SettlePostActionObservationOptions;
export type { LongPressCommandResult };
export type HoverCommandOptions = CommandContext & {
target: InteractionTarget;
/** ADR 0012 step 4: replay-only post-resolution guard; see resolution.ts. */
expectedResolvedTarget?: ExpectedResolvedTarget;
} & SettlePostActionObservationOptions;
export type { HoverCommandResult };
export const focusCommand: RuntimeCommand<FocusCommandOptions, FocusCommandResult> = async (
runtime,
options,
): Promise<FocusCommandResult> => {
const resolved = await resolveInteractionTarget(runtime, options, {
action: 'focus',
requireInteractive: true,
pipeline: SELECTOR_PIPELINE_POLICIES.resolvedTarget,
});
if (!runtime.backend.focus) {
throw new AppError('UNSUPPORTED_OPERATION', 'focus is not supported by this backend');
}
const point = requireResolvedPoint(resolved);
const backendResult = await runtime.backend.focus(toBackendContext(runtime, options), point);
const formattedBackendResult = toBackendResult(backendResult);
return {
...resolved,
...(formattedBackendResult ? { backendResult: formattedBackendResult } : {}),
...successText(`Focused (${point.x}, ${point.y})`),
};
};
export const longPressCommand: RuntimeCommand<
LongPressCommandOptions,
LongPressCommandResult
> = async (runtime, options): Promise<LongPressCommandResult> => {
const observation = planPostActionObservation(options);
const resolved = await resolveInteractionTarget(runtime, options, {
action: 'longPress',
requireInteractive: true,
pipeline: SELECTOR_PIPELINE_POLICIES.promotedTarget,
captureEvidenceBaseline: observation.needsPreActionBaseline,
expectedResolvedTarget: options.expectedResolvedTarget,
});
if (!runtime.backend.longPress) {
throw new AppError('UNSUPPORTED_OPERATION', 'longPress is not supported by this backend');
}
const durationMs =
options.durationMs === undefined
? undefined
: requireIntInRange(options.durationMs, 'durationMs', 0, 120_000);
const point = requireResolvedPoint(resolved);
const backendResult = await runtime.backend.longPress(toBackendContext(runtime, options), point, {
durationMs,
});
const formattedBackendResult = toBackendResult(backendResult);
return await applyPostActionObservation(
runtime,
options,
resolved,
{
...resolved,
...(durationMs !== undefined ? { durationMs } : {}),
...(formattedBackendResult ? { backendResult: formattedBackendResult } : {}),
...successText(`Long pressed (${point.x}, ${point.y})`),
},
observation,
);
};
export const hoverCommand: RuntimeCommand<HoverCommandOptions, HoverCommandResult> = async (
runtime,
options,
): Promise<HoverCommandResult> => {
const observation = planPostActionObservation(options);
const nativeRefHover = observation.needsPreActionBaseline
? null
: await maybeHoverRefTarget(runtime, options);
if (nativeRefHover) return nativeRefHover;
// Hover keeps the element it resolved (no hittable-ancestor promotion): the
// pointer only has to enter the matched node's box for its hover state to
// raise, and promoting could move it onto a sibling-owned region.
const resolved = await resolveInteractionTarget(runtime, options, {
action: 'hover',
requireInteractive: false,
pipeline: SELECTOR_PIPELINE_POLICIES.resolvedTarget,
captureEvidenceBaseline: observation.needsPreActionBaseline,
expectedResolvedTarget: options.expectedResolvedTarget,
});
if (!runtime.backend.hover) {
throw new AppError('UNSUPPORTED_OPERATION', 'hover is not supported by this backend');
}
const point = requireResolvedPoint(resolved);
const backendResult = await runtime.backend.hover(toBackendContext(runtime, options), point);
const formattedBackendResult = toBackendResult(backendResult);
return await applyPostActionObservation(
runtime,
options,
resolved,
{
...resolved,
...(formattedBackendResult ? { backendResult: formattedBackendResult } : {}),
...successText(`Hovered (${point.x}, ${point.y})`),
},
observation,
);
};
/**
* ADR 0011 `native-ref` path for hover: on web the ref IS the provider's own
* element handle (`hoverRef`), and the session's ref frame carries no rects,
* so a coordinate hover could not resolve it. Mirrors `maybeTapRefTarget`:
* the shared preflight guards run against the stored node, a guarded replay
* dispatch takes the runtime path, and `--settle` (which needs a pre-action
* baseline) is routed by the caller before reaching here.
*/
async function maybeHoverRefTarget(
runtime: AgentDeviceRuntime,
options: HoverCommandOptions,
): Promise<HoverCommandResult | null> {
if (options.target.kind !== 'ref' || !runtime.backend.hoverTarget) return null;
if (options.expectedResolvedTarget) return null;
const { hoverTarget } = runtime.backend;
return await dispatchNativeRefInteraction(
runtime,
options,
options.target,
'hover',
async (context, refTarget) => await hoverTarget(context, refTarget),
);
}
export const dragCommand: RuntimeCommand<DragCommandOptions, DragCommandResult> = async (
runtime,
options,
) => {
if (!runtime.backend.performGesture) {
throw new AppError('UNSUPPORTED_OPERATION', 'gesture is not supported by this backend');
}
await assertSupportedInteractionSurface(runtime, options, 'drag');
const viewport = await resolveGestureViewport(runtime, options);
const source = await resolveDragTarget(runtime, options, 'source');
const destination = await resolveDragTarget(runtime, options, 'destination');
const plan = buildDragGesturePlan(
{
from: requireResolvedPoint(source),
to: requireResolvedPoint(destination),
sourceHoldMs: options.gesture.sourceHoldMs,
moveMs: options.gesture.moveMs,
destinationHoldMs: options.gesture.destinationHoldMs,
},
viewport,
);
const backendResult = await runtime.backend.performGesture(
toBackendContext(runtime, options),
plan,
);
const formattedBackendResult = toBackendResult(backendResult);
const { start: from, end: to } = singlePointerPlanEndpoints(plan);
return {
kind: 'drag',
durationMs: plan.durationMs,
pointerCount: 1,
from,
to,
targets: {
source: dragTargetDisclosure(source),
destination: dragTargetDisclosure(destination),
},
recording: dragRecordingDetails(source, destination),
...(formattedBackendResult ? { backendResult: formattedBackendResult } : {}),
...successText(`Dragged ${options.gesture.source} to ${options.gesture.destination}`),
};
};
async function resolveDragTarget(
runtime: AgentDeviceRuntime,
options: DragCommandOptions,
endpoint: 'source' | 'destination',
): Promise<ResolvedInteractionTarget> {
const token = options.gesture[endpoint];
return await resolveInteractionTarget(
runtime,
{
...options,
target: token.startsWith('@')
? { kind: 'ref', ref: token }
: { kind: 'selector', selector: token },
},
{
action: 'drag',
requireInteractive: false,
pipeline: SELECTOR_PIPELINE_POLICIES.resolvedTarget,
expectedResolvedTarget: options.expectedResolvedTargets?.[endpoint],
replayTargetRole: endpoint,
},
);
}
function dragTargetDisclosure(target: ResolvedInteractionTarget): DragTargetDisclosure {
if (target.kind === 'point' || !target.resolution) {
throw new AppError('COMMAND_FAILED', 'gesture drag target resolution was not disclosed');
}
const selectorChain = 'selectorChain' in target ? target.selectorChain : undefined;
return {
...(selectorChain?.length ? { selectorChain } : {}),
resolution: target.resolution,
};
}
function dragRecordingDetails(
source: ResolvedInteractionTarget,
destination: ResolvedInteractionTarget,
): NonNullable<DragCommandResult['recording']> {
const sourceSelector = selectorExpression(source);
const destinationSelector = selectorExpression(destination);
const sourceTarget = recordedDragTarget(source);
const destinationTarget = recordedDragTarget(destination);
return {
...(sourceSelector ? { sourceSelector } : {}),
...(destinationSelector ? { destinationSelector } : {}),
...(sourceTarget ? { sourceTarget } : {}),
...(destinationTarget ? { destinationTarget } : {}),
};
}
function selectorExpression(target: ResolvedInteractionTarget): string | undefined {
return 'selectorChain' in target && target.selectorChain?.length
? target.selectorChain.join(' || ')
: undefined;
}
function recordedDragTarget(target: ResolvedInteractionTarget): DragRecordingTarget | undefined {
if (
!('selectorChain' in target) ||
!target.selectorChain?.length ||
!target.node ||
!target.preAction
) {
return undefined;
}
return {
selectorChain: target.selectorChain,
node: target.node,
preActionNodes: target.preAction.nodes,
};
}
function requireResolvedPoint(result: { point?: Point }): Point {
if (!result.point) {
throw new AppError('COMMAND_FAILED', 'Interaction target resolved without coordinates');
}
return result.point;
}