Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/ad-script/src/internal/__tests__/script.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,16 @@ test('a recorded gesture tap round-trips its contacts and series flags', () => {
assert.deepEqual(parsed?.flags, { holdMs: 40, count: 3, pauseMs: 100 });
});

test('a recorded gesture path keeps its JSON argument through the script line', () => {
const json =
'{"durationMs":500,"samples":[{"offsetMs":0,"point":{"x":1,"y":2}},{"offsetMs":500,"point":{"x":1,"y":4}}]}';
const line = formatReplayScriptForTest([
{ ts: 0, command: 'gesture', positionals: ['path', json], flags: {} },
]);
const [parsed] = parseReplayScriptDetailed(line).actions;
assert.deepEqual(parsed?.positionals, ['path', json]);
});

test('an .ad gesture tap with an odd coordinate count is refused before replay', () => {
assert.throws(() => parseReplayScriptDetailed('gesture tap 80 300 200\n'), {
code: 'INVALID_ARGS',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ function centroidAt(

function gestureMessage(input: GestureSemanticInput, from: Point, to: Point): string {
switch (input.intent) {
case 'path':
return `Moved one contact through ${input.samples.length} samples over ${input.durationMs} ms`;
case 'pan': {
const origin = 'preset' in input ? from : input.origin;
const delta = 'preset' in input ? { x: to.x - from.x, y: to.y - from.y } : input.delta;
Expand Down
2 changes: 1 addition & 1 deletion packages/command-surface/src/command-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export function objectSchema(
};
}

function pointSchema(description: string): JsonSchema {
export function pointSchema(description: string): JsonSchema {
return {
type: 'object',
description,
Expand Down
10 changes: 5 additions & 5 deletions packages/command-surface/src/interaction/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,10 +458,10 @@ const interactionCliSchemas = {
],
},
gesture: {
usageOverride: 'gesture <pan|fling|swipe|pinch|rotate|transform|tap|drag> ...',
usageOverride: 'gesture <pan|fling|swipe|pinch|rotate|transform|tap|drag|path> ...',
usageFlags: [],
listUsageOverride: 'gesture <pan|fling|swipe|pinch|rotate|transform|tap|drag> ...',
positionalArgs: ['pan|fling|swipe|pinch|rotate|transform|tap|drag', 'args?'],
listUsageOverride: 'gesture <pan|fling|swipe|pinch|rotate|transform|tap|drag|path> ...',
positionalArgs: ['pan|fling|swipe|pinch|rotate|transform|tap|drag|path', 'args?'],
allowsExtraPositionals: true,
allowedFlags: [...GESTURE_CLI_FLAGS, ...postActionObservationCliFlags('gesture')],
flagsByAction: GESTURE_FLAGS_BY_ACTION,
Expand Down Expand Up @@ -692,10 +692,10 @@ const gestureCommandFacet = defineCommandFacet({
name: 'gesture',
effect: 'destructive',
text: {
summary: 'Run pan, fling, swipe, pinch, rotate, transform, tap, or drag gestures',
summary: 'Run pan, fling, swipe, pinch, rotate, transform, tap, drag, or path',
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
searchHint: 'reorder zoom multi-touch',
cliDetail:
'Argument shapes: pan <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance], swipe <left|right|left-edge|right-edge|split-view-left|split-view-right|split-view-exit>, pinch <scale> [x y | @ref|selector] (centered on the screen when neither is given), rotate <degrees> [x] [y], transform <x> <y> <dx> <dy> <scale> <degrees> [durationMs], tap <x1> <y1> <x2> <y2> [... <x5> <y5>] [--hold-ms <ms>] [--count <n>] [--pause-ms <ms>], or drag <source-selector|pinned-ref> <destination-selector|pinned-ref> [sourceHoldMs] [moveMs] [destinationHoldMs]; drag holds the source down first (800 ms by default) before moving, which is what engages a reorder handle. For command plans, output only command lines. Android transform verification should use all app-observable effects, for example wait text "pan changed yes", wait text "pinch changed yes", and wait text "rotate changed yes", not exact transform values. Use --settle to wait for the UI to go quiet after the last repetition and compare with the last observed tree. gesture swipe accepts --no-post-gesture-stabilization to skip the stabilization wait before the next read, for a caller whose own polling verifies the screen.',
'Argument shapes: pan <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance], swipe <left|right|left-edge|right-edge|split-view-left|split-view-right|split-view-exit>, pinch <scale> [x y | @ref|selector] (centered on the screen when neither is given), rotate <degrees> [x] [y], transform <x> <y> <dx> <dy> <scale> <degrees> [durationMs], tap <x1> <y1> <x2> <y2> [... <x5> <y5>] [--hold-ms <ms>] [--count <n>] [--pause-ms <ms>], drag <source-selector|pinned-ref> <destination-selector|pinned-ref> [sourceHoldMs] [moveMs] [destinationHoldMs], or path \'<json>\' with durationMs and 2 to 256 samples of {offsetMs, point}; drag holds the source down first (800 ms by default) before moving, which is what engages a reorder handle. For command plans, output only command lines. Android transform verification should use all app-observable effects, for example wait text "pan changed yes", wait text "pinch changed yes", and wait text "rotate changed yes", not exact transform values. Use --settle to wait for the UI to go quiet after the last repetition and compare with the last observed tree. gesture swipe accepts --no-post-gesture-stabilization to skip the stabilization wait before the next read, for a caller whose own polling verifies the screen.',
},
metadata: metadata('gesture'),
run: (client, input) =>
Expand Down
22 changes: 20 additions & 2 deletions packages/command-surface/src/interaction/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
enumField,
integerField,
interactionTargetFields,
jsonSchemaField,
numberField,
operatorField,
pointArrayField,
Expand All @@ -44,6 +45,7 @@ import {
type CommandFieldMap,
type InferCommandInput,
type TargetedInput,
pointSchema,
} from '../command-input.ts';
import { readCommonInput, type CommonCommandInput } from '../common-input-fields.ts';
import { optionalBoolean, readInputRecord } from '../input-readers.ts';
Expand Down Expand Up @@ -83,7 +85,7 @@ const interactionCommandDescriptions = {
is: 'Check whether a selector satisfies a UI predicate such as visible, hidden, exists, absent, editable, selected, checked, focused, or text. `absent` passes only when one readable, complete, settled, unscoped, full-depth accessibility capture has zero matches. This command checks the current condition without polling.',
find: 'Find by text/label/value/role/id and run action; the action defaults to click. The role locator matches snapshot kind vocabulary (button, text, text-field, switch, ...); pre-reconciliation leaf spellings (statictext, edittext, textview) stay accepted on the nodes that carried them during a deprecation window. The focus and type actions aim at a text field: the match or the field holding it, even beside other fields, or else the one enabled on-screen field inside the match. Several enabled on-screen fields inside the match refuse with AMBIGUOUS_MATCH and the field candidates, and a disabled target refuses with reason target_disabled. Web text boxes are not recognized as text fields.',
gesture:
'Perform a structured pan, fling, swipe, pinch, rotate, transform, tap, or drag gesture. Each gesture kind has its own inputs. A tap touches 2 to 5 points at once; count and pauseMs control repetition. A drag takes a source and a destination ref or selector and holds the source down for 800 ms by default before carrying it over, which is how a list item changes position or a drop target is hit. Settle observes the UI once after the last repetition and compares with the last observed tree.',
'Perform a structured pan, fling, swipe, pinch, rotate, transform, tap, drag, or path gesture. Each gesture kind has its own inputs. A tap touches 2 to 5 points at once; count and pauseMs control repetition. A drag takes a source and a destination ref or selector and holds the source down for 800 ms by default before carrying it over, which is how a list item changes position or a drop target is hit. A path moves one contact through timed samples, so it can reverse, pause, or curve; it works where drag works. Settle observes the UI once after the last repetition and compares with the last observed tree.',
} as const;

type InteractionCommandName = keyof typeof interactionCommandDescriptions;
Expand Down Expand Up @@ -242,7 +244,23 @@ const gestureFields = {
'Element to pinch, as an @ref or selector; the pinch centers on it, in place of origin.',
),
degrees: numberField('Rotation in degrees.'),
durationMs: integerField('Pan/transform duration.', { min: 16, max: 10_000 }),
durationMs: integerField('Pan, transform, or path duration.', { min: 16, max: 10_000 }),
samples: jsonSchemaField<unknown>({
type: 'array',
description:
'Path samples for one contact: 2 to 256 points with whole-millisecond offsetMs from touch-down. Offsets start at 0, strictly increase, and end at durationMs. A repeated point at a later offset holds the contact there.',
items: {
type: 'object',
properties: {
offsetMs: { type: 'integer', minimum: 0 },
point: pointSchema('Contact position at offsetMs.'),
},
required: ['offsetMs', 'point'],
additionalProperties: false,
},
minItems: 2,
maxItems: 256,
}),
pointerCount: integerField('Pan touch pointer count (1 or 2).', { min: 1, max: 2 }),
points: pointArrayField('Tap contact points, held together for holdMs.', {
min: GESTURE_TAP_MIN_CONTACTS,
Expand Down
15 changes: 13 additions & 2 deletions packages/contracts/src/gesture-input.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Point } from '@agent-device/kernel/snapshot';
import type { ScrollDirection, SwipePreset } from './scroll-gesture.ts';
import type { GesturePointerCount } from './gesture-plan-types.ts';
import type { GesturePointerCount, PointerTrajectorySample } from './gesture-plan-types.ts';

export const COORDINATE_GESTURE_KINDS = [
'pan',
Expand All @@ -11,7 +11,7 @@ export const COORDINATE_GESTURE_KINDS = [
'transform',
'tap',
] as const;
export const GESTURE_KINDS = [...COORDINATE_GESTURE_KINDS, 'drag'] as const;
export const GESTURE_KINDS = [...COORDINATE_GESTURE_KINDS, 'drag', 'path'] as const;

export type DragGesturePayload = {
kind: 'drag';
Expand Down Expand Up @@ -75,7 +75,18 @@ export type TapGesturePayload = {
pauseMs?: number;
};

/**
* One contact that follows caller-authored samples. Each sample's offset is measured from touch-down,
* and a repeated point at a later offset holds the contact there.
*/
export type PathGesturePayload = {
kind: 'path';
durationMs: number;
samples: readonly PointerTrajectorySample[];
};

export type GesturePayload =
| PathGesturePayload
| PanGesturePayload
| FlingGesturePayload
| SwipeGesturePayload
Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/src/gesture-plan-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const DEFAULT_DRAG_SOURCE_HOLD_MS = 800;
export const DEFAULT_DRAG_MOVE_MS = 500;
export const DEFAULT_DRAG_DESTINATION_HOLD_MS = 0;

export type GestureIntent = 'fling' | 'pan' | 'pinch' | 'rotate' | 'transform' | 'tap';
export type GestureIntent = 'path' | 'fling' | 'pan' | 'pinch' | 'rotate' | 'transform' | 'tap';

export type DragGestureInput = {
intent: 'drag';
Expand All @@ -42,6 +42,7 @@ export type TargetedPinchGestureInput = {
export type GestureExecutionProfile = 'endpoint-hold' | 'timed-pan';

export type GestureSemanticInput =
| { intent: 'path'; durationMs: number; samples: readonly PointerTrajectorySample[] }
| { intent: 'fling'; from: Point; to: Point }
| { intent: 'fling'; preset: SwipePreset }
| {
Expand Down
11 changes: 11 additions & 0 deletions packages/contracts/src/platform-runtime-operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,14 @@ test('a held pan needs the target-authored-drag tier; an unheld one stays on pla
assert.equal(resolveGestureRuntimePlan({ ...pan, holdMs: 0 }).tier, 'plan');
assert.equal(resolveGestureRuntimePlan(pan).tier, 'plan');
});

test('a path needs the target-authored-drag tier, which keeps its intermediate samples', () => {
const samples = [
{ offsetMs: 0, point: { x: 10, y: 20 } },
{ offsetMs: 100, point: { x: 10, y: 120 } },
] as const;
assert.equal(
resolveGestureRuntimePlan({ intent: 'path', durationMs: 100, samples }).tier,
'target-authored-drag',
);
});
2 changes: 2 additions & 0 deletions packages/contracts/src/platform-runtime-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,8 @@ function gestureRuntimeTier(input: GestureCommandInput): GestureRuntimeTier {
// drops them, so admit it through the tier whose fact promises hold-preserving execution and let
// backends without that fact refuse before dispatch.
if (input.intent === 'pan' && (input.holdMs ?? 0) > 0) return 'target-authored-drag';
// An authored path lives in its intermediate samples for the same reason.
if (input.intent === 'path') return 'target-authored-drag';
if (isMultiTouchGesture(input)) return 'multi-touch';
// A direction-authored fling carries speed semantics a coordinate fling does not, which is the
// one thing the Linux drag primitive cannot reproduce.
Expand Down
44 changes: 43 additions & 1 deletion packages/contracts/src/scroll-gesture.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import type { GestureContactOrigin } from './gesture-plan-types.ts';
import type {
GestureContactOrigin,
PointerTrajectorySample,
SinglePointerTrajectory,
} from './gesture-plan-types.ts';
import { SCROLL_REASONS } from './scroll-reasons.ts';
import { defineStringEnum } from './string-enum.ts';
import { isViewportRootNode } from './snapshot-visibility.ts';
Expand Down Expand Up @@ -600,3 +604,41 @@ function isMeasurableRect(rect: Rect): boolean {
rect.height > 0
);
}

const PATH_GESTURE_MAX_SAMPLES = 256;

/**
* Checks an authored path timeline. The Android helper and WebDriver take whole-millisecond offsets,
* so a fractional offset is refused here instead of failing after dispatch.
*/
export function pathTimeline(
samples: readonly PointerTrajectorySample[],
durationMs: number,
): SinglePointerTrajectory['samples'] {
if (samples.length < 2 || samples.length > PATH_GESTURE_MAX_SAMPLES) {
throw new AppError(
'INVALID_ARGS',
`gesture path requires 2 to ${PATH_GESTURE_MAX_SAMPLES} samples`,
{ sampleCount: samples.length },
);
}
for (const [index, sample] of samples.entries()) {
const ordered =
index === 0 ? sample.offsetMs === 0 : sample.offsetMs > samples[index - 1]!.offsetMs;
if (!ordered || !Number.isInteger(sample.offsetMs)) {
throw new AppError(
'INVALID_ARGS',
'gesture path sample offsets must be whole milliseconds that start at 0 and strictly increase',
{ index, offsetMs: sample.offsetMs },
);
}
}
if (samples.at(-1)!.offsetMs !== durationMs) {
throw new AppError('INVALID_ARGS', 'gesture path final sample offset must equal durationMs', {
durationMs,
finalOffsetMs: samples.at(-1)!.offsetMs,
});
}
const [first, second, ...rest] = samples;
return [first!, second!, ...rest];
}
1 change: 1 addition & 0 deletions packages/daemon/src/core/gesture-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ function gestureViewportScope(input: GestureCommandInput): GestureViewportScope
if (input.intent === 'fling' && 'preset' in input && input.preset === 'split-view-exit') {
return 'display';
}
if (input.intent === 'path') return 'including-keyboard';
if (
input.intent === 'pan' &&
(input.pointerCount ?? 1) === 1 &&
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { expect, test } from 'vitest';
import { buildGesturePlan } from '@agent-device/gestures/gesture-plan';
import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon-command-surface';
import { daemonPlatformServicesFixture } from '../../../__tests__/support/platform-services-fixture.ts';
import { makeIosSession } from '../../../__tests__/support/session-factories.ts';
import { makeSessionStore } from '../../../__tests__/support/store-factory.ts';
import { touchCreateCommandSurface } from '../../../__tests__/support/touch-command-surface-fake.ts';
import { handleInteractionCommands } from '../index.ts';
import { gestureRuntimeBindingsFixture } from './__tests__/gesture-runtime-bindings.fixtures.ts';

const reversal = {
kind: 'path',
durationMs: 1000,
samples: [
{ offsetMs: 0, point: { x: 100, y: 160 } },
{ offsetMs: 400, point: { x: 100, y: 300 } },
{ offsetMs: 800, point: { x: 100, y: 160 } },
{ offsetMs: 1000, point: { x: 100, y: 160 } },
],
};

/** Plans and performs a coordinate gesture through the daemon's bound backend, as the runtime does. */
function executingSurface(sessionName: string): CreateDaemonCommandSurface {
return async (config) => {
const surface = await touchCreateCommandSurface(config);
return {
...surface,
interactions: {
...surface.interactions,
gesture: async (options) => {
if ('intent' in options.gesture && options.gesture.intent === 'path') {
const context = { session: sessionName };
const viewport = await config.backend.resolveGestureViewport!(context);
if (!viewport) throw new Error('expected a gesture viewport');
const plan = buildGesturePlan(options.gesture, viewport, 'ios');
await config.backend.performGesture!(context, plan);
}
return await surface.interactions.gesture(options);
},
},
};
};
}

async function runPath(input: Record<string, unknown>, gestures = gestureRuntimeBindingsFixture()) {
const sessionName = 'gesture-path';
const sessionStore = makeSessionStore();
const session = makeIosSession(sessionName, { appBundleId: 'com.example.app' });
sessionStore.publish(sessionName, session);
const response = await handleInteractionCommands({
createCommandSurface: executingSurface(sessionName),
platformServices: daemonPlatformServicesFixture(),
req: {
token: 't',
session: sessionName,
command: 'gesture',
positionals: [],
flags: {},
input,
},
sessionName,
sessionStore,
captureSnapshotForSession: async ({ session: s }) => s.snapshot!,
contextFromFlags: () => ({}),
inspectFacts: gestures.inspectFacts,
bindDevice: gestures.bindDevice,
});
return { response, session, gestures };
}

test('a path dispatches every authored sample through the target-authored-drag tier', async () => {
const { response, gestures } = await runPath(reversal);

expect(response).toMatchObject({ ok: true });
expect(gestures.performGesturePlan).not.toHaveBeenCalled();
expect(gestures.performTargetAuthoredDrag).toHaveBeenCalledOnce();
const { plan } = gestures.performTargetAuthoredDrag.mock.calls[0]![0];
expect(plan).toMatchObject({
topology: 'single',
executionProfile: 'timed-pan',
durationMs: 1000,
});
expect(plan.pointers[0]?.samples).toEqual(reversal.samples);
expect(gestures.gestureViewport.mock.calls[0]?.[0].scope).toBe('including-keyboard');
});

test('a backend without the target-authored-drag tier refuses a path before dispatch', async () => {
const gestures = gestureRuntimeBindingsFixture({ unavailable: ['performTargetAuthoredDrag'] });
const { response } = await runPath(reversal, gestures);

expect(response?.ok).toBe(false);
if (response && !response.ok) expect(response.error.code).toBe('UNSUPPORTED_OPERATION');
expect(gestures.performGesturePlan).not.toHaveBeenCalled();
});

test('a recorded path keeps every sample for replay', async () => {
const { session } = await runPath(reversal);

const [kind, payload] = session.actions[0]?.positionals ?? [];
expect(kind).toBe('path');
expect(JSON.parse(payload!)).toEqual({
durationMs: reversal.durationMs,
samples: reversal.samples,
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ function resolveExecutionProfile(
): GestureExecutionProfile | undefined {
if (gesture.intent === 'fling') return 'endpoint-hold';
if (gesture.intent === 'pan') return gesture.executionProfile ?? 'timed-pan';
if (gesture.intent === 'drag') return 'timed-pan';
if (gesture.intent === 'drag' || gesture.intent === 'path') return 'timed-pan';
return undefined;
}

Expand Down
Loading
Loading